I have a struct like this
type Data struct {
Foo string `json:"foo" binding:"required"`
}
And I use ShouldBind to bind query or json body to the struct.
data := Data{}
err := ctx.ShouldBind(&data)
I was wondering what is the best practice to trim white space for the string field?
transform {"foo": " bar "} to struct {"foo": "bar"}
- I have tried using custom string type, and add custom UnmarshalJSON function, but it won't work for ctx.shouldBind if it is query.
type Data struct {
Foo TrimSpaceString `json:"foo" binding:"required"`
}
type TrimSpaceString string
func (t *TrimSpaceString) UnmarshalJSON(data []byte) error {
data = bytes.Trim(data, "\"")
data = bytes.Trim(data, " ")
*t = TrimSpaceString(strings.TrimSpace(string(data)))
return nil
}
- I also tried to use conform and add tag for struct. But I have to add conform.Strings(data) after bind it and it is not convinence.
type Data struct {
Foo TrimSpaceString `json:"foo" binding:"required" conform:"trim"`
}
err := ctx.ShouldBind(&data)
conform.Strings(&data)
- Should I custom a Binding and trim string inside Binding?