Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bind should support default values #1052

Closed
atedja opened this issue Aug 2, 2017 · 15 comments
Closed

Bind should support default values #1052

atedja opened this issue Aug 2, 2017 · 15 comments

Comments

@atedja
Copy link

atedja commented Aug 2, 2017

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)
@thinkerou
Copy link
Member

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

@thinkerou
Copy link
Member

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

@appleboy
Copy link
Member

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

@calixwu
Copy link

calixwu commented Jun 21, 2019

So, how to use it???

@KingJeason
Copy link

So, how to use it ???

@to2false
Copy link

@KingJeason @calixwu

`form:"field_name,default=value"`

It worked for me.

@calixwu
Copy link

calixwu commented Jul 30, 2019

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

@SnowOnion
Copy link

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.

@Gera-coder
Copy link

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.

@kamly
Copy link

kamly commented Mar 4, 2021

@thinkerou @SnowOnion @Gera-coder

I want to wirte this

type Param struct {
   Name string `json:"name,default=john"`
   Age uint `json:"address,default=10"`
}
var param Param
c.ShouldBind(&param)

but it doesn't work, has any good method in ShouldBind JSON?

@runzhliu
Copy link

runzhliu commented Aug 31, 2021

I think the default value doesn't work for the json type, actually, I find no related unitest for the default value except for the form type, but assigning the default value before the binding works for me.

@kangour
Copy link

kangour commented Dec 7, 2022

if use dive then default invalid, help.

@olivatooo
Copy link

olivatooo commented Jun 9, 2023

help 😔

@AuroraTea
Copy link

@KingJeason @calixwu

`form:"field_name,default=value"`

It worked for me.

Sorry for Interrupting you, is it now discarded?

type ReqListUsers struct {
	Limit  int64  `form:"limit,default=20" binding:"min=1,max=100"`
	Sort   string `form:"sort,default=id" binding:"omitempty,oneof=id createAt lastLoginAt"`
	Order  string `form:"order,default=asc" binding:"omitempty,oneof=asc desc"`
}

func ListUsers(c *gin.Context) {
	var req ReqListUsers
	err := c.ShouldBindQuery(&req)

But not work.

@hexuan1922
Copy link

hexuan1922 commented Jun 14, 2024

@thinkerou @SnowOnion @Gera-coder

I want to wirte this

type Param struct {
   Name string `json:"name,default=john"`
   Age uint `json:"address,default=10"`
}
var param Param
c.ShouldBind(&param)

but it doesn't work, has any good method in ShouldBind JSON?

type User struct {
	Name string `form:"name,default=user1" json:"name,default=user2"`
	Age  int    `form:"age,default=10" json:"age,default=20"`
}

r := gin.Default()

// way1 curl 127.0.0.1:8900/bind?name=aa
// way2 curl -X POST 127.0.0.1:8900/bind -d "name=aa&age=30"
// way3 curl -X POST 127.0.0.1:8900/bind -H "Content-Type: application/json" -d "{\"name\": \"aa\"}"
r.Any("/bind", func(c *gin.Context) {
    var user User
    //user = User{Name: "bb", Age: 11} //way4:A variable of type User can be generated with the default value before bind

    if c.ContentType() == binding.MIMEJSON {
        //way5:A variable of type User can be generated with the default value before bind.
        _ = binding.MapFormWithTag(&user, nil, "json")
    }

    _ = c.Bind(&user) //Note that because bind is used here to request json, you specify the Content-Type header
    c.String(200, "Hello %v age %v", user.Name, user.Age)
})

// The above 4 way.
// way1/2 structTag is work.because gin at queryBinding/formBinding execute mapFormByTag logic, will check formTag
// way3 structTag not work. gin at jsonBinding non-execution  mapFormByTag logic
// way4/way5 no matter query/form/json All valid
// way5 is work.  Because the mapFormByTag logic is triggered in addition

r.Run(":8900")

good luck. @kamly

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests