Description
There's a use-case where I would like to exactly know if a key is present in the body of POST/PATCH. I would like know if a field in body is actually being sent as null
or it has been not sent at all. What is the best way to do this in gin framework?
What I am doing as of now?
Have written a custom body parser
func BodyParsing[T any](request *http.Request) (T, []string, error) {
jsonData, _ := ioutil.ReadAll(request.Body)
mapBody := make(map[string]interface{})
var body T
err := json.Unmarshal(jsonData, &body)
if err != nil {
return body, []string{}, err
}
validateErr := binding.Validator.ValidateStruct(body)
if validateErr != nil {
return body, []string{}, validateErr
}
err2 := json.Unmarshal(jsonData, &mapBody)
if err2 != nil {
return body, []string{}, err2
}
keys := make([]string, 0, len(mapBody))
for k := range mapBody {
keys = append(keys, k)
}
return body, keys, nil
}
Environment
- go version: 1.18
- operating system: Ubuntu 22.04