Gin: Binding uuid.UUID using ShouldBind

Created on 2 Jul 2020  路  2Comments  路  Source: gin-gonic/gin

Description

Binding uuid.UUID using ShouldBind gives error ["45e1f85e-bca5-458d-bd9c-c56edd8f847b"] is not valid value for uuid.UUID

How to reproduce

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)
    }
}

Actual result

["45e1f85e-bca5-458d-bd9c-c56edd8f847b"] is not valid value for uuid.UUID

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 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.

All 2 comments

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!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

mastrolinux picture mastrolinux  路  3Comments

CodingPapi picture CodingPapi  路  3Comments

ghost picture ghost  路  3Comments

gplume picture gplume  路  3Comments

lilee picture lilee  路  3Comments