如何在Gin-Gonic中验证请求头和请求体?

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

How to validate headers and body in Gin-Gonic?

问题

我有一个Gin程序。当有请求到来时,我希望变量data(类型为ProductCreate)的所有字段都有值:UserId(来自请求头)以及NamePrice(来自JSON请求体)。我使用了下面的代码,它可以工作:

  1. package main
  2. import (
  3. "fmt"
  4. "github.com/gin-gonic/gin"
  5. )
  6. type ProductCreate struct {
  7. UserId int `header:"user-id"`
  8. Name string `json:"name"`
  9. Price int `json:"price"`
  10. }
  11. func main() {
  12. r := gin.Default()
  13. r.POST("/product", func(c *gin.Context) {
  14. var data ProductCreate
  15. // 将请求头绑定到data
  16. if err := c.ShouldBindHeader(&data); err != nil {
  17. c.JSON(400, err.Error())
  18. return
  19. }
  20. // 将请求体绑定到data
  21. if err := c.ShouldBindJSON(&data); err != nil {
  22. c.JSON(400, err.Error())
  23. return
  24. }
  25. c.JSON(200, data)
  26. })
  27. r.Run(":8080")
  28. }

之后,我想确保这些字段必须提供,所以我将ProductCreate结构体修改为:

  1. type ProductCreate struct {
  2. UserId int `header:"user-id" binding:"required"`
  3. Name string `json:"name" binding:"required"`
  4. Price int `json:"price" binding:"required"`
  5. }

然后,当我再次测试时,出现了意外的错误:

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

我意识到错误发生在这里:

  1. // 将请求头绑定到data
  2. if err := c.ShouldBindHeader(&data); err != nil {
  3. c.JSON(400, err.Error())
  4. return
  5. }

有没有解决这个问题的方法?

英文:

I have a Gin program. When a request comes, I want all of the fields of the variable data (type ProductCreate) to have values: UserId (from headers) and Name, Price (from JSON body). I used the below code and it works:

  1. package main
  2. import (
  3. "fmt"
  4. "github.com/gin-gonic/gin"
  5. )
  6. type ProductCreate struct {
  7. UserId int `header:"user-id"`
  8. Name string `json:"name"`
  9. Price int `json:"price"`
  10. }
  11. func main() {
  12. r := gin.Default()
  13. r.POST("/product", func(c *gin.Context) {
  14. var data ProductCreate
  15. // bind the headers to data
  16. if err := c.ShouldBindHeader(&data); err != nil {
  17. c.JSON(400, err.Error())
  18. return
  19. }
  20. // bind the body to data
  21. if err := c.ShouldBindJSON(&data); err != nil {
  22. c.JSON(400, err.Error())
  23. return
  24. }
  25. c.JSON(200, data)
  26. })
  27. r.Run(":8080")
  28. }

After that, I wanted to make sure that fields must be provided so I edited the ProductCreate struct like this:

  1. type ProductCreate struct {
  2. UserId int `header:"user-id" binding:"required"`
  3. Name string `json:"name" binding:"required"`
  4. Price int `json:"price" binding:"required"`
  5. }

Then it raised an unexpected error when I tested it again:

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

I realized the error happened at this:

  1. // bind the headers to data
  2. if err := c.ShouldBindHeader(&data); err != nil {
  3. c.JSON(400, err.Error())
  4. return
  5. }

Is there any solution to resolve my problem?

答案1

得分: 2

你好!以下是翻译好的内容:

你能试试这个吗?

  1. curl --location --request POST 'http://localhost:8080/product' \
  2. --header 'user-id: 20' \
  3. --data-raw '{
  4. "name": "sr"
  5. }'

我尝试了你的代码,它完美地工作了。

  1. {
  2. "UserId": 20,
  3. "name": "sr",
  4. "price": 0
  5. }

Gin版本:github.com/gin-gonic/gin v1.8.1 // indirect

解决方案:

  1. package main
  2. import (
  3. "github.com/gin-gonic/gin"
  4. )
  5. type ProductCreate struct {
  6. Name *string `json:"name" binding:"required"`
  7. Price *int `json:"price" binding:"required"`
  8. }
  9. type Header struct {
  10. UserId *int `header:"user-id" binding:"required"`
  11. }
  12. func main() {
  13. r := gin.Default()
  14. r.POST("/product", func(c *gin.Context) {
  15. data := &ProductCreate{}
  16. header := &Header{}
  17. // 将头部绑定到数据
  18. if err := c.ShouldBindHeader(header); err != nil {
  19. c.JSON(400, err.Error())
  20. return
  21. }
  22. // 将请求体绑定到数据
  23. if err := c.ShouldBindJSON(data); err != nil {
  24. c.JSON(400, err.Error())
  25. return
  26. }
  27. c.JSON(200, data)
  28. })
  29. r.Run(":8080")
  30. }
英文:

Can you try this?

  1. curl --location --request POST 'http://localhost:8080/product' \
  2. --header 'user-id: 20' \
  3. --data-raw '{
  4. "name": "sr"
  5. }'

I tried your code and it works perfectly.

  1. {
  2. "UserId": 20,
  3. "name": "sr",
  4. "price": 0
  5. }

Gin version: github.com/gin-gonic/gin v1.8.1 // indirect

Soln:

  1. package main
  2. import (
  3. "github.com/gin-gonic/gin"
  4. )
  5. type ProductCreate struct {
  6. Name *string `json:"name" binding:"required"`
  7. Price *int `json:"price" binding:"required"`
  8. }
  9. type Header struct {
  10. UserId *int `header:"user-id" binding:"required"`
  11. }
  12. func main() {
  13. r := gin.Default()
  14. r.POST("/product", func(c *gin.Context) {
  15. data := &ProductCreate{}
  16. header := &Header{}
  17. // bind the headers to data
  18. if err := c.ShouldBindHeader(header); err != nil {
  19. c.JSON(400, err.Error())
  20. return
  21. }
  22. // bind the body to data
  23. if err := c.ShouldBindJSON(data); err != nil {
  24. c.JSON(400, err.Error())
  25. return
  26. }
  27. c.JSON(200, data)
  28. })
  29. r.Run(":8080")
  30. }

huangapple
  • 本文由 发表于 2022年7月22日 15:13:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/73076450.html
匿名

发表评论

匿名网友

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

确定