Skip to content

Commit fb97b97

Browse files
mromaszewiczclaude
andauthored
fix: let self-parsing types bind as a last resort (#197)
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 <noreply@anthropic.com>
1 parent cab876a commit fb97b97

3 files changed

Lines changed: 280 additions & 6 deletions

File tree

‎bindparam_test.go‎

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2106,3 +2106,47 @@ func TestBindExplodedObjectFieldErrors(t *testing.T) {
21062106
})
21072107
}
21082108
}
2109+
2110+
// Properties of an exploded form object bind one at a time through
2111+
// BindStringToObject, with a **T destination for an optional property, so
2112+
// they depend on it finding the parsing logic of the type behind the pointer.
2113+
// https://github.com/oapi-codegen/runtime/issues/196
2114+
func TestBindExplodedObjectSelfParsingFields(t *testing.T) {
2115+
type Filters struct {
2116+
Tags explodedObjectTags `json:"tags,omitempty"`
2117+
OptTags *explodedObjectTags `json:"optTags,omitempty"`
2118+
Words explodedObjectWords `json:"words,omitempty"`
2119+
OptWords *explodedObjectWords `json:"optWords,omitempty"`
2120+
IP net.IP `json:"ip,omitempty"`
2121+
OptIP *net.IP `json:"optIp,omitempty"`
2122+
}
2123+
2124+
rawQuery := "tags=a|b&optTags=c|d&words=e+f&optWords=g+h&ip=192.0.2.1&optIp=192.0.2.2"
2125+
2126+
check := func(t *testing.T, dst *Filters) {
2127+
require.NotNil(t, dst)
2128+
assert.Equal(t, explodedObjectTags{"a", "b"}, dst.Tags)
2129+
require.NotNil(t, dst.OptTags)
2130+
assert.Equal(t, explodedObjectTags{"c", "d"}, *dst.OptTags)
2131+
assert.Equal(t, explodedObjectWords{"e", "f"}, dst.Words)
2132+
require.NotNil(t, dst.OptWords)
2133+
assert.Equal(t, explodedObjectWords{"g", "h"}, *dst.OptWords)
2134+
assert.True(t, net.IPv4(192, 0, 2, 1).Equal(dst.IP))
2135+
require.NotNil(t, dst.OptIP)
2136+
assert.True(t, net.IPv4(192, 0, 2, 2).Equal(*dst.OptIP))
2137+
}
2138+
2139+
t.Run("BindQueryParameter", func(t *testing.T) {
2140+
values, err := url.ParseQuery(rawQuery)
2141+
require.NoError(t, err)
2142+
var dst *Filters
2143+
require.NoError(t, BindQueryParameter("form", true, false, "filters", values, &dst))
2144+
check(t, dst)
2145+
})
2146+
2147+
t.Run("BindRawQueryParameter", func(t *testing.T) {
2148+
var dst *Filters
2149+
require.NoError(t, BindRawQueryParameter("form", true, false, "filters", rawQuery, &dst))
2150+
check(t, dst)
2151+
})
2152+
}

‎bindstring.go‎

Lines changed: 44 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,11 @@ type BindStringToObjectOptions struct {
6868

6969
// BindStringToObjectWithOptions takes a string, and attempts to assign it to the destination
7070
// interface via whatever type conversion is necessary, with additional options.
71+
//
72+
// A destination which implements Binder parses itself. Otherwise the built in
73+
// conversions for primitives, times, dates and base64 apply, and a type which
74+
// none of those can handle is given the chance to parse itself, as a Binder
75+
// or an encoding.TextUnmarshaler, behind an optional pointer too.
7176
func BindStringToObjectWithOptions(src string, dst interface{}, opts BindStringToObjectOptions) error {
7277
var err error
7378

@@ -116,6 +121,9 @@ func BindStringToObjectWithOptions(src string, dst interface{}, opts BindStringT
116121
// can not be a fallthrough: the next case is the integer one, and a
117122
// source string that parses as an integer would reach v.OverflowInt
118123
// on a slice value, which panics.
124+
if handled, bindErr := bindStringViaUnmarshaler(src, v); handled {
125+
return bindErr
126+
}
119127
err = fmt.Errorf("can not bind to destination of type: %s", t.Kind())
120128
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
121129
var val int64
@@ -156,12 +164,10 @@ func BindStringToObjectWithOptions(src string, dst interface{}, opts BindStringT
156164
v.SetBool(val)
157165
}
158166
case reflect.Array:
159-
if tu, ok := dst.(encoding.TextUnmarshaler); ok {
160-
if err := tu.UnmarshalText([]byte(src)); err != nil {
161-
return fmt.Errorf("error unmarshaling '%s' text as %T: %w", src, dst, err)
162-
}
163-
164-
return nil
167+
// Arrays have no string representation of their own, so a type
168+
// such as uuid.UUID has to do its own parsing.
169+
if handled, bindErr := bindStringViaUnmarshaler(src, v); handled {
170+
return bindErr
165171
}
166172
fallthrough
167173
case reflect.Struct:
@@ -248,6 +254,14 @@ func BindStringToObjectWithOptions(src string, dst interface{}, opts BindStringT
248254
}
249255
fallthrough
250256
default:
257+
// Nothing above knows how to parse this type, so let it parse
258+
// itself if it is able to. This is deliberately a last resort: the
259+
// special cases above keep their existing behavior for types which
260+
// also happen to implement one of these interfaces, as time.Time
261+
// does.
262+
if handled, bindErr := bindStringViaUnmarshaler(src, v); handled {
263+
return bindErr
264+
}
251265
// We've got a bunch of types unimplemented, don't fail silently.
252266
err = fmt.Errorf("can not bind to destination of type: %s", t.Kind())
253267
}
@@ -256,3 +270,27 @@ func BindStringToObjectWithOptions(src string, dst interface{}, opts BindStringT
256270
}
257271
return nil
258272
}
273+
274+
// bindStringViaUnmarshaler binds src through the destination's own parsing
275+
// logic, a Binder or failing that an encoding.TextUnmarshaler, and reports
276+
// whether the destination had any.
277+
//
278+
// v is the destination with its pointers already dereferenced. That matters
279+
// for an optional field, where the caller holds a **T: the interfaces are
280+
// implemented by *T, which is only reachable here.
281+
func bindStringViaUnmarshaler(src string, v reflect.Value) (bool, error) {
282+
if !v.CanAddr() {
283+
return false, nil
284+
}
285+
dst := v.Addr().Interface()
286+
if binder, ok := dst.(Binder); ok {
287+
return true, binder.Bind(src)
288+
}
289+
if tu, ok := dst.(encoding.TextUnmarshaler); ok {
290+
if err := tu.UnmarshalText([]byte(src)); err != nil {
291+
return true, fmt.Errorf("error unmarshaling '%s' text as %T: %w", src, dst, err)
292+
}
293+
return true, nil
294+
}
295+
return false, nil
296+
}

‎bindstring_test.go‎

Lines changed: 192 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,12 +15,18 @@ package runtime
1515

1616
import (
1717
"encoding/base64"
18+
"errors"
1819
"fmt"
1920
"math"
21+
"math/big"
22+
"net"
23+
"net/netip"
2024
"net/url"
25+
"strings"
2126
"testing"
2227
"time"
2328

29+
"github.com/google/uuid"
2430
"github.com/oapi-codegen/nullable"
2531
"github.com/stretchr/testify/assert"
2632
"github.com/stretchr/testify/require"
@@ -349,3 +355,189 @@ func TestBindQueryParameter_NullableSliceDestination(t *testing.T) {
349355
})
350356
}
351357
}
358+
359+
// selfParsingSlice, selfParsingStruct and selfParsingMap implement Binder on
360+
// kinds which have no built in conversion from a string.
361+
type selfParsingSlice []string
362+
363+
func (s *selfParsingSlice) Bind(src string) error {
364+
if src == "" {
365+
return errors.New("empty")
366+
}
367+
*s = strings.Split(src, "|")
368+
return nil
369+
}
370+
371+
type selfParsingStruct struct{ Value string }
372+
373+
func (s *selfParsingStruct) Bind(src string) error {
374+
s.Value = src
375+
return nil
376+
}
377+
378+
type selfParsingMap map[string]string
379+
380+
func (m *selfParsingMap) Bind(src string) error {
381+
k, v, _ := strings.Cut(src, "=")
382+
*m = selfParsingMap{k: v}
383+
return nil
384+
}
385+
386+
// textSlice and textStruct implement encoding.TextUnmarshaler instead.
387+
type textSlice []string
388+
389+
func (s *textSlice) UnmarshalText(text []byte) error {
390+
*s = strings.Fields(string(text))
391+
return nil
392+
}
393+
394+
type textStruct struct{ X, Y string }
395+
396+
func (s *textStruct) UnmarshalText(text []byte) error {
397+
x, y, ok := strings.Cut(string(text), ":")
398+
if !ok {
399+
return errors.New("expected x:y")
400+
}
401+
s.X, s.Y = x, y
402+
return nil
403+
}
404+
405+
// Types which no built in conversion can handle parse themselves, through
406+
// Binder or encoding.TextUnmarshaler, whether or not they sit behind the
407+
// pointer of an optional field.
408+
// https://github.com/oapi-codegen/runtime/issues/196
409+
func TestBindStringToObject_SelfParsingTypes(t *testing.T) {
410+
t.Run("Binder slice", func(t *testing.T) {
411+
var dst selfParsingSlice
412+
require.NoError(t, BindStringToObject("a|b", &dst))
413+
assert.Equal(t, selfParsingSlice{"a", "b"}, dst)
414+
415+
var opt *selfParsingSlice
416+
require.NoError(t, BindStringToObject("a|b", &opt))
417+
require.NotNil(t, opt)
418+
assert.Equal(t, selfParsingSlice{"a", "b"}, *opt)
419+
})
420+
421+
t.Run("Binder struct", func(t *testing.T) {
422+
var dst selfParsingStruct
423+
require.NoError(t, BindStringToObject("x", &dst))
424+
assert.Equal(t, selfParsingStruct{Value: "x"}, dst)
425+
426+
var opt *selfParsingStruct
427+
require.NoError(t, BindStringToObject("x", &opt))
428+
require.NotNil(t, opt)
429+
assert.Equal(t, selfParsingStruct{Value: "x"}, *opt)
430+
})
431+
432+
t.Run("Binder map", func(t *testing.T) {
433+
var opt *selfParsingMap
434+
require.NoError(t, BindStringToObject("k=v", &opt))
435+
require.NotNil(t, opt)
436+
assert.Equal(t, selfParsingMap{"k": "v"}, *opt)
437+
})
438+
439+
t.Run("Binder error is returned", func(t *testing.T) {
440+
var opt *selfParsingSlice
441+
assert.EqualError(t, BindStringToObject("", &opt), "empty")
442+
})
443+
444+
t.Run("TextUnmarshaler slice", func(t *testing.T) {
445+
var dst textSlice
446+
require.NoError(t, BindStringToObject("a b", &dst))
447+
assert.Equal(t, textSlice{"a", "b"}, dst)
448+
449+
var opt *textSlice
450+
require.NoError(t, BindStringToObject("a b", &opt))
451+
require.NotNil(t, opt)
452+
assert.Equal(t, textSlice{"a", "b"}, *opt)
453+
})
454+
455+
t.Run("TextUnmarshaler struct", func(t *testing.T) {
456+
var dst textStruct
457+
require.NoError(t, BindStringToObject("1:2", &dst))
458+
assert.Equal(t, textStruct{X: "1", Y: "2"}, dst)
459+
460+
var opt *textStruct
461+
require.NoError(t, BindStringToObject("1:2", &opt))
462+
require.NotNil(t, opt)
463+
assert.Equal(t, textStruct{X: "1", Y: "2"}, *opt)
464+
})
465+
466+
t.Run("TextUnmarshaler error is returned", func(t *testing.T) {
467+
var dst textStruct
468+
err := BindStringToObject("nope", &dst)
469+
require.Error(t, err)
470+
assert.Contains(t, err.Error(), "expected x:y")
471+
})
472+
473+
t.Run("standard library types", func(t *testing.T) {
474+
var ip net.IP
475+
require.NoError(t, BindStringToObject("192.0.2.1", &ip))
476+
assert.True(t, net.IPv4(192, 0, 2, 1).Equal(ip))
477+
478+
var optIP *net.IP
479+
require.NoError(t, BindStringToObject("2001:db8::1", &optIP))
480+
require.NotNil(t, optIP)
481+
assert.True(t, net.ParseIP("2001:db8::1").Equal(*optIP))
482+
483+
var addr netip.Addr
484+
require.NoError(t, BindStringToObject("192.0.2.1", &addr))
485+
assert.Equal(t, netip.MustParseAddr("192.0.2.1"), addr)
486+
487+
var n big.Int
488+
require.NoError(t, BindStringToObject("123456789012345678901234567890", &n))
489+
assert.Equal(t, "123456789012345678901234567890", n.String())
490+
})
491+
492+
t.Run("optional TextUnmarshaler array", func(t *testing.T) {
493+
var opt *uuid.UUID
494+
require.NoError(t, BindStringToObject("5b3a3bc5-1c9e-4e55-9d0e-1c7d5a3b6f10", &opt))
495+
require.NotNil(t, opt)
496+
assert.Equal(t, uuid.MustParse("5b3a3bc5-1c9e-4e55-9d0e-1c7d5a3b6f10"), *opt)
497+
})
498+
}
499+
500+
// The self parsing fallback is a last resort, so everything which had a built
501+
// in conversion keeps it, even where the type implements TextUnmarshaler too.
502+
func TestBindStringToObject_SelfParsingIsLastResort(t *testing.T) {
503+
t.Run("time.Time still accepts a bare date", func(t *testing.T) {
504+
// time.Time.UnmarshalText only accepts RFC 3339.
505+
want := time.Date(2020, 11, 6, 0, 0, 0, 0, time.UTC)
506+
507+
var dst time.Time
508+
require.NoError(t, BindStringToObject("2020-11-06", &dst))
509+
assert.True(t, want.Equal(dst))
510+
511+
var opt *time.Time
512+
require.NoError(t, BindStringToObject("2020-11-06", &opt))
513+
require.NotNil(t, opt)
514+
assert.True(t, want.Equal(*opt))
515+
})
516+
517+
t.Run("time.Time still ignores an empty string", func(t *testing.T) {
518+
var dst time.Time
519+
require.NoError(t, BindStringToObject("", &dst))
520+
assert.True(t, dst.IsZero())
521+
})
522+
523+
t.Run("byte format still decodes base64 into a TextUnmarshaler", func(t *testing.T) {
524+
var ip net.IP
525+
err := BindStringToObjectWithOptions("wAACAQ==", &ip, BindStringToObjectOptions{Format: "byte"})
526+
require.NoError(t, err)
527+
assert.Equal(t, net.IP{192, 0, 2, 1}, ip)
528+
})
529+
530+
t.Run("plain slices are still an error", func(t *testing.T) {
531+
var dst []string
532+
err := BindStringToObject("abc", &dst)
533+
require.Error(t, err)
534+
assert.Contains(t, err.Error(), "can not bind to destination of type: slice")
535+
})
536+
537+
t.Run("plain structs are still an error", func(t *testing.T) {
538+
var dst struct{ A string }
539+
err := BindStringToObject("abc", &dst)
540+
require.Error(t, err)
541+
assert.Contains(t, err.Error(), "can not bind to destination of type: struct")
542+
})
543+
}

0 commit comments

Comments
 (0)