go - 如何在数组 go-gin 中拦截 ReST API 响应

标签 go

我在我的 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/

相关文章:

select - 跳出选择循环?

http - 如何使用 net/http 打破 go 中的分块?

golang 默认将 json 对象解码为 map[string]interface{},如何将其解码为 []byte?

尽管有锁,Go 仍检测到 map 上的并发读写

go - 提供包 <package_name> 的模块缺少 go.sum 条目

interface - 实现接口(interface)函数时结构字段未更新

go - 处理大量查询并避免重复

Golang 保持活力

web-applications - Go Webapp & Nginx : Confusion about listening, fastcgi & 反向代理

go - 高效地将压缩值写入流