我在我的 golang 项目中使用 go-gin 服务器,并从一个返回数组作为响应的外部 API 获取一些数据
[
{
"Continent": "South America",
"Countries": [
{
"Country": "Argentina"
}
]
}
]
在我的 golang 代码中,这里是我发送请求和拦截响应的方式
client := &http.Client{Transport: tr}
rget, _ := http.NewRequest("GET", "http://x.x.x.x/v1/geodata", nil)
resp, err := client.Do(rget)
if err != nil {
fmt.Println(err)
fmt.Println("Failed to send request")
}
defer resp.Body.Close()
respbody, err := ioutil.ReadAll(resp.Body)
c.Header("Content-Type", "application/json")
c.JSON(200, string(respbody))
这给出了正确的响应,但我得到的不是一个数组,而是一个包含整个数组的字符串。所以我得到的回应是
"[{\"Continent\":\"South America\",\"Countries\": [{\"Country\": \"Argentina\"} ] } ]"
如何拦截响应作为数组而不是字符串? 我什至尝试了以下确实给了我一个数组但一个空白的数组。我的响应正文中的元素可能是数组和字符串,因此内容是混合的。
type target []string
json.NewDecoder(resp.Body).Decode(target{})
defer resp.Body.Close()
c.Header("Content-Type", "application/json")
c.JSON(200, target{})
最佳答案
您的第一个示例不起作用,因为您试图将字符串编码为 JSON,而这只会对字符串进行转义。 相反,将最后一行更改为
c.String(200, string(respbody))
这根本不会改变您从第三方收到的字符串,只会返回它。参见 here为了区别。
如果您想在数据通过您的程序时检查它,您必须首先将 JSON 字符串解码为结构数组,如下所示:
type Response []struct {
Continent string `json:"Continent"`
Countries []struct {
Country string `json:"Country"`
} `json:"Countries"`
}
关于go - 如何在数组 go-gin 中拦截 ReST API 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40652375/