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
diff --git a/query/encode.go b/query/encode.go index 396d804..90dcabb 100644 --- a/query/encode.go +++ b/query/encode.go
@@ -167,6 +167,10 @@ } if sv.Type().Implements(encoderType) { + if !reflect.Indirect(sv).IsValid() { + sv = reflect.New(sv.Type().Elem()) + } + m := sv.Interface().(Encoder) if err := m.EncodeValues(name, &values); err != nil { return err
diff --git a/query/encode_test.go b/query/encode_test.go index 09efb0f..e0b2a36 100644 --- a/query/encode_test.go +++ b/query/encode_test.go
@@ -265,6 +265,21 @@ } } +func TestValues_MarshalerWithNilPointer(t *testing.T) { + s := struct { + Args *EncodedArgs `url:"arg"` + }{} + v, err := Values(s) + if err != nil { + t.Errorf("Values(%q) returned error: %v", s, err) + } + + want := url.Values{} + if !reflect.DeepEqual(want, v) { + t.Errorf("Values(%q) returned %v, want %v", s, v, want) + } +} + func TestTagParsing(t *testing.T) { name, opts := parseTag("field,foobar,foo") if name != "field" {