【发布时间】:2018-07-16 02:33:21
【问题描述】:
我想编写一个 gin 中间件处理程序,它从c.Request.FormValue("data") 获取数据,将其解组为一个结构(结构相当不同)并在上下文中设置一个变量(c.Set("Data",newP))。所以我搜索并写了这个:
package middleware
import (
"reflect"
"fmt"
"github.com/gin-gonic/gin"
"encoding/json"
)
//https://semaphoreci.com/community/tutorials/test-driven-development-of-go-web-applications-with-gin
//https://github.com/gin-gonic/gin/issues/420
func Data(t reflect.Type) gin.HandlerFunc {
return func(c *gin.Context) {
//https://stackoverflow.com/a/7855298/5257901
//https://stackoverflow.com/a/45680060/5257901
//t := reflect.TypeOf(orig)
v := reflect.New(t.Elem())
// reflected pointer
newP := v.Interface()
data:=c.Request.FormValue("data")
fmt.Printf("%s data:%s\n",c.Request.URL.Path,data)
if err:=json.Unmarshal([]byte(data),newP); err!=nil{
fmt.Printf("%s data unmarshall %s, data(in quotes):\"%s\"",c.Request.URL.Path,err,data)
c.Abort()
return
}
ustr, _:=json.Marshal(newP)
fmt.Printf("%s unmarshalled:%s\n",c.Request.URL.Path,ustr)
c.Set("Data",newP)
c.Next()
}
}
我是这样使用它的:
func InitHandle(R *gin.Engine) {
Plan := R.Group("/Plan")
Plan.POST("/clickCreate",middleware.Data(reflect.TypeOf(new(tls.PlanTabel))), clickCreatePlanHandle)
}
和
var data = *(c.MustGet("Data").(*tls.PlanTabel))
这是相当沉重和丑陋的。我想要
middleware.Data(tls.PlanTabel{})
和
var data = c.MustGet("Data").(tls.PlanTabel)
换句话说,省略杜松子酒,我想要一个吃i interface{}并返回一个函数(data string) (o interface{})的闭包
func Data(i interface{}) (func (string) (interface{})) {
//some reflect magic goes here
//extract the structure type from interface{} :
//gets a reflect type pointer to it, like
//t := reflect.TypeOf(orig)
return func(data string) (o interface{}) {
//new reflected structure (pointer?)
v := reflect.New(t.Elem())
//interface to it
newP := v.Interface()
//unmarshal
json.Unmarshal([]byte(data),newP);
//get the structure from the pointer back
//returns interface to the structure
//reflect magic ends
}
}
【问题讨论】:
标签: json go reflection unmarshalling go-gin