亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

正確的請求正文被 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": "[email protected]",    "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 關注
  • 104 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號