Skip to content

Commit 6bf4c7c

Browse files
author
Jamie Tanna
authored
Allow binding types as parameters through String() methods (#638)
If trying to use a type, such as a UUID in a path parameter, we'd previously receive an error at runtime to say that `types.UUID` isn't supported. As this is a common use case, we should support it. Instead of adding support for it manually, we can instead look at whether the there's a `String` method, and if so use that to serialise the field.
1 parent d4b9b85 commit 6bf4c7c

2 files changed

Lines changed: 11 additions & 1 deletion

File tree

styleparam.go

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -382,7 +382,12 @@ func primitiveToString(value interface{}) (string, error) {
382382
case reflect.String:
383383
output = v.String()
384384
default:
385-
return "", fmt.Errorf("unsupported type %s", reflect.TypeOf(value).String())
385+
v, ok := value.(fmt.Stringer)
386+
if !ok {
387+
return "", fmt.Errorf("unsupported type %s", reflect.TypeOf(value).String())
388+
}
389+
390+
output = v.String()
386391
}
387392
return output, nil
388393
}

styleparam_test.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -629,6 +629,11 @@ func TestStyleParam(t *testing.T) {
629629
assert.NoError(t, err)
630630
assert.EqualValues(t, "1.05", result)
631631

632+
uuidValue := uuid.MustParse("c2d07ba4-5106-4eab-bcad-0bd6068dcb1a")
633+
result, err = StyleParamWithLocation("simple", false, "foo", ParamLocationQuery, types.UUID(uuidValue))
634+
assert.NoError(t, err)
635+
assert.EqualValues(t, "c2d07ba4-5106-4eab-bcad-0bd6068dcb1a", result)
636+
632637
// Test that we handle optional fields
633638
type TestObject2 struct {
634639
FirstName *string `json:"firstName"`

0 commit comments

Comments
 (0)