请求体被Go中的验证器视为无效。

huangapple go评论86阅读模式
英文:

Correct request body is deemed to be invalid by validator in Go

问题

我正在尝试使用validator来根据这个结构体验证请求体。但是在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:

// 请求体
{
    "featureName": "crypto",
    "email": "test5@gmail.com",
    "can_access": true
}

// 响应体
{
    "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()

	// 将请求体解码为user结构体
	if err := json.NewDecoder(r.Body).Decode(&user); err != nil {
		response.Message = "Error"
		response.Status = http.StatusInternalServerError
		json.NewEncoder(w).Encode(response)
		return
	} else {
		// 验证结构体以检查所有字段是否正确
		// 在这里失败!
		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
		} else {
			// 执行插入语句到数据库
			stmt := `INSERT INTO features (user_id, feature_name, can_access) SELECT id, ?, ? FROM users WHERE email=?`
			if _, err = db.Exec(stmt, &user.FeatureName, &user.CanAccess, &user.Email); err != nil {
				response.Message = "Error"
				response.Status = http.StatusInternalServerError
				json.NewEncoder(w).Encode(response)
				return
			} else {
				response.Message = "Success"
				response.Status = http.StatusOK
				json.NewEncoder(w).Encode(response)
				return
			}

		}

	}

}
英文:

I am trying to validate the request body according to this struct using validator. But in Postman it always throws an error when validating the struct. I just want all values to be required when making a request.

package model
type User struct {
FeatureName string `json:"featureName" validate:"required"`
Email       string `json:"email" validate:"required"`
CanAccess   *bool  `json:"can_access" validate:"required"`
}

I have tried sending this as the request body on Postman:

// Request body
{
"featureName": "crypto",
"email": "test5@gmail.com",
"can_access": true
}
// Response body
{
"status": 422,
"message": "Missing parameters featureName/can_access/email"
}

Code:

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
} else {
// Execute insert statement to database
stmt := `INSERT INTO features (user_id, feature_name, can_access) SELECT id, ?, ? FROM users WHERE email=?`
if _, err = db.Exec(stmt, &user.FeatureName, &user.CanAccess, &user.Email); err != nil {
response.Message = "Error"
response.Status = http.StatusInternalServerError
json.NewEncoder(w).Encode(response)
return
} else {
response.Message = "Success"
response.Status = http.StatusOK
json.NewEncoder(w).Encode(response)
return
}
}
}
}
</details>
# 答案1
**得分**: 1
将评论移动到答案中
我看到你的代码中存在一个问题,你分享的链接是`https://github.com/go-playground/validator`,但是在代码中导入的是`gopkg.in/validator.v2`。如果你正在使用`go-playground validator`,请使用以下代码进行验证:
```go
import "github.com/go-playground/validator"
validatorInstance := validator.New()
validatorInstance.Struct(user)
英文:

> Moving Comment to answer

I see a problem in your code the link you have shared is https://github.com/go-playground/validator but in the code, import is gopkg.in/validator.v2
If you are using the go-playground validator Use below code to validate

import https://github.com/go-playground/validator
validatorInstance:=validator.New()
validatorInstance.Struct(user)

huangapple
  • 本文由 发表于 2021年6月3日 12:14:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/67815275.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定