I want to write a gin middleware handler which gets data from c.Request.FormValue("data")
, unmarshalls it into a structure (structures are rather different) and sets a variable in context (c.Set("Data",newP)
). So I searched and wrote this:
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()
}
}
and I use it like this:
func InitHandle(R *gin.Engine) {
Plan := R.Group("/Plan")
Plan.POST("/clickCreate",middleware.Data(reflect.TypeOf(new(tls.PlanTabel))), clickCreatePlanHandle)
}
and
var data = *(c.MustGet("Data").(*tls.PlanTabel))
which is rather heavy and ugly. I want to
middleware.Data(tls.PlanTabel{})
and
var data = c.MustGet("Data").(tls.PlanTabel)
In other words, omitting gin, I want a closure that eats i interface{}
and returns a function (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
}
}