Binding uuid.UUID using ShouldBind gives error ["45e1f85e-bca5-458d-bd9c-c56edd8f847b"] is not valid value for uuid.UUID
Used Postman to make request:
Content-Type: multipart/form-data
Body with form-data:
key: colorID
value: 45e1f85e-bca5-458d-bd9c-c56edd8f847b
// Go model in which I want to map
type Test struct {
colorID uuid.UUID `binding:"required" form:"colorID"`
}
func test(ctx *gin.Context) {
t := Test{}
err := ctx.ShouldBind(&t)
if err != nil {
panic(err)
}
}
["45e1f85e-bca5-458d-bd9c-c56edd8f847b"] is not valid value for uuid.UUID
I have the same issue when attempting to bind with url-safe base64 values, I couldn't find a way to define a custom type handle the binding and error handling on its own and had to basically decode the string and handle the error in every handler. it's possible to use custom types when using json.Unmarshal, but, even though ShouldBind falls back to using enconding/json as well, the input value isn't json in those cases (it's a string for uuid.UUID and my case), and the binding fails.
Maybe TextUnmarshaler could be used as another fallback? uuid.UUID implements the UnmarshalText method, and it would be easy to do for custom types too.
It could be seen as API-breaking though, since TextUnmarshaler is a pretty common interface, people using ShouldBind to bind to structs with non-primitive fields may have surprises.
I have this problem too, but I found solution!
You can change uuid.UUID to string and place in binding uuid tag!
Most helpful comment
I have the same issue when attempting to bind with url-safe base64 values, I couldn't find a way to define a custom type handle the binding and error handling on its own and had to basically decode the string and handle the error in every handler. it's possible to use custom types when using
json.Unmarshal, but, even thoughShouldBindfalls back to usingenconding/jsonas well, the input value isn't json in those cases (it's a string foruuid.UUIDand my case), and the binding fails.Maybe
TextUnmarshalercould be used as another fallback?uuid.UUIDimplements theUnmarshalTextmethod, and it would be easy to do for custom types too.It could be seen as API-breaking though, since
TextUnmarshaleris a pretty common interface, people usingShouldBindto bind to structs with non-primitive fields may have surprises.