遇到问题:gin 使用 Bind 时无法填充,改成下面代码可以获取到

go
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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")

Reference

Bind should support default values