fatih / structs

Utilities for Go structs

Home Page:http://godoc.org/github.com/fatih/structs

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

panic on nested map

russ666 opened this issue · comments

I got a panic error if my struct has an nested map. Not sure but, i think it starts appear after go compiler updated. Now it 1.6.

reflect: Elem of invalid type
/usr/lib/go/src/runtime/panic.go:426 (0x42d659)
        gopanic: reflectcall(nil, unsafe.Pointer(d.fn), deferArgs(d), uint32(d.siz), uint32(d.siz))
/usr/lib/go/src/reflect/type.go:599 (0x5b3283)
        (*rtype).Elem: panic("reflect: Elem of invalid type")
/opt/project/src/github.com/fatih/structs/structs.go:535 (0x6cccd5)
        (*Struct).nested: v := val.Type().Elem()
/opt/project/src/github.com/fatih/structs/structs.go:120 (0x6c9c2e)
        (*Struct).FillMap: finalVal = s.nested(val)
/opt/project/src/github.com/fatih/structs/structs.go:84 (0x6c97db)
        (*Struct).Map: s.FillMap(out)
...

Can you please provide a reproducible struct and case that I can test. Thanks.

Thanks for quick reply. I used a next structure:

type WebhookModel struct {
	Id bson.ObjectId `json:"id" bson:"_id,omitempty"`
	Name string `json:"name" bson:"name" validate:"required,max=256"`
	Ip string `json:"ip" bson:"ip" validate:"required,ip"`
	Query string `json:"query" bson:"query" validate:"max=256"`
	Payload interface{} `json:"payload" bson:"payload"`
	CreatedAt time.Time `json:"createdAt" bson:"createdAt" validate:"required"`
}

Payload field could contain string or structured map. In case, when it's a simple map (ex. map[string]string {"test_param": "test_value"}) I got an error, described above

Could you also fill the value that makes it panicing ? Just want to get as much information as it makes debugging easier. Thanks

Ok. There are simpler example:

import (
	"github.com/fatih/structs"
	"log"
)

type WebhookModel struct {
	Name string `json:"name" bson:"name" validate:"required,max=256"`
	Ip string `json:"ip" bson:"ip" validate:"required,ip"`
	Query string `json:"query" bson:"query" validate:"max=256"`
	Payload interface{} `json:"payload" bson:"payload"`
}

model := WebhookModel{
	Name: "test",
	Ip: "127.0.0.1",
	Query: "",
	Payload: map[string]string {"test_param": "test_param"},
}

structToMap := structs.New(model)
structToMap.TagName = "bson"

//panic raised here
params := structToMap.Map()

log.Println(params)

hi. i found a solution. don't know what other bugs it could born, but package's tests completed successfully. just remove the line, where the panic raised v := val.Type().Elem(). Looks like v already contains suitable value.

Upd: this solution omit iteration over map's structs. is it necessary at all?

Thanks @russ666

I have a fix on my local branch. I just need to add some tests to be sure it doesn't break old tests. I'll push it when it's ready, you'll get notified when this get closed.

This is now fixed in master. Thanks for the feedback again 👍