How to look for specific keys in request body? If not, error out

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.

I have also tried using json.Decode:

err := json.NewDecoder(r.Body).Decode(&user)
// no json body
if err != nil {
	res.Error = err.Error()
	// return 400 status codes
	w.WriteHeader(http.StatusBadRequest)
	json.NewEncoder(w).Encode(res)
	return
}

But this block is not reachable as there is no error in decoding.

Use DisallowUnknownFields from Decoder:

jsonDecoder := json.NewDecoder(r.Body)
jsonDecoder.DisallowUnknownFields()
defer r.Body.Close()

// check if there is proper json body or error
if err := jsonDecoder.Decode(&user); err != nil {
	res.Error = err.Error()
	// return 400 status codes
	w.WriteHeader(http.StatusBadRequest)
	json.NewEncoder(w).Encode(res)
	return
}

defer r.Body.Close() should be called after error block.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.