为了账号安全,请及时绑定邮箱和手机立即绑定

正确的请求正文被 Go 中的验证器视为无效

正确的请求正文被 Go 中的验证器视为无效

Go
慕田峪7331174 2022-09-05 10:41:05
我正在尝试使用验证器根据此结构验证请求正文。但是在Postman中,在验证结构时,它总是会抛出错误。我只希望在提出请求时需要所有值。package modeltype User struct {    FeatureName string `json:"featureName" validate:"required"`    Email       string `json:"email" validate:"required"`    CanAccess   *bool  `json:"can_access" validate:"required"`}我已尝试将其作为Postman上的请求正文发送:// Request body{    "featureName": "crypto",    "email": "test5@gmail.com",    "can_access": true}// Response body{    "status": 422,    "message": "Missing parameters featureName/can_access/email"}法典:package controllerimport (    "database/sql"    "encoding/json"    "errors"    "net/http"    "unicode/utf8"    "github.com/yudhiesh/api/model"    "gopkg.in/validator.v2"    "github.com/yudhiesh/api/config")func InsertFeature(w http.ResponseWriter, r *http.Request) {    var user model.User    var response model.Response    db := config.Connect()    defer db.Close()    // Decode body into user struct    if err := json.NewDecoder(r.Body).Decode(&user); err != nil {        response.Message = "Error"        response.Status = http.StatusInternalServerError        json.NewEncoder(w).Encode(response)        return    } else {        // Validate struct to check if all fields are correct        // Fails here!        if err := validator.Validate(user); err != nil {            response.Message = "Missing parameters featureName/can_access/email"            response.Status = http.StatusUnprocessableEntity            json.NewEncoder(w).Encode(response)            return        }
查看完整描述

1 回答

?
慕姐8265434

TA贡献1813条经验 获得超2个赞

将注释移动到答案


我在您的代码中看到一个问题,您共享的链接是,但在代码中,导入是 如果您使用下面的代码进行验证https://github.com/go-playground/validatorgopkg.in/validator.v2go-playground validator


import https://github.com/go-playground/validator


validatorInstance:=validator.New()

validatorInstance.Struct(user)


查看完整回答
反对 回复 2022-09-05
  • 1 回答
  • 0 关注
  • 105 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号