gin
gin copied to clipboard
Error ShouldBindBodyWith EOF
Description
How to reproduce
Middleware
package middleware
import (
"*/src/models"
"*/src/util"
"fmt"
"net/http"
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
)
//BodyValidationCheckReservations
func BodyValidationCheckReservations() gin.HandlerFunc {
return func(c *gin.Context) {
var bodySchema models.RequestCheckReservations
if err := c.ShouldBindBodyWith(&bodySchema, binding.JSON); err != nil {
util.LOGGER.Error("error parser body CheckReservations MBH ", err.Error())
fmt.Printf("bodySchema %s\n", bodySchema)
c.AbortWithStatusJSON(http.StatusBadRequest, ErrorResponse400())
return
}
c.Next()
}
}
Model
package models
type RequestCheckReservations struct {
Rut string `json:"rut" binding:"required"`
}
Expectations
curl --location --request POST 'localhost:8080/checkReservations' \
--header 'x-country: data' \
--header 'x-commerce: data' \
--header 'x-chref: data' \
--header 'x-rhsref: data' \
--header 'x-cmref: data' \
--header 'Content-Type: application/json' \
--data-raw '{
"rut": "123456789-0"
}'
Validations ok!
Actual result
go run .\main.go
[GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.
[GIN-debug] [WARNING] Running in "debug" mode. Switch to "release" mode in production.
- using env: export GIN_MODE=release
- using code: gin.SetMode(gin.ReleaseMode)
[GIN-debug] POST /checkReservations/ --> http-adapter/src/controller.(*ControllerStruct).CheckReservationsController-fm (9 handlers)
[GIN-debug] POST /payReservation/ --> http-adapter/src/middleware.BodyValidationPayReservations.func1 (8 handlers)
INFO[2022-06-20 20:31:51.7665] http-adapterrunning port: 8080, version: 1.0.0
[GIN-debug] [WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value.
Please check https://pkg.go.dev/github.com/gin-gonic/gin#readme-don-t-trust-all-proxies for details.
[GIN-debug] Listening and serving HTTP on :8080
[GIN-debug] redirecting request 307: /checkReservations/ --> /checkReservations/
2022/06/20 20:31:59 Respondiendo al cliente ::1 Body:
ERRO[2022-06-20 20:31:59.6768] error parser body CheckReservations MBH EOF
bodySchema {}
Environment
- go version: 1.16.15
- gin version (or commit ref): v1.7.7
- operating system: W11
Whether the request body has been read
Whether the request body has been read
but, the error is EOF, the validations failing
@mbaezahuenupil Why not try to print the request body before calling ShouldBindBodyWith
which checks the body is not empty? That becomes clear where the EOF comes from.