Description
ShouldBindQuery cannot bind to struct with []interface{} field
How to reproduce
package main
import "github.com/gin-gonic/gin"
func main() {
type query struct {
InvalidField any `form:"invalidField"`
}
router := gin.Default()
router.GET("/test", func(c *gin.Context) {
var q query
if err := c.ShouldBindQuery(&q); err != nil {
c.JSON(400, gin.H{"error": err.Error(), "message": "failed to bind query"})
return
}
c.JSON(200, q)
})
router.Run()
}
Expectations
$ curl http://localhost:8080/test
1
Actual result
acheong@insignificantv5 ~> curl "http://127.0.0.1:8080/test?invalidField=1"
{"error":"unknown type","message":"failed to bind query"}
Environment
go version go1.20.6 linux/amd64
- github.com/gin-gonic/gin@02e754be9c4889f7ee56db0660cc611 eb82b61d6
- operating system:
6.4.6-200.fc38.x86_64
Comment From: keyvangholami
Unfortunately, Gin does not know how to bind to an arbitrary interface{} since it needs to know the type to handle correctly. You would need to specify the type or handle the binding manually.
If you know what type you are expecting, you can change the field to that type, or If you want to handle multiple types for this field, you'll need to implement custom binding logic.
Comment From: acheong08
Is there an alternative if I'm only looking to use primitives like string
, bool
, and int
?
Comment From: keyvangholami
Is there an alternative if I'm only looking to use primitives like
string
,bool
, andint
?
You can define a custom type to represent those values and implement the necessary methods to bind them.