diff --git a/query/encode.go b/query/encode.go index ec5c0ee..a3bbd65 100644 --- a/query/encode.go +++ b/query/encode.go @@ -191,6 +191,11 @@ func reflectValue(values url.Values, val reflect.Value, scope string) error { sv = sv.Elem() } + // Stop at the first pointer that provides a custom encoding. + for sv.Kind() == reflect.Ptr && !sv.IsNil() && !sv.Type().Implements(encoderType) { + sv = sv.Elem() + } + if sv.Type().Implements(encoderType) { // if sv is a nil pointer and the custom encoder is defined on a non-pointer // method receiver, set sv to the zero value of the underlying type @@ -205,14 +210,6 @@ func reflectValue(values url.Values, val reflect.Value, scope string) error { continue } - // recursively dereference pointers. break on nil pointers - for sv.Kind() == reflect.Ptr { - if sv.IsNil() { - break - } - sv = sv.Elem() - } - if sv.Kind() == reflect.Slice || sv.Kind() == reflect.Array { if sv.Len() == 0 { // skip if slice or array is empty diff --git a/query/encode_test.go b/query/encode_test.go index e65afa9..8bf68b0 100644 --- a/query/encode_test.go +++ b/query/encode_test.go @@ -654,6 +654,14 @@ func (m *customEncodedIntPtr) EncodeValues(key string, v *url.Values) error { // Test behavior when encoding is defined for a pointer of a custom type. // Custom type should be able to encode values for nil pointers. func TestValues_CustomEncodingPointer(t *testing.T) { + t.Run("indirect pointer", func(t *testing.T) { + c := customEncodedIntPtr(1) + ptr := &c + testValue(t, struct { + V **customEncodedIntPtr `url:"v"` + }{&ptr}, url.Values{"v": {"_1"}}) + }) + var zero customEncodedIntPtr = 0 var one customEncodedIntPtr = 1 tests := []struct {