【问题标题】:Determine if POST data value matches struct field type确定 POST 数据值是否与结构字段类型匹配
【发布时间】:2015-06-07 09:19:22
【问题描述】:

使用 gin 框架,我试图确定 POST 数据是否与结构字段类型不匹配,并通知 API 用户他们的错误。

type CreateApp struct {
    LearnMoreImage string `db:"learn_more_image" json:"learn_more_image,omitempty" valid:"string,omitempty"`
    ApiVersion     int64  `db:"api_version" json:"api_version" valid:"int,omitempty"`
}
...
func CreateApps(c *gin.Context) {
    var json models.CreateApp
    c.Bind(&json)

所以当我发帖时

curl -H "Content-Type: application/json" -d '{"learn_more_image":"someimage.jpg","api_version":"somestring"}' "http://127.0.0.1:8080/v1.0/apps"

我想确定字段“api_version”的 POST 数据(作为字符串传递)是否与它绑定到的结构字段 (int) 不匹配。如果数据不匹配,我想向用户发送一条消息。正是出于这个原因,我希望我可以遍历 gin 上下文数据并进行检查。

gin 函数 'c.Bind()' 似乎忽略了无效数据和所有后续数据字段。

【问题讨论】:

    标签: go go-gin


    【解决方案1】:

    Gin 有一个内置的验证引擎:https://github.com/bluesuncorp/validator/blob/v5/baked_in.go

    但您可以使用自己的或完全禁用它。

    验证器不验证有线数据(json 字符串),而是验证绑定的结构:

    LearnMoreImage string `db:"learn_more_image" json:"learn_more_image,omitempty" binding:"required"`
    ApiVersion     int64  `db:"api_version" json:"api_version" binding:"required,min=1"`
    

    请注意:绑定:“required,min=1”

    然后:

    err := c.Bind(&json)
    

    或使用中间件并阅读c.Errors

    更新:

    三种解决方法:

    • 自己验证json字符串(enconding/json不能做到)
    • 验证整数是否 > 0 绑定:“min=1”
    • 使用 map[string]interface{} 而不是 Struct,然后验证类型。

      func endpoint(c *gin.Context) {
          var json map[string]interface{}
          c.Bind(&json)
          struct, ok := validateCreateApp(json)
          if ok { /** DO SOMETHING */ }
      }
      
      func validateCreateApp(json map[string]interface{}) (CreateApp, bool) {
          learn_more_image, ok := json["learn_more_image"].(string)
          if !ok {
              return CreateApp{}, false
          }
          api_version, ok = json["api_version"].(int)
          if !ok {
              return CreateApp{}, false
          }
          return CreateApp{
              learn_more_image, api_version,
          }
      }
      

    【讨论】:

    • 谢谢。我尝试使用 c.Errors 但它不适合,因为返回的错误“json: cannot unmarshal string into Go value of type int64”没有指定错误的字段。关于如何手动验证存储在 gin 上下文中的 POST 数据的任何提示?
    • 尝试 map[string]interface{} 方法... 标准库没有返回更好的错误消息,这很糟糕。
    猜你喜欢
    • 2014-12-30
    • 1970-01-01
    • 2018-09-10
    • 1970-01-01
    • 2021-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-23
    相关资源
    最近更新 更多