Description
bindQuery set *int to 0
How to reproduce
package main
import (
"github.com/gin-gonic/gin"
)
type QueryRequest struct{
Name string `form:"name"`
Age *int `form:"age"`
}
func main() {
g := gin.Default()
g.GET("/list", func(c *gin.Context) {
var req QueryRequest
if err:=c.BindQuery(&req);err!=nil{
....
}
})
g.Run(":9000")
}
Expectations
$ curl http://localhost:9000/list?name=john&age=
$ curl http://localhost:9000/list?name=john
gin receives different parameters from these two url the first one field age is 0 and the second one age is nil
When the url address contains the age parameter but does not contain a value, it does not mean that the data value is missing. If age is a query condition, it will not be able to distinguish whether the age value is missing or whether age=0 needs to be queried
Comment From: RedCrazyGhost
This has to do with golang's reflection mechanism.
If there is no age key, the struct created by reflection will have no age field and no space in memory.
If an age key is present, the struct will have an age field with the default value type.zero
You can use json for the effect you want to achieve.
package main
import (
"github.com/gin-gonic/gin"
)
type QueryRequest struct{
Name string `json:"name"`
Age *int `json:"age"`
}
func main() {
g := gin.Default()
g.GET("/list", func(c *gin.Context) {
var req QueryRequest
if err:=c.BindJSON(&req);err!=nil{
....
}
})
g.Run(":9000")
}