Skip to content
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions bindparam_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
})
}
50 changes: 44 additions & 6 deletions bindstring.go
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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())
}
Expand All @@ -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
}
192 changes: 192 additions & 0 deletions bindstring_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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")
})
}