An error occurred while binding int type on Shouldbind in the Gin framework and has not been able to bind

Issue

When I implemented paging queries using the Gin framework, I found that JSON passed in Postman was never successfully bound to PageSize and PageNum of type INT. (Shouldbind doesn’t have err)
Here is the image link:https://i.imgur.com/fbkgonI.png
Code:
api:

func GetAllTask(c *gin.Context)  {
 var getAllService service.GetAllService
 err := c.ShouldBind(&getAllService)
 if err != nil {
    c.JSON(http.StatusBadRequest,gin.H{
       "status":-1,
       "msg":"json解析失败",
       "error":err.Error(),
    })
    return
 }

 claims, err := util.ParserToken(c.GetHeader("token"))
 if err != nil {
    c.JSON(http.StatusBadRequest,gin.H{
       "status":-1,
       "msg":"token解析失败",
       "error":err.Error(),
    })
    return
 }
 res := getAllService.GetAllTask(claims.Uid)
 c.JSON(http.StatusOK,res)
}

service:

type GetAllService struct {
    PageSize int    `json:"page_size" form:"page_size" default:"10"`
    PageNum  int    `json:"page_num" form:"page_num" default:"1"`
    //KeyWord  string `form:"key_word"`
    Desc     bool   `json:"desc" form:"desc"`
}

Request body JSON in postman:

{
    "page_size":2,
    "page_num":1,
    "desc":false
}

Please help me.Thank you!

Solution

Thank blackgreen. It was careless of me. I should change Get to POST in route.
Here:
Change task.GET("/getall",api.GetAllTask) to task.POST("/getall",api.GetAllTask)

Or keep task.GET("/getall",api.GetAllTask), just modify the url in the Postman for localhost:8080/api/task/getall?page_size=2&page_num=2.

Answered By – Windtalkers

Answer Checked By – Pedro (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.