如何验证 Gin-Gonic 中的标题和正文?

我有一个 Gin 程序。当请求到来时,我希望变量data(type ProductCreate) 的所有字段都具有值:(UserId来自标头)和Name,Price(来自 JSON 正文)。我使用了下面的代码并且它有效:


package main


import (

    "fmt"

    "github.com/gin-gonic/gin"

)


type ProductCreate struct {

    UserId int    `header:"user-id"`

    Name   string `json:"name"`

    Price  int    `json:"price"`

}


func main() {

    r := gin.Default()


    r.POST("/product", func(c *gin.Context) {

        var data ProductCreate


        // bind the headers to data

        if err := c.ShouldBindHeader(&data); err != nil {

            c.JSON(400, err.Error())

            return

        }


        // bind the body to data

        if err := c.ShouldBindJSON(&data); err != nil {

            c.JSON(400, err.Error())

            return

        }


        c.JSON(200, data)

    })


    r.Run(":8080")

}

之后,我想确保必须提供字段,所以我ProductCreate像这样编辑结构:


type ProductCreate struct {

    UserId int    `header:"user-id" binding:"required"`

    Name   string `json:"name" binding:"required"`

    Price  int    `json:"price" binding:"required"`

}

然后当我再次测试时它引发了意外错误:


Key: 'ProductCreate.Name' Error:Field validation for 'Name' failed on the 'required' tag\nKey: 'ProductCreate.Price' Error:Field validation for 'Price' failed on the 'required' tag


我意识到错误发生在这个地方:


// bind the headers to data

if err := c.ShouldBindHeader(&data); err != nil {

   c.JSON(400, err.Error())

   return

}

有什么办法可以解决我的问题吗?


小唯快跑啊
浏览 94回答 1
1回答

慕尼黑8549860

你能试试这个吗?curl --location --request POST 'http://localhost:8080/product' \--header 'user-id: 20' \--data-raw '{    "name": "sr"   }'我试过你的代码,它工作得很好。{    "UserId": 20,    "name": "sr",    "price": 0}Gin 版本:github.com/gin-gonic/gin v1.8.1 // 间接索恩:package mainimport (    "github.com/gin-gonic/gin")type ProductCreate struct {    Name  *string `json:"name" binding:"required"`    Price *int    `json:"price" binding:"required"`}type Header struct {    UserId *int `header:"user-id" binding:"required"`}func main() {    r := gin.Default()    r.POST("/product", func(c *gin.Context) {        data := &ProductCreate{}        header := &Header{}        // bind the headers to data        if err := c.ShouldBindHeader(header); err != nil {            c.JSON(400, err.Error())            return        }        // bind the body to data        if err := c.ShouldBindJSON(data); err != nil {            c.JSON(400, err.Error())            return        }        c.JSON(200, data)    })    r.Run(":8080")}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go