Golang solves the problem that the body parameter can only be read once in the Gin framework
When using the gin framework, it is found that the requested body data can only be read once.
An error is reported in the step of reading BindJSON for the second time: EOF.
Use the official golang library to recommend this method to solve this problem
package main
import (
"fmt"
"gopkg.in/gin-gonic/gin.v1"
"net/http"
"io/ioutil"
"bytes"
"encoding/json"
)
type Person struct{
Name string `json:"name"`
Phone int64 `json:"phone"`
Data string `json:"data"`
}
func main(){
router := gin.Default()
router.POST("/",HelloMiddleware(),Hello)
router.Run(":8000")
}
func HelloMiddleware() gin.HandlerFunc {
return func(ctx *gin.Context) {
data,err := ctx.GetRawData()
if err != nil{
fmt.Println(err.Error())
}
fmt.Printf("data: %v\n",string(data))
ctx.Request.Body = ioutil.NopCloser(bytes.NewBuffer(data)) // 关键点
ctx.Next()
}
}
func Hello(ctx *gin.Context){
var info Person
err := ctx.BindJSON(&info)
if err != nil{
fmt.Println(err.Error())
}
fmt.Printf("info: %#v\n",info)
ctx.JSON(http.StatusOK, gin.H{
"code":200,
"msg":"success",
})
}