【问题标题】:gin how to check whether params was post or not杜松子酒如何检查参数是否已发布
【发布时间】:2021-05-05 01:44:51
【问题描述】:
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如果我不赋值就不会更新struct中的字段:

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

【问题讨论】:

    标签: go go-gin


    【解决方案1】:

    使用指针类型绕过默认值0:

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

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

    【讨论】:

      【解决方案2】:

      我认为这种约束提出了对构建用户的唯一公共方式的需求。

      type user struct { Status int Keyword string ShowTypeint}
      func NewUser() (*user) { return &user{Status: -1} }
      

      这样可以确保用户结构仅通过 NewUser 构造,其 Status 默认值 Status 始终等于 -1。

      【讨论】:

        猜你喜欢
        • 2013-01-20
        • 2019-04-13
        • 1970-01-01
        • 2022-01-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-01-12
        • 2016-11-24
        相关资源
        最近更新 更多