Skip to content

BindStringToObject ignores Binder behind an optional pointer, and TextUnmarshaler on non-array types #196

Closed

Description

@mromaszewicz

Found while working on #193. Reproduced on main at 9b7381c.

BindStringToObjectWithOptions only finds a type's own parsing logic in two narrow cases, so custom types (typically brought in with x-go-type) fail to bind with can not bind to destination of type: slice / struct:

  1. Binder is only checked on dst itself. The check happens before any pointer is dereferenced. For an optional field the destination is a **T, which does not implement Binder even when *T does, so the code falls through to the kind switch.
  2. encoding.TextUnmarshaler is only honored for reflect.Array kinds (the uuid.UUID case). Slice and struct types that implement it, such as net.IP, are rejected.

time.Time and types.Date are unaffected, since they are special-cased by convertibility.

Repro

type Tags []string

func (t *Tags) Bind(src string) error { *t = strings.Split(src, "|"); return nil }

type BStruct struct{ V string }

func (b *BStruct) Bind(src string) error { b.V = src; return nil }

type Point struct{ X, Y string }

func (p *Point) UnmarshalText(b []byte) error { /* parse "x:y" */ return nil }

var a Tags
runtime.BindStringToObject("a|b", &a) // ok: [a b]

var ap *Tags
runtime.BindStringToObject("a|b", &ap) // error: can not bind to destination of type: slice

var b *BStruct
runtime.BindStringToObject("x", &b) // error: can not bind to destination of type: struct

var p Point
runtime.BindStringToObject("1:2", &p) // error: can not bind to destination of type: struct

In the pointer cases the destination pointer is also left allocated (pointing at a zero value) after the error.

Where it shows up

Properties of an exploded form-style object query parameter are bound through this function, one field at a time, with v.Field(i).Addr().Interface() as the destination:

Field type Query Result
Tags (Binder, slice) tags=a|b binds
*Tags tags=a|b error
net.IP / *net.IP (TextUnmarshaler, slice) ip=192.0.2.1 error
Point / *Point (TextUnmarshaler, struct) point=1:2 error

Before #195 these errors were swallowed and the whole parameter was silently dropped; since #195 they are returned to the caller.

Possible fix

After dereferencing pointers (and allocating a nil optional pointer), check the addressable value for Binder, then for encoding.TextUnmarshaler, before the kind switch. Care is needed to keep the time.Time / types.Date special cases ahead of TextUnmarshaler, since time.Time implements it with stricter RFC 3339 parsing than the current date-or-datetime fallback.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions