简体   繁体   English

如何在Go中编写通用处理程序?

[英]How to write a generic handler in Go?

I need to create a HTTP Handler for a REST API. 我需要为REST API创建一个HTTP处理程序。

This REST API have many different objects that are stored in a database (MongoDB in my case). 该REST API具有许多不同的对象,这些对象存储在数据库中(在我的情况下为MongoDB)。

Currently, I need to write one handler per action per object. 当前,我需要为每个对象的每个动作编写一个处理程序。

I would like to find a way like it's possible with Generics to write a generic handler that could handle a specific action but for any kind of object (As basically it's just CRUD in most of the case) 我想找到一种方法,让Generics可以编写一个通用处理程序,该处理程序可以处理特定的动作,但可以处理任何类型的对象(基本上,在大多数情况下,这只是CRUD)

How can I do this ? 我怎样才能做到这一点 ?

Here is examples of Handlers I would like to transform into a generic one : 这是我想转换为通用处理程序的处理程序的示例:

func IngredientIndex(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json; charset=UTF-8")
    db := r.Context().Value("Database").(*mgo.Database)
    ingredients := []data.Ingredient{}
    err := db.C("ingredients").Find(bson.M{}).All(&ingredients)
    if err != nil {
        panic(err)
    }
    json.NewEncoder(w).Encode(ingredients)
}

func IngredientGet(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json; charset=UTF-8")
    vars := mux.Vars(r)
    logger := r.Context().Value("Logger").(zap.Logger)
    db := r.Context().Value("Database").(*mgo.Database)
    ingredient := data.Ingredient{}
    err := db.C("ingredients").Find(bson.M{"_id": bson.ObjectIdHex(vars["id"])}).One(&ingredient)
    if err != nil {
        w.WriteHeader(404)
        logger.Info("Fail to find entity", zap.Error(err))
    } else {
        json.NewEncoder(w).Encode(ingredient)
    }
}

Basically I would need a handler like this (This is my tentative that doesn't work) : 基本上,我需要这样的处理程序(这是我的尝试性的,不起作用):

func ObjectIndex(collection string, container interface{}) func(http.ResponseWriter, *http.Request) {
    return func(w http.ResponseWriter, r *http.Request) {
        w.Header().Set("Content-Type", "application/json; charset=UTF-8")
        db := r.Context().Value("Database").(*mgo.Database)
        objects := container
        err := db.C(collection).Find(bson.M{}).All(&objects)
        if err != nil {
            panic(err)
        }
        json.NewEncoder(w).Encode(objects)
    }

How can I do that ? 我怎样才能做到这一点 ?

Use the reflect package to create a new container on each invocation: 使用反射包在每次调用时创建一个新容器:

func ObjectIndex(collection string, container interface{}) func(http.ResponseWriter, *http.Request) {
  t := reflect.TypeOf(container)
  return func(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json; charset=UTF-8")
    db := r.Context().Value("Database").(*mgo.Database)
    objects := reflect.New(t).Interface()
    err := db.C(collection).Find(bson.M{}).All(objects)
    if err != nil {
        panic(err)
    }
    json.NewEncoder(w).Encode(objects)
}

Call it like this: 这样称呼它:

h := ObjectIndex("ingredients", data.Ingredient{})

assuming that data.Indgredient is a slice type. 假设data.Indgredient是切片类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM