golang solves the problem of Gin framework, the body parameter can only be read once

When using the gin framework, it is found that the requested body data is only allowed to be read once.

The step of reading BindJSON for the second time reports an error: EOF.

Using the golang official library, this method is recommended 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",
    })
   
}

Leave a Reply

Your email address will not be published.

en_USEnglish