我的主要目标是将 JSON 对象传递回客户端。但是,我的结构中不断出现 nil 或空值。如何获得预期和所需的 JSON 数组响应?下面是我的代码片段。
package main
import (
"net/http"
"fmt"
"encoding/json"
)
type News struct {
NewsID int `json:"newsId"`
PlayerID int `json:"playerId"`
TeamID int `json:"teamId"`
Team string `json:"team"`
Title string `json:"title"`
Content string `json:"content"`
Url string `json:"url"`
Source string `json:"source"`
TermsOfUse string `json:"terms"`
Updated string `json:"updated"`
}
func GetBoxScore (w http.ResponseWriter, r *http.Request) {
news := News{}
req, _ := http.NewRequest("GET","https://api.fantasydata.net/v3/nhlpb/scores/JSON/News", nil)
req.Header.Set("Ocp-Apim-Subscription-Key", "API KEY")
req.Host = "api.fantasydata.net"
client := &http.Client{}
res, err := client.Do(req)
defer res.Body.Close()
if err != nil {
fmt.Printf("The HTTP request failed with error %s\n", err)
}
err = json.NewDecoder(r.Body).Decode(&news)
newsJson, err := json.Marshal(news)
if err != nil {
panic(err)
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusAccepted)
w.Write(newsJson)
}
目前,响应是我的空 News 结构,所有值为 nil。我想要和期待的回应如下:
[
{
"NewsID": 8919,
"PlayerID": 30003647,
"TeamID": 28,
"Team": "VAN",
"Title": "Rumors have Elias Pettersson back this week",
"Content": "The rumor mill has Elias Pettersson (concussion) returning this week.",
"Url": "http://www.rotoworld.com/player/nhl/5819/elias-pettersson",
"Source": "NBCSports.com",
"TermsOfUse": "NBCSports.com feeds in the RSS format are provided free of charge for use by individuals for personal, non-commercial uses. More details here: http://fantasydata.com/resources/rotoworld-rss-feed.aspx",
"Updated": "2018-10-21T11:54:00"
},
aluckdog
胡子哥哥
相关分类