Reputation:
I'm having trouble validating if JSON body passed to my POST endpoints matches the struct created for the acceptable JSON body. Any help would be appreciated
type NewUser struct {
UserID string `json:"user_id"`
UserName string `json:"user_name"`
}
func AddUser(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
decoder := json.NewDecoder(r.Body)
var user NewUser
err := decoder.Decode(&user)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
}
user.UserID != NewUser.UserID{
http.Error(w, "error", http.StatusBadRequest),
}
}
Upvotes: 0
Views: 736
Reputation: 51542
There are multiple ways you can achieve this, with different levels of strictness:
You can check if UserID and UserName are nonempty. This will not validate if the input matches the structure. It only captures the userid and name if those fields appear in the input.
If empty values are acceptable, you can use *string
instead of string
, and check if the pointer is nil. If the pointer is nil, that field does not appear in the JSON, or it appears as nil. If it appears as empty string, the pointer will not be nil, but the string will be empty. This method also accepts if there are additional fields in the submitted JSON.
For this specific case, if you want to make sure no additional unrecognized fields are passed, you can unmarshal the body into interface{}
, and make sure it contains at most two fields, and that those are the fields you recognize.
In general if you need to do strict validation, you can use a json schema, and check if input validates against the schema you expect. This is usually more trouble than it is worth.
Upvotes: 1