Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: support encoding.TextMarshaler in StyleParamWithLocation #634

Merged
merged 2 commits into from Jun 29, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
20 changes: 20 additions & 0 deletions pkg/runtime/styleparam.go
Expand Up @@ -14,6 +14,7 @@
package runtime

import (
"encoding"
"errors"
"fmt"
"net/url"
Expand Down Expand Up @@ -62,6 +63,25 @@ func StyleParamWithLocation(style string, explode bool, paramName string, paramL
t = v.Type()
}

// If the value implements encoding.TextMarshaler we use it for marshaling
// https://github.com/deepmap/oapi-codegen/issues/504
if tu, ok := value.(encoding.TextMarshaler); ok {
t := reflect.Indirect(reflect.ValueOf(value)).Type()
convertableToTime := t.ConvertibleTo(reflect.TypeOf(time.Time{}))
convertableToDate := t.ConvertibleTo(reflect.TypeOf(types.Date{}))

// Since both time.Time and types.Date implement encoding.TextMarshaler
// we should avoid calling theirs MarshalText()
if !convertableToTime && !convertableToDate {
b, err := tu.MarshalText()
if err != nil {
return "", fmt.Errorf("error marshaling '%s' as text: %s", value, err)
}

return stylePrimitive(style, explode, paramName, paramLocation, string(b))
}
}

switch t.Kind() {
case reflect.Slice:
n := v.Len()
Expand Down
15 changes: 15 additions & 0 deletions pkg/runtime/styleparam_test.go
Expand Up @@ -14,6 +14,7 @@
package runtime

import (
"github.com/google/uuid"
"testing"
"time"

Expand Down Expand Up @@ -676,4 +677,18 @@ func TestStyleParam(t *testing.T) {
result, err = StyleParamWithLocation("simple", false, "id", ParamLocationQuery, object3)
assert.NoError(t, err)
assert.EqualValues(t, "date_field,1996-03-19,time_field,1996-03-19T00%3A00%3A00Z,uuid_field,baa07328-452e-40bd-aa2e-fa823ec13605", result)

// Test handling of struct that implement encoding.TextMarshaler
timeVal = time.Date(1996, time.March, 19, 0, 0, 0, 0, time.UTC)

result, err = StyleParamWithLocation("simple", false, "id", ParamLocationQuery, timeVal)
assert.NoError(t, err)
assert.EqualValues(t, "1996-03-19T00%3A00%3A00Z", result)

uuidD := uuid.MustParse("972beb41-e5ea-4b31-a79a-96f4999d8769")

result, err = StyleParamWithLocation("simple", false, "id", ParamLocationQuery, uuidD)
assert.NoError(t, err)
assert.EqualValues(t, "972beb41-e5ea-4b31-a79a-96f4999d8769", result)

}