This is my HandleFunc
.
type User struct {
Username string `json:"username"`
Password string `json:"password"`
}
type ResponseResult struct {
Error string `json:"error"`
Result string `json:"result"`
}
func Registration(w http.ResponseWriter, r *http.Request) {
var res ResponseResult
w.Header().Set("Content-Type", "application/json")
body, err := ioutil.ReadAll(r.Body)
// no json body
if err != nil {
res.Error = err.Error()
// return 400 status codes
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(res)
return
}
}
This works well if I am not passing any JSON body with the request.
But I want that if wrong data is given, it should error out too. For example, I don’t want the following data to be taken as correct:
{
"usernm": "foo",
"passwd": "bar"
}
This is what I am using:
var user model.User
// check if valid data is coming, username and password
err = json.Unmarshal(body, &user)
// wrong keys in json body
if err != nil {
res.Error = "Incorrect data sent. See API docs."
// return 400 status codes
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(res)
return
}
res.Result = "No difficulties"
json.NewEncoder(w).Encode(res)
I am getting no error at json.Unmarshal
with the wrong body.