登录
首页 >  Golang >  Go问答

Gin中间件绑定问题的解决方案

来源:stackoverflow

时间:2024-03-20 12:39:29 412浏览 收藏

**Gin 中间件绑定问题解决方案** 在使用 Gin 框架绑定中间件时,出现键“itempostrequest.name”错误“必需”标记验证失败的问题。解决方法是确保请求头中包含 Content-Type application/json,因为 Gin 在默认情况下无法自动解析 JSON 请求体。通过添加中间件 c.next(),可以将控制权传递给后续中间件或处理程序,并在出错时访问 c.errors 中的错误消息。

问题内容

我尝试为杜松子酒验证提供自定义错误消息并遵循此线程中的建议:https://github.com/gin-gonic/gin/issues/430

我正在尝试用这种方式绑定杜松子酒中间件:

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 发送请求,但尽管我发送了正确的请求,但它总是说: 键:“itempostrequest.name”错误:“必需”标记上“名称”的字段验证失败

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

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

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


正确答案


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

今天关于《Gin中间件绑定问题的解决方案》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>