<分区>
我是 Go 的新手,我正在尝试构建一个简单的 HTTP 服务器。但是我遇到了 JSON 响应的一些问题。我写了下面的代码,然后尝试 postman 发送一些 JSON 数据。但是,我的 postman 总是得到一个空响应,content-type
是 text/plain;字符集=utf-8
。然后我在http://www.alexedwards.net/blog/golang-response-snippets#json中检查了一个样本.我复制并粘贴了示例,效果很好。但我看不出我的和 sample 有什么区别。有人可以帮忙吗?
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)
}