Gin: Bind() default values

Created on 26 Sep 2015  路  4Comments  路  Source: gin-gonic/gin

Hi! I have a code:

    type select struct {
        Active bool     `form:"active" json:"active" xml:"active"`  //def: true
        Nick   string   `form:"nick" json:"nick" xml:"nick"`        //def: "anonymous"
        // ........
    }
    var s struct
    c.Bind(&s)

Necessary to achieve these results:

http://......?active=true&nick=aa    // s.Active: true,   s.Nick: "aa"

http://......?active=false&nick=bb   // s.Active: false,  s.Nick: "bb"

http://......?none                   // s.Active: true,   s.Nick: "anonymous"

Are there ways to achieve these results?

Most helpful comment

Actually I already found better way.

var args struct {
    Active bool   `form:"active" json:"active" xml:"active"` //def: true
    Nick   string `form:"nick" json:"nick" xml:"nick"`       //def: "anonymous"
}
args.Active = true
args.Nick = "anonymous"

c.Bind(&args)

Maybe it can help someone)

All 4 comments

:+1:

I'm late a bit, but:

var (
    defaultActive = false
    defaultNick   = "anonymous"
)

var args struct {
    Active *bool   `form:"active" json:"active" xml:"active"` //def: true
    Nick   *string `form:"nick" json:"nick" xml:"nick"`       //def: "anonymous"
}

c.Bind(&args)

if args.Active == nil {
    args.Active = &defaultActive
}

if args.Nick == nil {
    args.Nick = &defaultNick
}

Actually I already found better way.

var args struct {
    Active bool   `form:"active" json:"active" xml:"active"` //def: true
    Nick   string `form:"nick" json:"nick" xml:"nick"`       //def: "anonymous"
}
args.Active = true
args.Nick = "anonymous"

c.Bind(&args)

Maybe it can help someone)

:+1:

Was this page helpful?
0 / 5 - 0 ratings

Related issues

nxvl picture nxvl  路  3Comments

oryband picture oryband  路  3Comments

gplume picture gplume  路  3Comments

mastrolinux picture mastrolinux  路  3Comments

boneq picture boneq  路  3Comments