3 回答
TA贡献1797条经验 获得超4个赞
你可以这样做:
func List(list interface{}, w http.ResponseWriter, r *http.Request,) {
db.Find(list)
json.NewEncoder(w).Encode(list)
}
TA贡献1951条经验 获得超3个赞
鉴于您正在调用,db.Find(&list)我假设它们共享一个通用接口。在这种情况下,您可以像这样包装您的处理程序调用;
func ListHandler(list <YOUR_INTERFACE>) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
db.Find(&list)
json.NewEncoder(w).Encode(list)
}
}
在您的电话中;
http.HandleFunc("/user/list", ListHandler([]models.User{}))
http.HandleFunc("/product/list", ListHandler([]models.Product{}))
http.HandleFunc("/order/list", ListHandler([]models.Order{}))
TA贡献1798条经验 获得超3个赞
如果您将模型类型作为请求参数传递,则应该这样做(包括错误处理):
func List(w http.ResponseWriter, r *http.Request) {
var list interface{}
switch r.FormValue("model") {
case "user":
list = new([]models.User)
case "product":
list = new([]models.Product)
case "order":
list = new([]models.Order)
default:
http.Error(w, "invalid type", http.StatusBadRequest)
return
}
if err := db.Find(list); err != nil {
http.Error(w, "db error", http.StatusInternalServerError)
return
}
if err := json.NewEncoder(w).Encode(list); err != nil {
log.Printf("json encoding error: %v", err)
}
}
另一种选择是建立一个类型的注册表,甚至切片的创建可以被分解,使用帮助reflect:
var reg = map[string]reflect.Type{
"user": reflect.TypeOf((*models.User)(nil)).Elem(),
"product": reflect.TypeOf((*models.Product)(nil)).Elem(),
"order": reflect.TypeOf((*models.Order)(nil)).Elem(),
}
func List(w http.ResponseWriter, r *http.Request) {
etype := reg[r.FormValue("model")]
if etype == nil {
http.Error(w, "invalid type", http.StatusBadRequest)
return
}
list := reflect.New(reflect.SliceOf(etype)).Interface()
if err := db.Find(list); err != nil {
http.Error(w, "db error", http.StatusInternalServerError)
return
}
if err := json.NewEncoder(w).Encode(list); err != nil {
log.Printf("json encoding error: %v", err)
}
}
- 3 回答
- 0 关注
- 216 浏览
添加回答
举报