Skip to content

Commit

Permalink
fix: support encoding.TextMarshaler in StyleParamWithLocation (#634)
Browse files Browse the repository at this point in the history
Co-authored-by: Marcin Romaszewicz <47459980+deepmap-marcinr@users.noreply.github.com>
  • Loading branch information
mazitovt and deepmap-marcinr committed Jun 29, 2022
1 parent 6e0423f commit de9733b
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
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)

}

0 comments on commit de9733b

Please sign in to comment.