我是Go的新手,我正在尝试构建一个简单的HTTP服务器。但是我在JSON响应中遇到了一些问题。我编写了以下代码,然后尝试邮递员发送一些JSON数据。但是,我的邮递员总是得到空响应,而content-type
is 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)
}
主要区别在于结构中的变量是公共的(导出的)
type Profile struct {
Name string
Hobbies []string
}
在您的情况下,它们不是(小写)。
type ResponseCommands struct {
key string
value bool
}
请参阅“ Go中带有JSON Marshal的小写JSON密钥名称 ”。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句