我有这样的反应结构
type Reaction struct {
Id uint `json:"id" form:"id"`
ReactionType uint `json:"reactionType" form:"reactionType"`
PostId uint `json:"postId" form:"postId"`
ReactorId uint `json:"reactorId" form:"reactorId"`
CreatedAt string `json:"createdAt" form:"createdAt"`
UpdatedAt string `json:"updatedAt" form:"createdAt"`
}
我有一个函数,它使用一个API,它应该返回Reaction
的一个片段。
var myClient = &http.Client{Timeout: 7 * time.Second}
func getJson(url string, result interface{}) error {
req, _ := http.NewRequest("GET", url, nil)
resp, err := myClient.Do(req)
if err != nil {
return fmt.Errorf("cannot fetch URL %q: %v", url, err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("unexpected http GET status: %s", resp.Status)
}
err = json.NewDecoder(resp.Body).Decode(result)
if err != nil {
return fmt.Errorf("cannot decode JSON: %v", err)
}
return nil
}
但不知何故,它未能显示我想要检索的对象的数组/片段,我根本没有任何数据。我错过了哪里?
func main(){
..
..
var reactList []Reaction
getJson("http://localhost:80/reactions", reactList)
for _, r := range reactList {
fmt.Print(r.ReactionType)
}
}
这是最初的回应
[
{
"id": 55,
"reactionType": 5,
"reactorId": 2,
"postId": 4,
"createdAt": "2017-11-18 14:23:29",
"updatedAt": ""
},
{
"id": 56,
"reactionType": 5,
"reactorId": 3,
"postId": 4,
"createdAt": "2017-11-18 14:23:42",
"updatedAt": ""
},
{
"id": 57,
"reactionType": 4,
"reactorId": 4,
"postId": 4,
"createdAt": "2017-11-18 14:23:56",
"updatedAt": ""
}
]
发布于 2017-11-22 09:08:15
正如注释中所指出的,您需要传递一个指向getJson
的指针,以便它能够实际修改片的内容。
getJson("http://localhost:80/reactions", &reactList)
这是您所拥有的PnNK64giE的紧密表示,只需查看在您的情况下哪些地方不合适。
发布于 2017-11-22 08:59:01
查看这个操场:https://play.golang.org/p/VjocUtiDRN
也许这就是你想要的。因此,您应该使您的函数getJson
(在Golang命名约定中getJSON
是更好的名称)接受[]Reaction
参数,而不是interface{}
。然后,您可以将类似数组的响应解编组到Reaction
的片段中。
发布于 2017-11-22 10:21:52
这里的主要错误是在没有指针的情况下传递结果。应:
getJson("http://localhost:80/reactions", &reactList)
https://stackoverflow.com/questions/47430024
复制相似问题