diff --git a/bindstring.go b/bindstring.go index f38cf84..7aa8f7e 100644 --- a/bindstring.go +++ b/bindstring.go @@ -49,6 +49,11 @@ type BindStringToObjectOptions struct { func BindStringToObjectWithOptions(src string, dst interface{}, opts BindStringToObjectOptions) error { var err error + // Check if the destination implements Binder interface before any reflection + if binder, ok := dst.(Binder); ok { + return binder.Bind(src) + } + v := reflect.ValueOf(dst) t := reflect.TypeOf(dst) @@ -134,11 +139,6 @@ func BindStringToObjectWithOptions(src string, dst interface{}, opts BindStringT } fallthrough case reflect.Struct: - // if this is not of type Time or of type Date look to see if this is of type Binder. - if dstType, ok := dst.(Binder); ok { - return dstType.Bind(src) - } - if t.ConvertibleTo(reflect.TypeOf(time.Time{})) { // Don't fail on empty string. if src == "" { diff --git a/bindstring_test.go b/bindstring_test.go index 043917b..b3fb26e 100644 --- a/bindstring_test.go +++ b/bindstring_test.go @@ -26,6 +26,16 @@ import ( "github.com/oapi-codegen/runtime/types" ) +// CustomStringBinder is a string type that implements Binder but not TextUnmarshaler +// This tests that Binder interface is checked for primitive types +type CustomStringBinder string + +func (c *CustomStringBinder) Bind(src string) error { + // Custom binding logic: add a prefix to demonstrate the Bind method was called + *c = CustomStringBinder("CUSTOM:" + src) + return nil +} + func TestBindStringToObject(t *testing.T) { var i int assert.NoError(t, BindStringToObject("5", &i)) @@ -211,6 +221,12 @@ func TestBindStringToObject(t *testing.T) { assert.NoError(t, BindStringToObject(uuidString, &dstUUID)) assert.Equal(t, dstUUID.String(), uuidString) + // Checks that primitive types implementing Binder are respected + // This tests the fix for ensuring Binder is checked before type reflection + var customString CustomStringBinder + assert.NoError(t, BindStringToObject("hello", &customString)) + assert.Equal(t, CustomStringBinder("CUSTOM:hello"), customString) + } // TestBindStringToObject_ByteSlice tests that BindStringToObject correctly handles