Gin: Bind should support default values

Created on 2 Aug 2017  路  9Comments  路  Source: gin-gonic/gin

Bind() is great, but what do you guys think if it supports default values when a param is not specified? Something like this:

    params = struct {
        Name string `form:"name,default=john"`
        Age uint `form:"address,default=10"`
    }{}

    c.Bind(&param)

Most helpful comment

Another story. For those who, like me, want default JSON field value when using BindJSON:
Just set the default value when initializing the struct. E.g.

params = struct {
    Name string `json:"name"`
    Age  uint   `json:"address"`
}{
    Name: "john",
    Age:  10,
}
c.BindJSON(&params)

And from this issue I got to know anonymous struct.

I learnt a lot today.

All 9 comments

Hi @atedja I have commit one pull request and I attempt to complete it.

@atedja Now the pr have merged to the master branch.

Implement in #1138 . try it in the latest master branch.

So, how to use it???

So, how to use it ???

@KingJeason @calixwu

`form:"field_name,default=value"`

It worked for me.

@to2false I have already used it that way, but thanks all the same. I think it's better to document this usage.

Another story. For those who, like me, want default JSON field value when using BindJSON:
Just set the default value when initializing the struct. E.g.

params = struct {
    Name string `json:"name"`
    Age  uint   `json:"address"`
}{
    Name: "john",
    Age:  10,
}
c.BindJSON(&params)

And from this issue I got to know anonymous struct.

I learnt a lot today.

Another story. For those who, like me, want default JSON field value when using BindJSON:
Just set the default value when initializing the struct. E.g.

params = struct {
  Name string `json:"name"`
  Age  uint   `json:"address"`
}{
  Name: "john",
  Age:  10,
}
c.BindJSON(&params)

And from this issue I got to know anonymous struct.

I learnt a lot today.

Hi Snow, I tried your way but it can only work with field missing.
For example, if you passed in a json string with age set to init value zero, 10 would got replaced.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

iiinsomnia picture iiinsomnia  路  3Comments

rawoke083 picture rawoke083  路  3Comments

xpbliss picture xpbliss  路  3Comments

gplume picture gplume  路  3Comments

nxvl picture nxvl  路  3Comments