如何使用Context.Request.Body并保留它? [英] How to use Context.Request.Body and retain it?
问题描述
我正在尝试编写一个中间件,在其中我将针对请求主体进行json模式验证.验证之后,我需要再次使用请求正文.但是我无法弄清楚如何做到这一点.我提到了这篇文章并找到了一种进入身体的方法.但是,一旦使用了请求正文,我就需要下一个函数可用.
I am trying to write a middleware where I will be doing a json schema validation against the request body. After the validation, I need to use the request body again. But I am not able to figure out how this can be done. I referred this post and found a way to access the body. But once the request body is used, I need that available to my next function.
这是示例代码:
package main
import (
"fmt"
"io/ioutil"
"net/http"
"github.com/gin-gonic/gin"
//"github.com/xeipuuv/gojsonschema"
)
func middleware() gin.HandlerFunc {
return func(c *gin.Context) {
//Will be doing json schema validation here
body := c.Request.Body
x, _ := ioutil.ReadAll(body)
fmt.Printf("%s \n", string(x))
fmt.Println("I am a middleware for json schema validation")
c.Next()
return
}
}
type E struct {
Email string
Password string
}
func test(c *gin.Context) {
//data := &E{}
//c.Bind(data)
//fmt.Println(data) //prints empty as json body is already used
body := c.Request.Body
x, _ := ioutil.ReadAll(body)
fmt.Printf("body is: %s \n", string(x))
c.JSON(http.StatusOK, c)
}
func main() {
router := gin.Default()
router.Use(middleware())
router.POST("/test", test)
//Listen and serve
router.Run("127.0.0.1:8080")
}
当前输出:
{
"email": "test@test.com",
"password": "123"
}
I am a middleware for json schema validation
body is:
预期输出:
{
"email": "test@test.com",
"password": "123"
}
I am a middleware for json schema validation
body is: {
"email": "test@test.com",
"password": "123"
}
推荐答案
Thellimist所说的话,但用更多的词来表达.
What Thellimist said, but in more words.
您需要捕捉并恢复"身体.Body是一个缓冲区,这意味着一旦您阅读它,它就会消失.因此,如果您将其捕获并放回",则可以再次访问它.
You need to "catch and restore" the Body. The Body is a buffer, that means that once you read it, its gone. So, if you catch it and "put it back", you can access it again.
检查此答案,我认为这是您要查找的内容: https://stackoverflow.com/a/47295689/3521313
Check this answer, I think this is what you are looking for: https://stackoverflow.com/a/47295689/3521313
这篇关于如何使用Context.Request.Body并保留它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!