I'm setting up HTTP server, and want /test
route to accept POST request, but with this code body is always empty. This is my request body:
{
"asd": "123"
}
This is my code:
func main() {
router := mux.NewRouter()
router.HandleFunc("/test", handleData).Methods("POST")
log.Fatal(http.ListenAndServe(":80", router))
}
type test1 struct {
asd string
}
func handleData(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
var test test1
_ = json.NewDecoder(r.Body).Decode(&test)
json.NewEncoder(w).Encode(test)
}
The asd
field is unexported. Change it to Asd string `json:"asd"`
. Identifiers (types, functions, fields, methods, variables, constants, etc.) that start with upper case letter are exported, those that start with lower case are unexported. The json package works only with exported fields, unexported ones are ignored.