Skip to content

Commit 50c87b2

Browse files
authored
Fix encoding non-nil pointers by their by using their actual value (#42)
As described in issue #26 if we unwrap the value of the pointer prior to the slice/array logic this should work. It is placed under the omitempty check, since this would be backwards breaking.
1 parent 1d3f675 commit 50c87b2

File tree

2 files changed

+12
-7
lines changed

2 files changed

+12
-7
lines changed

query/encode.go

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -151,6 +151,7 @@ func reflectValue(values url.Values, val reflect.Value, scope string) error {
151151
continue
152152
}
153153
name, opts := parseTag(tag)
154+
154155
if name == "" {
155156
if sf.Anonymous && sv.Kind() == reflect.Struct {
156157
// save embedded struct for later processing
@@ -169,6 +170,13 @@ func reflectValue(values url.Values, val reflect.Value, scope string) error {
169170
continue
170171
}
171172

173+
for sv.Kind() == reflect.Ptr {
174+
if sv.IsNil() {
175+
break
176+
}
177+
sv = sv.Elem()
178+
}
179+
172180
if sv.Type().Implements(encoderType) {
173181
if !reflect.Indirect(sv).IsValid() {
174182
sv = reflect.New(sv.Type().Elem())
@@ -217,13 +225,6 @@ func reflectValue(values url.Values, val reflect.Value, scope string) error {
217225
continue
218226
}
219227

220-
for sv.Kind() == reflect.Ptr {
221-
if sv.IsNil() {
222-
break
223-
}
224-
sv = sv.Elem()
225-
}
226-
227228
if sv.Type() == timeType {
228229
values.Add(name, valueString(sv, opts))
229230
continue

query/encode_test.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,10 @@ func TestValues_Pointers(t *testing.T) {
9999
{struct{ V []*string }{}, url.Values{}},
100100
{struct{ V []*string }{[]*string{&str, &str}}, url.Values{"V": {"s", "s"}}},
101101

102+
// pointer to slice
103+
{struct{ V *[]string }{}, url.Values{"V": {""}}},
104+
{struct{ V *[]string }{&[]string{"a", "b"}}, url.Values{"V": {"a", "b"}}},
105+
102106
// pointer values for the input struct itself
103107
{(*struct{})(nil), url.Values{}},
104108
{&struct{}{}, url.Values{}},

0 commit comments

Comments
 (0)