首页 > 解决方案 > go lang 错误:“必需”标签上的“”字段验证失败

问题描述

即使我传递了所需的查询字符串参数,我的请求也无法从其他服务中获得。这是验证码:

type ActionByRuleRequest struct {
    Code  string `json:"code" form:"code" query:"code" validate:"required,oneof=gde cse scc"`
    Name string `json:"name" form:"name" query:"name" validate:"required"` // Monitoring rule name
}

这是使用验证验证查询字符串

func GetActionByRule(c echo.Context) error {
    // Get parameters from the query string
    req := new(model.ActionByRuleRequest)
    err := c.Bind(req);
    if  err != nil {
        log.Println(err)
        error := model.Error{
            Message: err.Error(),
        }
        responseError := &model.ResponseError{
            Status: http.StatusBadRequest,
            Code:   "INVALID_INPUT",
        }
        responseError.Errors = append(responseError.Errors, error)
        return echo.NewHTTPError(http.StatusBadRequest, responseError)
    }
    // Validate input
    log.Printf("[/action_by_rule] 00000000000 get req = %#v\n", req)

    v := validator.New()

    err = v.Struct(req); 

    if err == nil {
        log.Println("Input valid")
    } else {
        log.Println("Input validation failed:", err)
     }
}

请求网址:' http: //127.0.0.1 :3015/action?code=csf&name=tbiubi-csf-rule '

错误:

 Key: 'ActionByRuleRequest.Code' Error:Field validation for 'Code' failed on the 'required' tag
Key: 'ActionByRuleRequest.Name' Error:Field validation for 'Name' failed on the 'required' tag

标签: validationgo

解决方案


推荐阅读