Skip to content

Commit 2a60fc2

Browse files
Rican7willnorris
authored andcommitted
Fix invalid call to value method with nil pointer
Now checking if a reflected value is invalid and, if so, making sure to initialize the reflected value with the type's expected zero-value before attempting to call the interface method. This prevents panics due to invocation through reflection, such as: "value method query.EncodedArgs.EncodeValues called using nil *EncodedArgs pointer" Fixes #9
1 parent 547ef5a commit 2a60fc2

File tree

2 files changed

+19
-0
lines changed

2 files changed

+19
-0
lines changed

query/encode.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -167,6 +167,10 @@ func reflectValue(values url.Values, val reflect.Value, scope string) error {
167167
}
168168

169169
if sv.Type().Implements(encoderType) {
170+
if !reflect.Indirect(sv).IsValid() {
171+
sv = reflect.New(sv.Type().Elem())
172+
}
173+
170174
m := sv.Interface().(Encoder)
171175
if err := m.EncodeValues(name, &values); err != nil {
172176
return err

query/encode_test.go

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -265,6 +265,21 @@ func TestValues_Marshaler(t *testing.T) {
265265
}
266266
}
267267

268+
func TestValues_MarshalerWithNilPointer(t *testing.T) {
269+
s := struct {
270+
Args *EncodedArgs `url:"arg"`
271+
}{}
272+
v, err := Values(s)
273+
if err != nil {
274+
t.Errorf("Values(%q) returned error: %v", s, err)
275+
}
276+
277+
want := url.Values{}
278+
if !reflect.DeepEqual(want, v) {
279+
t.Errorf("Values(%q) returned %v, want %v", s, v, want)
280+
}
281+
}
282+
268283
func TestTagParsing(t *testing.T) {
269284
name, opts := parseTag("field,foobar,foo")
270285
if name != "field" {

0 commit comments

Comments
 (0)