【发布时间】:2018-03-19 13:12:58
【问题描述】:
我是 Go 新手,我正在尝试构建一个简单的 HTTP 服务器。但是,我遇到了 JSON 响应的一些问题。我编写了以下代码,然后尝试邮递员发送一些 JSON 数据。但是,我的邮递员总是得到一个空的回复,content-type 是text/plain; charset=utf-8。然后我在http://www.alexedwards.net/blog/golang-response-snippets#json 中检查了一个样本。我复制并粘贴了示例,它运行良好。但我看不出我的和样品有什么区别。有人可以帮忙吗?
package main
import (
"encoding/json"
"net/http"
)
type ResponseCommands struct {
key string
value bool
}
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":5432", nil)
}
func handler(rw http.ResponseWriter, req *http.Request) {
responseBody := ResponseCommands{"BackOff", false}
data, err := json.Marshal(responseBody)
if err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
return
}
rw.WriteHeader(200)
rw.Header().Set("Content-Type", "application/json")
rw.Write(data)
}
【问题讨论】: