gin icon indicating copy to clipboard operation
gin copied to clipboard

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

Open giose86 opened this issue 2 years ago • 1 comments

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

giose86 avatar Dec 05 '23 12:12 giose86

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.

VarusHsu avatar Dec 07 '23 11:12 VarusHsu