The examples listed on this page use the following model:
type User struct {
Name string `json:"username" yaml:"Username"`
Mail string `json:"email" yaml:"E-Mail"`
Password string `json:"-" yaml:"-"`
}
type Team struct {
name string
members []User
}
Note that Team does not have any field tags. Thus, a custom Formatter is required in order to obtain a proper string representation. Moreover, it prints the number of Team members instead of enumerating them.
w := NewJSON(os.Stdout)
w.Formatter.SetFormatterFunc(reflect.TypeOf(t).Name(), func(i interface{}) (string, error) {
tm := i.(Team)
return `{"team":"` + tm.Name() + `","members":` + strconv.Itoa(len(tm.Members())) + `}`, nil
})
n, err := w.Write(t)
// Output:
// {"team":"SUPPORT","members":2}
By default, the table representation of a struct is a two-column newline-separated string. The columns are aligned, which results in a human-readable table.
firstFieldName value1
secondFieldName value2
A map is handled similarly. Each entry in the map corresponds to a row in the table representation.
w := NewTab(os.Stdout)
n, err := w.Write(u)
// Output:
// username John Doe
// email john.doe@local
}
When writing a struct or map slice, the table layout is changed accordingly. Every element in the slice corresponds to a row of multiple columns.
w := NewTab(os.Stdout)
n, err := w.Write(users)
// Output:
// username email
// John Doe john.doe@local
// Rudolf Lingens rudolf.lingens@local
When formatting a struct, map or a slice thereof to YAML, the “yaml” field tags are considered instead. This enables to have a different naming for JSON and YAML output. Moreover, certain fields could be excluded by using the field tag "-".
w := NewYAML(os.Stdout)
_, _ = w.Write(users)
// Output:
// - Username: John Doe
// E-Mail: john.doe@local
// - Username: Rudolf Lingens
// E-Mail: rudolf.lingens@local