package controllers
import (
"encoding/json"
"errors"
"io"
"io/ioutil"
"reflect"
)
func GetTypeFromReq(c *App, ty interface{}) (interface{}, error) {
//get the type we are going to marshall into
item := reflect.ValueOf(ty)
//define and set the error that we will be returning to null
var retErr error
retErr = nil
//extract the body from the request and defer closing of the body
body, err := ioutil.ReadAll(io.LimitReader(c.Request.Body, 1048576))
defer c.Request.Body.Close()
//handle errors and unmarshal our data
if err != nil {
retErr = errors.New("Failed to Read body: " + err.Error())
} else if err = json.Unmarshal(body, &item); err != nil {
retErr = errors.New("Unmarshal Failed: " + err.Error())
}
return item, retErr
}
我想一个类型和请求传递到一个函数,那么该函数内部和解组请求到一个变量,并将其返回。如何一般马歇尔请求到JSON在golang
我认为我的做法是错误的,因为当我尝试这样做:
inter, err := GetTypeFromReq(&c, models.User{})
if err != nil {
revel.ERROR.Println(err.Error())
}
user := inter.(models.User)
我得到的错误“接口转换:接口{}是reflect.Value,不models.User”
关于如何解决这个问题的任何提示?最后一行的
真的很棒的解释,非常感谢你 –
完成,woops。我以为我做到了。 –