我正在尝试编写一个中间件,我将在其中对请求正文进行 json 模式验证。验证后,我需要再次使用请求正文。但我无法弄清楚如何做到这一点。我参考了这篇文章 并找到了一种访问正文的方法。但是一旦使用了请求正文,我就需要它可用于我的下一个函数。
这是示例代码:
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"
}