From bfa8fb343eef37f78c192a6ab03f2e731ff615a4 Mon Sep 17 00:00:00 2001 From: Marcin Romaszewicz Date: Sun, 22 Nov 2026 16:09:07 -0800 Subject: [PATCH] fix: let self-parsing types bind as a last resort BindStringToObject only found a type's own parsing logic in two narrow cases: Binder on the destination exactly as passed, and encoding.TextUnmarshaler on array kinds. An optional field hands it a **T, on which neither interface is visible, and a TextUnmarshaler slice or struct such as net.IP, netip.Addr or big.Int was never consulted, so all of these failed with "can not bind to destination of type". Where no built-in conversion applies, check the dereferenced destination for Binder and then encoding.TextUnmarshaler before giving up. The array case uses the same check, which also fixes an optional *uuid.UUID property of an exploded form object. This is a fallback only. Every destination which binds today takes the same path as before, including time.Time and types.Date, whose lenient parsing stays ahead of their stricter UnmarshalText, and base64 decoding for format: byte. A Binder on a primitive kind behind an optional pointer is still parsed as a plain primitive without calling Bind. Honoring Bind there changes the result of requests which bind today, so it is a separate change. Part of #196 Co-Authored-By: Claude Fable 5.2 --- bindparam_test.go | 44 +++++++++++ bindstring.go | 50 ++++++++++-- bindstring_test.go | 192 +++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 280 insertions(+), 6 deletions(-) diff --git a/bindparam_test.go b/bindparam_test.go index ab610e9..0603400 100644 --- a/bindparam_test.go +++ b/bindparam_test.go @@ -2106,3 +2106,47 @@ func TestBindExplodedObjectFieldErrors(t *testing.T) { }) } } + +// Properties of an exploded form object bind one at a time through +// BindStringToObject, with a **T destination for an optional property, so +// they depend on it finding the parsing logic of the type behind the pointer. +// https://github.com/oapi-codegen/runtime/issues/196 +func TestBindExplodedObjectSelfParsingFields(t *testing.T) { + type Filters struct { + Tags explodedObjectTags `json:"tags,omitempty"` + OptTags *explodedObjectTags `json:"optTags,omitempty"` + Words explodedObjectWords `json:"words,omitempty"` + OptWords *explodedObjectWords `json:"optWords,omitempty"` + IP net.IP `json:"ip,omitempty"` + OptIP *net.IP `json:"optIp,omitempty"` + } + + rawQuery := "tags=a|b&optTags=c|d&words=e+f&optWords=g+h&ip=192.0.2.1&optIp=192.0.2.2" + + check := func(t *testing.T, dst *Filters) { + require.NotNil(t, dst) + assert.Equal(t, explodedObjectTags{"a", "b"}, dst.Tags) + require.NotNil(t, dst.OptTags) + assert.Equal(t, explodedObjectTags{"c", "d"}, *dst.OptTags) + assert.Equal(t, explodedObjectWords{"e", "f"}, dst.Words) + require.NotNil(t, dst.OptWords) + assert.Equal(t, explodedObjectWords{"g", "h"}, *dst.OptWords) + assert.True(t, net.IPv4(192, 0, 2, 1).Equal(dst.IP)) + require.NotNil(t, dst.OptIP) + assert.True(t, net.IPv4(192, 0, 2, 2).Equal(*dst.OptIP)) + } + + t.Run("BindQueryParameter", func(t *testing.T) { + values, err := url.ParseQuery(rawQuery) + require.NoError(t, err) + var dst *Filters + require.NoError(t, BindQueryParameter("form", true, false, "filters", values, &dst)) + check(t, dst) + }) + + t.Run("BindRawQueryParameter", func(t *testing.T) { + var dst *Filters + require.NoError(t, BindRawQueryParameter("form", true, false, "filters", rawQuery, &dst)) + check(t, dst) + }) +} diff --git a/bindstring.go b/bindstring.go index dd2a63e..e66183b 100644 --- a/bindstring.go +++ b/bindstring.go @@ -68,6 +68,11 @@ type BindStringToObjectOptions struct { // BindStringToObjectWithOptions takes a string, and attempts to assign it to the destination // interface via whatever type conversion is necessary, with additional options. +// +// A destination which implements Binder parses itself. Otherwise the built in +// conversions for primitives, times, dates and base64 apply, and a type which +// none of those can handle is given the chance to parse itself, as a Binder +// or an encoding.TextUnmarshaler, behind an optional pointer too. func BindStringToObjectWithOptions(src string, dst interface{}, opts BindStringToObjectOptions) error { var err error @@ -116,6 +121,9 @@ func BindStringToObjectWithOptions(src string, dst interface{}, opts BindStringT // can not be a fallthrough: the next case is the integer one, and a // source string that parses as an integer would reach v.OverflowInt // on a slice value, which panics. + if handled, bindErr := bindStringViaUnmarshaler(src, v); handled { + return bindErr + } err = fmt.Errorf("can not bind to destination of type: %s", t.Kind()) case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: var val int64 @@ -156,12 +164,10 @@ func BindStringToObjectWithOptions(src string, dst interface{}, opts BindStringT v.SetBool(val) } case reflect.Array: - if tu, ok := dst.(encoding.TextUnmarshaler); ok { - if err := tu.UnmarshalText([]byte(src)); err != nil { - return fmt.Errorf("error unmarshaling '%s' text as %T: %w", src, dst, err) - } - - return nil + // Arrays have no string representation of their own, so a type + // such as uuid.UUID has to do its own parsing. + if handled, bindErr := bindStringViaUnmarshaler(src, v); handled { + return bindErr } fallthrough case reflect.Struct: @@ -248,6 +254,14 @@ func BindStringToObjectWithOptions(src string, dst interface{}, opts BindStringT } fallthrough default: + // Nothing above knows how to parse this type, so let it parse + // itself if it is able to. This is deliberately a last resort: the + // special cases above keep their existing behavior for types which + // also happen to implement one of these interfaces, as time.Time + // does. + if handled, bindErr := bindStringViaUnmarshaler(src, v); handled { + return bindErr + } // We've got a bunch of types unimplemented, don't fail silently. err = fmt.Errorf("can not bind to destination of type: %s", t.Kind()) } @@ -256,3 +270,27 @@ func BindStringToObjectWithOptions(src string, dst interface{}, opts BindStringT } return nil } + +// bindStringViaUnmarshaler binds src through the destination's own parsing +// logic, a Binder or failing that an encoding.TextUnmarshaler, and reports +// whether the destination had any. +// +// v is the destination with its pointers already dereferenced. That matters +// for an optional field, where the caller holds a **T: the interfaces are +// implemented by *T, which is only reachable here. +func bindStringViaUnmarshaler(src string, v reflect.Value) (bool, error) { + if !v.CanAddr() { + return false, nil + } + dst := v.Addr().Interface() + if binder, ok := dst.(Binder); ok { + return true, binder.Bind(src) + } + if tu, ok := dst.(encoding.TextUnmarshaler); ok { + if err := tu.UnmarshalText([]byte(src)); err != nil { + return true, fmt.Errorf("error unmarshaling '%s' text as %T: %w", src, dst, err) + } + return true, nil + } + return false, nil +} diff --git a/bindstring_test.go b/bindstring_test.go index 21438eb..b921432 100644 --- a/bindstring_test.go +++ b/bindstring_test.go @@ -15,12 +15,18 @@ package runtime import ( "encoding/base64" + "errors" "fmt" "math" + "math/big" + "net" + "net/netip" "net/url" + "strings" "testing" "time" + "github.com/google/uuid" "github.com/oapi-codegen/nullable" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -349,3 +355,189 @@ func TestBindQueryParameter_NullableSliceDestination(t *testing.T) { }) } } + +// selfParsingSlice, selfParsingStruct and selfParsingMap implement Binder on +// kinds which have no built in conversion from a string. +type selfParsingSlice []string + +func (s *selfParsingSlice) Bind(src string) error { + if src == "" { + return errors.New("empty") + } + *s = strings.Split(src, "|") + return nil +} + +type selfParsingStruct struct{ Value string } + +func (s *selfParsingStruct) Bind(src string) error { + s.Value = src + return nil +} + +type selfParsingMap map[string]string + +func (m *selfParsingMap) Bind(src string) error { + k, v, _ := strings.Cut(src, "=") + *m = selfParsingMap{k: v} + return nil +} + +// textSlice and textStruct implement encoding.TextUnmarshaler instead. +type textSlice []string + +func (s *textSlice) UnmarshalText(text []byte) error { + *s = strings.Fields(string(text)) + return nil +} + +type textStruct struct{ X, Y string } + +func (s *textStruct) UnmarshalText(text []byte) error { + x, y, ok := strings.Cut(string(text), ":") + if !ok { + return errors.New("expected x:y") + } + s.X, s.Y = x, y + return nil +} + +// Types which no built in conversion can handle parse themselves, through +// Binder or encoding.TextUnmarshaler, whether or not they sit behind the +// pointer of an optional field. +// https://github.com/oapi-codegen/runtime/issues/196 +func TestBindStringToObject_SelfParsingTypes(t *testing.T) { + t.Run("Binder slice", func(t *testing.T) { + var dst selfParsingSlice + require.NoError(t, BindStringToObject("a|b", &dst)) + assert.Equal(t, selfParsingSlice{"a", "b"}, dst) + + var opt *selfParsingSlice + require.NoError(t, BindStringToObject("a|b", &opt)) + require.NotNil(t, opt) + assert.Equal(t, selfParsingSlice{"a", "b"}, *opt) + }) + + t.Run("Binder struct", func(t *testing.T) { + var dst selfParsingStruct + require.NoError(t, BindStringToObject("x", &dst)) + assert.Equal(t, selfParsingStruct{Value: "x"}, dst) + + var opt *selfParsingStruct + require.NoError(t, BindStringToObject("x", &opt)) + require.NotNil(t, opt) + assert.Equal(t, selfParsingStruct{Value: "x"}, *opt) + }) + + t.Run("Binder map", func(t *testing.T) { + var opt *selfParsingMap + require.NoError(t, BindStringToObject("k=v", &opt)) + require.NotNil(t, opt) + assert.Equal(t, selfParsingMap{"k": "v"}, *opt) + }) + + t.Run("Binder error is returned", func(t *testing.T) { + var opt *selfParsingSlice + assert.EqualError(t, BindStringToObject("", &opt), "empty") + }) + + t.Run("TextUnmarshaler slice", func(t *testing.T) { + var dst textSlice + require.NoError(t, BindStringToObject("a b", &dst)) + assert.Equal(t, textSlice{"a", "b"}, dst) + + var opt *textSlice + require.NoError(t, BindStringToObject("a b", &opt)) + require.NotNil(t, opt) + assert.Equal(t, textSlice{"a", "b"}, *opt) + }) + + t.Run("TextUnmarshaler struct", func(t *testing.T) { + var dst textStruct + require.NoError(t, BindStringToObject("1:2", &dst)) + assert.Equal(t, textStruct{X: "1", Y: "2"}, dst) + + var opt *textStruct + require.NoError(t, BindStringToObject("1:2", &opt)) + require.NotNil(t, opt) + assert.Equal(t, textStruct{X: "1", Y: "2"}, *opt) + }) + + t.Run("TextUnmarshaler error is returned", func(t *testing.T) { + var dst textStruct + err := BindStringToObject("nope", &dst) + require.Error(t, err) + assert.Contains(t, err.Error(), "expected x:y") + }) + + t.Run("standard library types", func(t *testing.T) { + var ip net.IP + require.NoError(t, BindStringToObject("192.0.2.1", &ip)) + assert.True(t, net.IPv4(192, 0, 2, 1).Equal(ip)) + + var optIP *net.IP + require.NoError(t, BindStringToObject("2001:db8::1", &optIP)) + require.NotNil(t, optIP) + assert.True(t, net.ParseIP("2001:db8::1").Equal(*optIP)) + + var addr netip.Addr + require.NoError(t, BindStringToObject("192.0.2.1", &addr)) + assert.Equal(t, netip.MustParseAddr("192.0.2.1"), addr) + + var n big.Int + require.NoError(t, BindStringToObject("123456789012345678901234567890", &n)) + assert.Equal(t, "123456789012345678901234567890", n.String()) + }) + + t.Run("optional TextUnmarshaler array", func(t *testing.T) { + var opt *uuid.UUID + require.NoError(t, BindStringToObject("5b3a3bc5-1c9e-4e55-9d0e-1c7d5a3b6f10", &opt)) + require.NotNil(t, opt) + assert.Equal(t, uuid.MustParse("5b3a3bc5-1c9e-4e55-9d0e-1c7d5a3b6f10"), *opt) + }) +} + +// The self parsing fallback is a last resort, so everything which had a built +// in conversion keeps it, even where the type implements TextUnmarshaler too. +func TestBindStringToObject_SelfParsingIsLastResort(t *testing.T) { + t.Run("time.Time still accepts a bare date", func(t *testing.T) { + // time.Time.UnmarshalText only accepts RFC 3339. + want := time.Date(2020, 11, 6, 0, 0, 0, 0, time.UTC) + + var dst time.Time + require.NoError(t, BindStringToObject("2020-11-06", &dst)) + assert.True(t, want.Equal(dst)) + + var opt *time.Time + require.NoError(t, BindStringToObject("2020-11-06", &opt)) + require.NotNil(t, opt) + assert.True(t, want.Equal(*opt)) + }) + + t.Run("time.Time still ignores an empty string", func(t *testing.T) { + var dst time.Time + require.NoError(t, BindStringToObject("", &dst)) + assert.True(t, dst.IsZero()) + }) + + t.Run("byte format still decodes base64 into a TextUnmarshaler", func(t *testing.T) { + var ip net.IP + err := BindStringToObjectWithOptions("wAACAQ==", &ip, BindStringToObjectOptions{Format: "byte"}) + require.NoError(t, err) + assert.Equal(t, net.IP{192, 0, 2, 1}, ip) + }) + + t.Run("plain slices are still an error", func(t *testing.T) { + var dst []string + err := BindStringToObject("abc", &dst) + require.Error(t, err) + assert.Contains(t, err.Error(), "can not bind to destination of type: slice") + }) + + t.Run("plain structs are still an error", func(t *testing.T) { + var dst struct{ A string } + err := BindStringToObject("abc", &dst) + require.Error(t, err) + assert.Contains(t, err.Error(), "can not bind to destination of type: struct") + }) +}