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

我正在尝试使用验证器根据此结构验证请求正文。但是在Postman中,在验证结构时,它总是会抛出错误。我只希望在提出请求时需要所有值。


package model


type 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 controller


import (

    "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

        }

慕田峪7331174
浏览 106回答 1
1回答

慕姐8265434

将注释移动到答案我在您的代码中看到一个问题,您共享的链接是,但在代码中,导入是 如果您使用下面的代码进行验证https://github.com/go-playground/validatorgopkg.in/validator.v2go-playground validatorimport https://github.com/go-playground/validatorvalidatorInstance:=validator.New()validatorInstance.Struct(user)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go