Gin绑定中间件总是失败。

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

Gin binding middleware always fail

问题

我正在尝试为gin验证设置自定义错误消息,并遵循此线程中的建议:https://github.com/gin-gonic/gin/issues/430

我尝试以以下方式使用gin绑定中间件:

package main

import (
	"fmt"
	"net/http"
	"github.com/gin-gonic/gin"
)

type itemPostRequest struct {
	Name string `json:"name" binding:"required"`
}

func main() {
	router := gin.Default()
	router.Use(func (c *gin.Context) {
		c.Next()
		fmt.Println(c.Errors)
	})
	router.POST("/item", gin.Bind(itemPostRequest{}), func (c *gin.Context) {
		fmt.Println("Im inside handler")
		req := c.MustGet(gin.BindKey).(*itemPostRequest)
		fmt.Println(req)
		c.JSON(http.StatusOK, gin.H{"success": true})
	})
	router.Run()
}

我使用Postman发送请求,尽管我发送了正确的请求,但它总是显示:
Key: 'itemPostRequest.Name' Error:Field validation for 'Name' failed on the 'required' tag

如果我不使用绑定中间件:

router.POST("/item", func (c *gin.Context) {
  ...

它可以工作,但我希望能够在进入处理程序之前绑定并返回错误,就像线程中的建议一样。为什么这样不起作用?谢谢。

英文:

Im trying to have custom error messages for gin validation & followed the advice in this thread: https://github.com/gin-gonic/gin/issues/430

Im trying the gin binding midddleware this way:

package main

import (
	"fmt"
	"net/http"
	"github.com/gin-gonic/gin"
)

type itemPostRequest struct {
	Name string `json:"name" binding:"required"`
}

func main() {
	router := gin.Default()
	router.Use(func (c *gin.Context) {
		c.Next()
		fmt.Println(c.Errors)
	})
	router.POST("/item", gin.Bind(itemPostRequest{}), func (c *gin.Context) {
		fmt.Println("Im inside handler")
		req := c.MustGet(gin.BindKey).(*itemPostRequest)
		fmt.Println(req)
		c.JSON(http.StatusOK, gin.H{"success": true})
	})
	router.Run()
}

I send the request using Postman but although I have sent the correct request, it always say:
Key: 'itemPostRequest.Name' Error:Field validation for 'Name' failed on the 'required' tag

If I don't use the binding middleware:

router.POST("/item", func (c *gin.Context) {
  ...

It works but i want to be able to bind and return error before I go to the handler, just like the advice on the thread. Why is this not working? Thank you

答案1

得分: 0

感谢评论,我意识到我忘记了Content-Type为application/json。我之前使用c.ShouldBindWithJSON时没有意识到这一点,因为它不需要这个头部。

英文:

thx to the comment, I realized I missed Content-Type application/json. I didn't realize this because I used c.ShouldBindWithJSON before and it didnt need this header.

huangapple
  • 本文由 发表于 2021年7月12日 08:58:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/68340917.html
匿名

发表评论

匿名网友

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

确定