我的 Go 服务器没有从远程 API 检索所有 JSON 数据
我什至尝试创建一个自定义 http.Client 来发出请求...但它仍然无法检索 全部 JSON数据,甚至尝试延长各自的超时时间
这是我的代码:
var netTransport = &http.Transport{
Dial: (&net.Dialer{
Timeout: 50 * time.Second,
}).Dial,
TLSHandshakeTimeout: 50 * time.Second,
}
var netClient = &http.Client{
Timeout: time.Second * 40,
Transport: netTransport,
}
res, getErr := netClient.Get(url)
if getErr != nil {
log.Fatal(getErr)
}
data := JSONData{}
if err := json.NewDecoder(res.Body).Decode(&data); err != nil {
log.Fatal(err)
}
data.Username = user
fmt.Println(data)
JSONData 定义如下:
type Owner struct {
Login string
}
// Item is the single repository data structure
type Item struct {
ID int
Name string
FullName string `json:"full_name"`
Owner Owner
Description string
CreatedAt string `json:"created_at"`
}
// JSONData contains the GitHub API response
type JSONData struct {
Count int `json:"total_count"`
Username string
Items []Item
}
最佳答案
JSONData
需要定义 JSON 标签。
type Owner struct {
Login string `json:"login"`
}
// Item is the single repository data structure
type Item struct {
ID int `json:"id"`
Name string `json:"name"`
FullName string `json:"full_name"`
Owner Owner `json:"owner"`
Description string `json:"description"`
CreatedAt string `json:"created_at"`
}
// JSONData contains the GitHub API response
type JSONData struct {
Count int `json:"total_count"`
Username string `json:"username"`
Items []Item `json:"items"`
}
如果未指定标签,则按原样使用名称:
type Owner struct {
Login string
}
这将被编码(并相应地解码)成类似的:
{"Login": "some login"}
关于json - 服务器没有从远程 REST API 获取所有 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59529411/