亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何驗證 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 關注
  • 102 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號