为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Go
小唯快跑啊 2023-01-03 16:56:28
我有一个 Gin 程序。当请求到来时,我希望变量data(type ProductCreate) 的所有字段都具有值:(UserId来自标头)和Name,Price(来自 JSON 正文)。我使用了下面的代码并且它有效:package mainimport (    "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 dataif err := c.ShouldBindHeader(&data); err != nil {   c.JSON(400, err.Error())   return}有什么办法可以解决我的问题吗?
查看完整描述

1 回答

?
慕尼黑8549860

TA贡献1818条经验 获得超11个赞

你能试试这个吗?


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 main


import (

    "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")

}


查看完整回答
反对 回复 2023-01-03
  • 1 回答
  • 0 关注
  • 63 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信