gin-gonic / gin

Gin is a HTTP web framework written in Go (Golang). It features a Martini-like API with much better performance -- up to 40 times faster. If you need smashing performance, get yourself some Gin.
https://gin-gonic.com/
MIT License
78.03k stars 7.97k forks source link

ShouldBind does not go in error when content type is not defined #3788

Open giose86 opened 9 months ago

giose86 commented 9 months ago

Description

The ShouldBind method does not return an error when the request is missing the 'Content-Type' header and payload is not provided. I would expect an error because the defined POST API requires a specific json payload in input. This expectation is correct? Or i am missing something? Thanks :)

How to reproduce

package main

import (
    "net/http"

    "github.com/gin-gonic/gin"
)

func main() {
    g := gin.Default()
    g.POST("/hello", func(c *gin.Context) {
        var body TestBody
        err := c.ShouldBind(&body)
        if err != nil {
            c.Status(http.StatusBadRequest)
        }
        c.String(http.StatusOK, body.Msg)
    })
    err := g.Run(":9000")
    if err != nil {
        return
    }
}

type TestBody struct {
    Msg string `json:"msg"`
}

Expectations

$ curl -v http://localhost:9000/hello -X POST -d ''"
< HTTP/1.1 400 Bad request

Actual result

$ curl -v http://localhost:9000/hello -X POST -d ''"
 HTTP/1.1 200 OK

Environment

VarusHsu commented 9 months ago
package main

import (
    "net/http"

    "github.com/gin-gonic/gin"
)

func main() {
    g := gin.Default()
    g.POST("/hello", func(c *gin.Context) {
        var body TestBody
        err := c.ShouldBind(&body)
        if err != nil {
            c.Status(http.StatusBadRequest)
            return
        }
        c.String(http.StatusOK, body.Msg)
    })
    err := g.Run(":9000")
    if err != nil {
        return
    }
}

type TestBody struct {
    Msg string `json:"msg" binding:"required"`
}