gin参数绑定panic错误分析
经过长期实践
func (e *SubscribeApi) FnExample(c *gin.Context) {//获取参数并检验var req *request.FnReqif err := c.ShouldBindQuery(&req); err != nil {response.FailWithMsg(c, "Parameter validation error: "+err.Error())return}//...
}type FnReq struct {ShopId int64 `json:"shop_id" form:"shop_id" uri:"shop_id" binding:"required"`Sign string `json:"sign" form:"sign" uri:"sign" binding:"required"`ChargeId int64 `json:"charge_id" form:"charge_id" uri:"charge_id" binding:"required"`PackageId int64 `json:"p" form:"p" uri:"p" binding:"required"`
}
这种写法在传部分参数时不会蹦,
在什么参数都不传的时候会崩, 报panic错误.
那么该如何避免参数绑定时报panic错误呢?
//参数结构体定义不变
//接收参数的变量设置为非指针的普通变量
func (e *SubscribeApi) FnExample(c *gin.Context) {//获取参数并检验var req request.FnReqif err := c.ShouldBindQuery(&req); err != nil {response.FailWithMsg(c, "Parameter validation error: "+err.Error())return}
}