A Go package for rendering structs as column-aligned tables with optional ANSI color styling, or as JSON/YAML.
- Text Output: Column-aligned tables with automatic header generation
- Multiple Formats: Output as text, JSON, or YAML
- ANSI Styling: Automatic color/style support with terminal detection
- Struct Tags: Customize column headers and behavior with
tabletags - Annotations: Insert comments between table rows
- Custom Colors: Apply custom ANSI styling via the
wrapperinterface - Smart Defaults: CamelCase field names convert to UPPERCASE_SNAKE_CASE headers
go get endobit.io/tablepackage main
import (
"endobit.io/table"
)
typeserverstruct {
NamestringStatusstringPortint
}
funcmain() {
t:=table.New()
t.Write(server{Name: "web-1", Status: "running", Port: 8080})
t.Write(server{Name: "web-2", Status: "stopped", Port: 8081})
_=t.Flush()
}Output:
NAME STATUS PORT
web-1 running 8080
web-2 stopped 8081
Use the table tag to customize column headers or hide fields:
typehoststruct {
Zonestring`table:"ZONE"`// Custom headerClusterstring`table:"CLUSTER"`Hoststring`table:"HOST"`Rackstring`table:"RACK,omitempty"`// Hide if all values are zeroRankint`table:"RANK"`Internalstring`table:"-"`// Skip this field
}These tags affect text table output only. JSON and YAML output encode the original structs.
Insert comments or context between rows:
t:=table.New()
t.Write(host{Zone: "east", Cluster: "prod", Host: "compute-0"})
t.Annotate("maintenance window scheduled")
t.Write(host{Zone: "west", Cluster: "prod", Host: "compute-1"})
_=t.Flush()t:=table.New()
t.Write(server{Name: "web-1", Status: "running", Port: 8080})
// Output as JSON_=t.FlushJSON()
// Output as YAML_=t.FlushYAML()Implement the wrapper interface to apply custom styling:
import"endobit.io/table/sgr/color"typerankintfunc (rrank) Wrap() sgr.Wrapped {
returnsgr.Wrap(color.Green, r)
}
typehoststruct {
NamestringRankrank// Will be rendered in green
}// Custom writert:=table.New(table.WithWriter(myWriter))
// Custom colorscolors:=&table.Colors{
Header: []sgr.Param{sgr.Bold, sgr.Underline},
EvenRow: []sgr.Param{sgr.Faint},
}
t:=table.New(table.WithColor(colors))
// Custom label functiont:=table.New(table.WithLabelFunction(strings.ToLower))- Colors automatically disabled when output is not a terminal
- Respects
NO_COLORenvironment variable - ANSI escape sequences properly handled in column width calculations
See the example directory for a complete working example.