简体   繁体   中英

How to send a JSON response from an HTTP GET request in Golang?

I am learning how to build a server with Go, and wanted to know how to send a response back in JSON using Go's "encoding/json" library. Here is the code I have so far:

func HandlePosts (w http.ResponseWriter, r *http.Request) {
    rs, err := http.Get("https://jsonplaceholder.typicode.com/posts")
    if err != nil {
        panic(err)
    }

    defer rs.Body.Close()

    w.Header().Set("Content-Type", "application/json")

    json.NewEncoder(w).Encode(rs.Body)
}

When I log this response in the browser's console, it just gives me an empty object. Any help would be appreciated!

You can't "encode" the http.Repsonse.Body . It's an io.ReadCloser , so you need to read from it.

In this case, the response is already json, so just send it back to the client.

io.Copy(w, rs.Body)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM