From 650a2f4ff56a1124772a1432fd4c938e94c59c1f Mon Sep 17 00:00:00 2001 From: Jamie Tanna Date: Wed, 29 Jun 2022 16:11:46 +0100 Subject: [PATCH] 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. --- pkg/runtime/styleparam.go | 7 ++++++- pkg/runtime/styleparam_test.go | 5 +++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/pkg/runtime/styleparam.go b/pkg/runtime/styleparam.go index ae2f33b2d..6c01def1b 100644 --- a/pkg/runtime/styleparam.go +++ b/pkg/runtime/styleparam.go @@ -382,7 +382,12 @@ func primitiveToString(value interface{}) (string, error) { case reflect.String: output = v.String() default: - return "", fmt.Errorf("unsupported type %s", reflect.TypeOf(value).String()) + v, ok := value.(fmt.Stringer) + if !ok { + return "", fmt.Errorf("unsupported type %s", reflect.TypeOf(value).String()) + } + + output = v.String() } return output, nil } diff --git a/pkg/runtime/styleparam_test.go b/pkg/runtime/styleparam_test.go index 821c1a90b..ff7e52d7c 100644 --- a/pkg/runtime/styleparam_test.go +++ b/pkg/runtime/styleparam_test.go @@ -629,6 +629,11 @@ func TestStyleParam(t *testing.T) { assert.NoError(t, err) assert.EqualValues(t, "1.05", result) + uuidValue := uuid.MustParse("c2d07ba4-5106-4eab-bcad-0bd6068dcb1a") + result, err = StyleParamWithLocation("simple", false, "foo", ParamLocationQuery, types.UUID(uuidValue)) + assert.NoError(t, err) + assert.EqualValues(t, "c2d07ba4-5106-4eab-bcad-0bd6068dcb1a", result) + // Test that we handle optional fields type TestObject2 struct { FirstName *string `json:"firstName"`