gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 01:58:23 27 4
gpt4 key购买 nike

我需要为 REST API 创建一个 HTTP 处理程序。

这个 REST API 有许多不同的对象存储在数据库中(在我的例子中是 MongoDB)。

目前,我需要为每个对象的每个操作编写一个处理程序。

我想找到一种方法,就像使用 Generics 一样可以编写一个通用处理程序,该处理程序可以处理特定的操作,但适用于任何类型的对象(因为基本上在大多数情况下它只是 CRUD)

我该怎么做?

以下是我想转换为通用处理程序的示例:

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)
}
}

基本上我需要一个这样的处理程序(这是我暂定的,但行不通):

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)
}

我该怎么做?

最佳答案

使用反射包在每次调用时创建一个新容器:

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)
}

这样调用它:

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

假设 data.Indgredient 是 slice 类型。

关于rest - 如何在 Go 中编写通用处理程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41186856/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com