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。我以爲我做到了。 –