3

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?

1 Answers1

1

I got this working by modifying UnmarshalJSON function a bit. I don't have anything to explain as I'm also new, but will try, what's different is that we are converting byte data into a string by json.Unmarshal.Then we trim the space on string and appends it to the field or the original string

type trim string

func (t *trim) UnmarshalJSON(data []byte) error {
    var s string
    if err := json.Unmarshal(data, &s); err != nil {
        return err
    }
    *t = trim(strings.TrimSpace(s))
    fmt.Printf("these are the strings: '%s'\n", *t)
    return nil
}

Here is the playground if you want to try it yourself https://go.dev/play/p/BuxvMQibVsn

Perfectó
  • 91
  • 6