• go version: 1.12.4
  • gin version (or commit ref): 1.3.0/1.4.0
  • operating system: Debian stretch

Description

Hi all, I'm trying to set the default value in my struct and it's actually working with ShouldBind and not ShouldBindJSON. Here is my sample code:

type t1 struct {
    Currency string `form:"currency,default=eur"`
}

type t2 struct {
    Currency string `json:"currency,default=eur"`
}

func Test1(c *gin.Context) {
    var s t1
    if err := c.ShouldBind(&s); err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
        return
    }
    c.JSON(http.StatusOK, s)
}

func Test2(c *gin.Context) {
    var s t2
    if err := c.ShouldBindJSON(&s); err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
        return
    }
    c.JSON(http.StatusOK, s)
}

With curl -XPOST localhost:8080/api/v1/test1 then result is of course {"Currency":"eur"} but for curl -XPOST localhost:8080/api/v1/test2 result is {"error":"EOF"}

Any specific reason why it's failing with ShouldBindJSON?

Comment From: thinkerou

@Lord-Y form data support set default value, but I guess json should not support. https://github.com/gin-gonic/gin/blob/master/binding/form_mapping.go

Comment From: Djolivald

but I guess json should not support

Any reason why? It would be nice to have really...

Comment From: Lord-Y

I would be really nice yeah for both json and xml (for people that use it).

Comment From: sidai

I happened to find a library which supports the default tag. https://github.com/mcuadros/go-defaults

This might solve the problem. Just set the default value before trying to invoke c.ShouldBind(&s)

Comment From: blackpiglet

Don't understand why JSON and many others not support default value. go-defaults mentioned by @sidai is a good option, but I still think set default value at register stage rather than calling stage is better.

Comment From: avarf

It would be great if you add the default value to json too

Comment From: rmrf

json support default value is really needed feature.

Comment From: shushenghong

json need default value too

Comment From: MQPearth

json need default value too 😆

Comment From: nityamehrotra1

json need default value too

Comment From: yinebebt

json need default value too