Gin: Binding validations does not work when request body is Array of objects

Created on 13 Nov 2017  路  8Comments  路  Source: gin-gonic/gin

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.

question

Most helpful comment

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?

All 8 comments

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"`
}

https://mholt.github.io/json-to-go/

use dive

Items    []Item `json:"mails" binding:"dive"`
Was this page helpful?
0 / 5 - 0 ratings

Related issues

gplume picture gplume  路  3Comments

lilee picture lilee  路  3Comments

nxvl picture nxvl  路  3Comments

iiinsomnia picture iiinsomnia  路  3Comments

olegsobchuk picture olegsobchuk  路  3Comments