我是golang的新手,我正在尝试构建一个简单的tcp服务器.但是我遇到了一些使用JSON响应的问题.我写了下面的代码,然后尝试postman发送一些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)
}
Run Code Online (Sandbox Code Playgroud)