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 (
type Person struct{
    Name string `json:"name"`
    Phone int64 `json:"phone"`
    Data string `json:"data"`
func main(){
    router := gin.Default()
func HelloMiddleware() gin.HandlerFunc {
    return func(ctx *gin.Context) {
        data,err := ctx.GetRawData()
        if err != nil{
        fmt.Printf("data: %v\n",string(data)) 
        ctx.Request.Body = ioutil.NopCloser(bytes.NewBuffer(data)) //

func Hello(ctx *gin.Context){
    var info Person
    err := ctx.BindJSON(&info)
    if err != nil{
    fmt.Printf("info: %#v\n",info)
    ctx.JSON(http.StatusOK, gin.H{

Leave a Reply

Your email address will not be published. Required fields are marked *