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

  • go version: 1.21.3
  • gin version (or commit ref): v1.9.1
  • operating system: Ubuntu

Comment From: VarusHsu

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"`
}
  • because c.String(http.StatusOK, body.Msg) cover c.Status(http.StatusBadRequest) always.