【问题标题】:How to print to http.ResponseWriter directly the json got from http.Get in Go?go - 如何将Go中从http.Get获取的json直接打印到http.ResponseWriter?
【发布时间】:2016-07-21 07:42:53
【问题描述】:

这是我的代码:

func GetRepositories(w http.ResponseWriter, r *http.Request) {
   w.Header().Set("Access-Control-Allow-Origin", "*")
   res, err := http.Get(fmt.Sprintf("%s/%s", sconf.RegistryConf.url, sconf.RegistryConf.listrepo))
   if err != nil {
      w.WriteHeader(500)
      log.Errorf("Could not get repositories: %s", err)
      return
   }
  log.Info("Repositories returned")
  fmt.Fprintf(w, fmt.Sprintf("%v", res))

}

我想要做的是直接打印当我访问 http.Get 内的 URL 时出现的相同内容,它是 JSON 格式,但我得到了其他内容。如果不对 JSON 内容表单 http.Get 进行编组然后编组并返回它,我该如何做到这一点?

【问题讨论】:

    标签: json http go


    【解决方案1】:

    http.Get() 返回的http.Response 不仅仅是服务器发送的 (JSON) 数据,它是一个包含所有其他 HTTP 协议相关字段(例如 HTTP 状态代码、协议版本、标头值等)的结构。您需要“转发”的只是Response.Body字段,它是一个io.ReadCloser,因此您可以从中读取服务器发送的实际数据。

    您可以使用io.Copy() 将正文从http.Get() 的响应复制到您的http.ResponseWriter。在此之前,建议设置与您获得的相同的内容类型。

    defer res.Body.Close()
    if contentType := res.Header.Get("Content-Type"); contentType != "" {
        w.Header().Set("Content-Type", contentType)
    }
    if _, err := io.Copy(w, res.Body); err != nil {
        // Handle error
    }
    

    【讨论】:

      猜你喜欢
      • 2021-06-27
      • 1970-01-01
      • 2013-10-03
      • 1970-01-01
      • 2018-04-21
      • 1970-01-01
      • 2015-03-15
      • 1970-01-01
      相关资源
      最近更新 更多