Gin's request validation feature is not working when the request body (JSON) represents an array of objects
Ex:
type item struct {
Field1 string `binding:"required"`
Field2 string `binding:"required"`
}
var items []item
err := c.BindJSON(&items)
To be more clear, the validation logic in gin is expecting the root object to be a struct and hence bails out when an array type gets passed.
Yes, this is an expected behavior. From the StructValidator interface, it says 'If the received type is not a struct, any validation should be skipped and nil must be returned.'.
Even though this might be expected behaviour per interface definition, I was surprised to see binding:"required" lose its effect without any warnings or complaints at least at runtime.
@ycavatars So, what is best way to validate each object in an array passed in the body?
@khier996 yes, closing.
the issue was closed without answer the last question:
what is best way to validate each object in an array passed in the body?
Could someone answer it?
I define a required struct field as a pointer and later check such fields for nil, but maybe there is not so dirty way?
+1
use
type AutoGenerated []struct {
OrgID string `json:"org_id"`
GroupID string `json:"group_id"`
}
use dive
Items []Item `json:"mails" binding:"dive"`
Most helpful comment
the issue was closed without answer the last question:
Could someone answer it?
I define a required struct field as a pointer and later check such fields for nil, but maybe there is not so dirty way?