I'm new to Go, and I'm trying to practice creating a simple HTTP server. However, I ran into some problems with JSON answers. I wrote the following code, then try the postman to send some JSON data. However, my postman always gets an empty answer, and content-type
- text/plain; charset=utf-8
. Then I checked the sample at http://www.alexedwards.net/blog/golang-response-snippets#json . I copied and pasted the sample, and it worked well. But I do not see any difference between mine and the sample. Can anyone help?
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)
}
source
share