Skip to content

Instantly share code, notes, and snippets.

@hallazzang
Created January 5, 2021 08:25
Show Gist options
  • Save hallazzang/d45cf935f2e58918cfdef6a91ebcfe1b to your computer and use it in GitHub Desktop.
Save hallazzang/d45cf935f2e58918cfdef6a91ebcfe1b to your computer and use it in GitHub Desktop.
Dump configuration struct with defaults
func DumpConfig(s interface{}) {
var dump func(interface{}, int)
dump = func(s interface{}, level int) {
e := reflect.ValueOf(s)
t := e.Type()
for i := 0; i < e.NumField(); i++ {
f := e.Field(i)
ft := t.Field(i)
if !ft.Anonymous {
fmt.Printf("%s%s:", strings.Repeat(" ", level), tagName(ft))
}
if f.Kind() == reflect.Struct {
fmt.Println()
if ft.Anonymous {
dump(f.Interface(), level)
} else {
dump(f.Interface(), level+1)
}
} else {
fmt.Printf(" %s", ft.Type)
if !f.IsZero() {
fmt.Printf(" (default: %#v)", f.Interface())
}
fmt.Println()
}
}
}
dump(s, 0)
}
func tagName(f reflect.StructField) string {
return strings.SplitN(tagValue(f), ",", 2)[0]
}
func tagValue(f reflect.StructField) string {
for _, key := range []string{"json", "mapstructure"} {
if v, ok := f.Tag.Lookup(key); ok {
return v
}
}
return f.Name
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment