登录
首页 >  Golang >  Go问答

如何验证Gin请求中的参数是否已发布

来源:stackoverflow

时间:2024-02-14 09:18:24 408浏览 收藏

小伙伴们有没有觉得学习Golang很有意思?有意思就对了!今天就给大家带来《如何验证Gin请求中的参数是否已发布》,以下内容将会涉及到,若是在学习中对其中部分知识点有疑问,或许看了本文就能帮到你!

问题内容

type listparams struct {
    status int `form:"status"`
    keyword string `form:"keyword"`
    showtype int `form:"show_type"`
}

func list(c *gin.context) {
    var reqdata listparams
    _ = c.shouldbind(&reqdata)
     
    // i fetch this by postform() to check it empy if it equal to empty string
    if stat := c.postform("status"); stat == "" {
        reqdata.status = -99
    }

    // .......
}

在这段代码中,我如何知道它是否是前端发布的 status

由于go的默认值,如果我检查reqdata.status == 0,如果前端没有发布它,它总是返回true,但就我而言,0是一个有意义的值,所以我无法通过等于 0 来检查它。

那我还有其他方法可以检查吗?

ps:我尝试发现,如果我不赋值,gorm将不会更新结构中的字段:

var d &User{} // User is a definition of user table
d.ID = 1
d.Name = "Joy"
// d.Status = 1 // It has this field, but I dont assign it
db.Model(&User{}).updates(&d)

最后,status不会更新为0(根据我的理解,d.status应该是0


正确答案


使用指针类型来规避默认值 0:

type listParams struct {
    Status &int `form:"status"`
    Keyword string `form:"keyword"`
    ShowType int `form:"show_type"`
}

检查d.status是否为nil,否则获取关联值

今天关于《如何验证Gin请求中的参数是否已发布》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>