Said  Saifi
Said Saifi

Reputation: 2408

How to print to http.ResponseWriter directly the json got from http.Get in Go?

This is my code:

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))

}

What I am trying to do is to directly print the same thing that appears when I access the URL inside http.Get which is in JSON format, but I am getting other things. How can I do this without umarshaling the JSON content form http.Get and then marshaling it and returning it?

Upvotes: 2

Views: 2271

Answers (1)

icza
icza

Reputation: 418585

The http.Response returned by http.Get() is not just the (JSON) data sent by the server, it's a struct containing all other HTTP protocol related fields (e.g. HTTP status code, protocol version, header values etc). What you need to "forward" is only the Response.Body field which is an io.ReadCloser, so you can read the actual data from it sent by the server.

You may use io.Copy() to copy the body from the response of http.Get() to your http.ResponseWriter. Before that it's recommended to set the same content type that you get.

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
}

Upvotes: 2

Related Questions