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 when using both flatten and omitempty

BlueMonday opened this issue · comments

Hello!

When flattening a struct, if all of the fields in the struct have the omitempty option at least one of them must be set or the library will panic. This means I can't safely combine "flatten" and "omitempty". It would be nice if the two could be used together safely.

I believe this happens because of this check: https://github.com/fatih/structs/blob/master/structs.go#L527

The embedded struct is converted to a map. If the map is empty the function returns a the struct value instead of a map which results in a panic in the parent function since it expects a map[string]interface{} (https://github.com/fatih/structs/blob/master/structs.go#L142).

For example:

package main

import (
	"fmt"

	"github.com/fatih/structs"
)

type Parent struct {
       Embedded `structs:",flatten"`
}

type Embedded struct {
        A string `structs:",omitempty"`
        B string `structs:",omitempty"`
}

func main() {
        p := &Parent{}
        fmt.Println(structs.Map(p))
}

Results in this error:

panic: interface conversion: interface {} is main.Embedded, not map[string]interface {}

goroutine 1 [running]:
github.com/fatih/structs.(*Struct).FillMap(0xc420014240, 0xc420012240)
	/home/serenst/go/src/github.com/fatih/structs/structs.go:144 +0x569
github.com/fatih/structs.(*Struct).Map(0xc420014240, 0xc42000a320)
	/home/serenst/go/src/github.com/fatih/structs/structs.go:83 +0x65
github.com/fatih/structs.Map(0x493640, 0xc42000a320, 0x0)
	/home/serenst/go/src/github.com/fatih/structs/structs.go:449 +0x43
main.main()
	/home/serenst/bugreport.go:20 +0x6a
exit status 2

Hi,

Unfortunately, I'm archiving this project and will no longer maintaining it. For more information, please read my blog post: Taking an indefinite sabbatical from my projects.

Thanks for the feedback and contribution.