Hello, is there a way to bind ignoring binding tag but don't set global binding false ?
Why I ask this?
In the update and create cases for a model, I want to use the same model. For instance:
type User struct{
Username string `json:"username" binding:"required"`
Field2 string
Field3 string
}
in the case of creating , username is required.However in the case of updating, field username can be ignored. The solution of designing two almostly the same models is really bothering.
I wonder can gin add a function BindWithoutBindingTag(interface{}) like:
func (c *gin.Context) BindWithoutBindingTag(interface{}) error{
}
This is my case for json:
BindWithoutBindingTag(c *gin.Context, in, dest interface{}) error{
if c.ContentType() != "application/json" {
return errors.New("'BindWithoutBindingTag' only serves for application/json not for "+ c.ContentType())
}
buf,e :=ioutil.ReadAll(c.Request.Body)
if e!=nil {
return e
}
c.Request.Body = ioutil.NopCloser(bytes.NewReader(buf))
return json.Unmarshal(buf, dest)
}
It's good idea. @thinkerou what do you think about? I can create PR for the feature.
@b3lc0d3 yes,yes,
by the way,
Sometimes I need to read out from request.body,however after you've bind in a former middleware ,then it'll throws an EOF error if you bind again afterwards, like:
c.Bind(&o1) // success
c.Bind(&o2) // EOF
Can gin provide a method to bind repeated?
here is my personal solution for json however not involved to the officals regardless of some offical tags:
BindRepeatedly(c *gin.Context,dest interface{}) error{
if c.ContentType() != "application/json" {
return errors.New("'BindRepeatedly' only serves for application/json not for "+ c.ContentType())
}
buf,e :=ioutil.ReadAll(c.Request.Body)
if e!=nil {
return e
}
c.Request.Body = ioutil.NopCloser(bytes.NewReader(buf))
return json.Unmarshal(buf, dest)
}
@fwhezfwhez @b3lc0d3 please see https://github.com/gin-gonic/gin#model-binding-and-validation, you can use binding:"-".
@thinkerou
type User struct{
Username string `binding:"-"`
}
how to use a single model to fits both cases:
createUser: username required. Username stringbinding:"required"``
updateUser: username optional. Username stringbinding:"-"``
@fwhezfwhez any update about single model to fits your both cases?
@thinkerou @mosleim
type User struct{
Username string `binding:"required"`
}
c.BindIgnoreBindTag(&user) // will not require username
c.Bind(&user) // require username
Most helpful comment
@thinkerou
how to use a single model to fits both cases:
createUser: username required.
Username stringbinding:"required"``updateUser: username optional.
Username stringbinding:"-"``