Customization

Formatting maps

The order is not specified and is not guaranteed to be the same from one invocation to the next. If a certain order is required, you must define a custom Formatter and specify the order:

m := map[string]interface{}{"a": "A", "b": "B", "c": "C"}
w := NewTab(os.Stdout)

// Create a custom formatter, which outputs certain map entries in the given order.
ks := []reflect.Value{reflect.ValueOf("c"), reflect.ValueOf("a")}
f := formatter.FromMapKeys("\t", "\t\n", ks...)
// Register the formatter for type map[string]interface{}.
w.Formatter.SetFormatter(reflect.TypeOf(m).String(), f)

n, err := w.Write(m)
// Output:
// c	C
// a	A

Similarly, a custom Formatter can be used for map slice:

ms := []map[string]interface{}{m}

// Create another formatter - using FromMapSliceKeys().
// The keys could be the same as before, or different if another output format is needed.
f := formatter.FromMapSliceKeys("\t", "\t\n", ks...)
w.Formatter.SetFormatter(reflect.TypeOf(ms).String(), f)

n, err := w.Write(ms)
// Output:
// c	a
// C	A

Use different metadata for a struct

By default, a reflection-based Resolver extracts field information of struct types. It looks for the json tag and returns its name, if present, or the field name instead. The community welcomed tags and has built ORMs, further encodings, flag parsers and much more around them since, especially for these tasks, single-sourcing is beneficial for data structures.

The default Resolver can be changed so that it looks for another tag such as yaml instead. This can be done by setting a new Resolver.

meta.Resolve = TagResolver{"yaml"}.lookup

Several well-known frameworks and their struct tags are listed at: https://github.com/golang/go/wiki/Well-known-struct-tags

Use jsoniter instead of encoding/json

jsoniter (json-iterator) is a fast and flexible JSON parser available in Java and Go. It can be used as a drop-in replacement for “encoding/json”.

In order to build another project, having gutenfmt using jsoniter, use the jsoniter build tag as follows:

go build -tags=jsoniter ./...

For building gutenfmt as a standalone binary, it is recommended to use it’s Makefile and set GOFLAGS accordingly:

GOFLAGS='-tags=jsoniter' make