gorilla/schema

[bug] Encoding struct with custom encoder and omitempty panics

rzajac opened this issue · 0 comments

Describe the bug
Encoding struct with custom encoder and omitempty causes schema to panic with error:

panic: reflect.Value.Interface: cannot return value obtained from unexported field or method

goroutine 1 [running]:
reflect.valueInterface(0x4bbe00, 0xc00006e180, 0x1ab, 0xc00001e101, 0x8b, 0x14)
        /usr/local/go/src/reflect/value.go:1011 +0x161
reflect.Value.Interface(...)
        /usr/local/go/src/reflect/value.go:1000
github.com/gorilla/schema.isZero(0x4bbe00, 0xc00006e180, 0x1ab, 0x0)
        /home/thor/go/pkg/mod/github.com/gorilla/schema@v1.1.0/encoder.go:68 +0x1a6
github.com/gorilla/schema.isZero(0x4db180, 0xc00006e180, 0x199, 0x0)
        /home/thor/go/pkg/mod/github.com/gorilla/schema@v1.1.0/encoder.go:62 +0x2ef
github.com/gorilla/schema.(*Encoder).encode(0xc000078c08, 0x4b6be0, 0xc00006e180, 0x16, 0xc00006e1b0, 0xc000078b58, 0x40cd3d)
        /home/thor/go/pkg/mod/github.com/gorilla/schema@v1.1.0/encoder.go:99 +0x635
github.com/gorilla/schema.(*Encoder).Encode(0xc000078c08, 0x4b6be0, 0xc00006e180, 0xc00006e1b0, 0xf, 0x0)
        /home/thor/go/pkg/mod/github.com/gorilla/schema@v1.1.0/encoder.go:29 +0xb2
main.main()
        /home/thor/gws/meas/tmp/tmp.go:27 +0x43d

Versions
Go version: go version go1.14.6 linux/amd64
package version: v1.1.0

Steps to Reproduce
Run example code.

Expected behavior
Running example does not panic.

Code Snippets

package main

import (
	"fmt"
	"reflect"
	"time"

	"github.com/gorilla/schema"
)

type Data struct {
	From time.Time `form:"from,omitempty"`
	To   time.Time `form:"to,omitempty"`
}

func main() {
	enc := schema.NewEncoder()
	enc.SetAliasTag("form")
	enc.RegisterEncoder(time.Time{}, encTime)

	data := &Data{
		From: time.Date(2018, time.July, 3, 10, 15, 0, 0, time.UTC),
		To:   time.Date(2019, time.July, 3, 10, 15, 0, 0, time.UTC),
	}

	vs := make(map[string][]string)
	_ = enc.Encode(data, vs)
	fmt.Println(vs)
}

func encTime(value reflect.Value) string {
	tim, ok := value.Interface().(time.Time)
	if ok {
		return tim.Format(time.RFC3339Nano)
	}
	return ""
}

https://play.golang.org/p/uWrVzdCiEHy