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 (
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 *