简体   繁体   English

如何在Golang中从HTTP GET请求发送JSON响应?

[英]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. 我正在学习如何使用Go构建服务器,并且想知道如何使用Go的“ encoding / json”库以JSON发送回响应。 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 . 您无法“编码” http.Repsonse.Body It's an io.ReadCloser , so you need to read from it. 这是io.ReadCloser ,所以您需要从中读取。

In this case, the response is already json, so just send it back to the client. 在这种情况下,响应已经是json,因此只需将其发送回客户端即可。

io.Copy(w, rs.Body)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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