我正在尝试使用验证器根据此结构验证请求正文。但是在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)
- 1 回答
- 0 关注
- 105 浏览
添加回答
举报
0/150
提交
取消
