Created
January 5, 2021 08:25
-
-
Save hallazzang/d45cf935f2e58918cfdef6a91ebcfe1b to your computer and use it in GitHub Desktop.
Dump configuration struct with defaults
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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