Documentation
¶
Overview ¶
Package fmter renders structured data in multiple output formats.
Supported formats are JSON, YAML, CSV, Table, Markdown, List, ENV, Plain, TSV, JSONL, HTML, and GoTemplate. The central entry points are Write and Marshal, which accept a Format constant and variadic items of any type. JSON, YAML, Plain, and JSONL work on any value; other formats require the items to implement specific interfaces.
Interface Design ¶
The package uses a layered interface design. A minimal interface unlocks a format, and optional interfaces enhance the rendering:
- Rower → CSV, Table, Markdown, TSV, HTML (row data)
- Headed → adds column headers to CSV, Table, Markdown, TSV, HTML
- Lister → List format
- Mappable → ENV format
Use IsSupported to check at runtime whether a type implements the required interfaces for a given format:
if fmter.IsSupported[MyType](fmter.CSV) { ... }
JSON and YAML ¶
Any value works. Implement Indented to control indentation:
fmter.Write(os.Stdout, fmter.JSON, myStruct) fmter.Write(os.Stdout, fmter.YAML, items...)
CSV ¶
Requires Rower. Optional interfaces:
TSV ¶
Requires Rower. Tab-delimited output with no quoting. Optional:
- Headed — header row
Table ¶
Requires Rower. Optional interfaces control every aspect of rendering:
- Headed — column headers
- Titled — title above the table
- Bordered — border style (default BorderRounded)
- Aligned — per-column alignment
- Footered — footer row
- Numbered — row number column
- Captioned — line below the table
- Truncated — max column widths with "..." truncation
- Styled — per-column style functions (e.g., ANSI colors)
- Grouped — separator between groups of rows
- Paged — repeat header every N rows
- Wrapped — multi-line cells with per-column wrap widths
Markdown ¶
Requires Rower and Headed. Renders a GitHub-flavored Markdown table. Implement Aligned to set column alignment markers.
HTML ¶
Requires Rower. Renders a semantic HTML table. Optional interfaces:
List ¶
Requires Lister. Implement Separator to control the delimiter between items (default newline).
ENV ¶
Requires Mappable. Optional interfaces:
Plain ¶
Works on any value. Uses fmt.Stringer if available, otherwise fmt.Sprintf("%v"). One item per line.
JSONL ¶
Works on any value. One JSON object per line (no array wrapping). Implement Indented for per-line indentation.
GoTemplate ¶
Use GoTemplate to create a parameterized format that renders each item using a Go text/template:
fmter.Write(os.Stdout, fmter.GoTemplate("{{.Name}}: {{.Age}}"), items...)
Streaming ¶
WriteIter and WriteChan support streaming output for iterator and channel sources. Formats that render items independently (Plain, JSONL, CSV, TSV, GoTemplate) write each item as it arrives. Formats that need all data for layout (Table, Markdown, HTML) collect items first.
Formatter ¶
Implement Formatter for per-item control. If Format returns non-nil bytes, they are written directly; returning (nil, nil) falls through to default rendering.
Format Selection ¶
Use ParseFormat to convert a CLI flag string into a Format. It recognizes all static formats and "go-template=<tmpl>" strings:
f, err := fmter.ParseFormat(flagValue) fmter.Write(os.Stdout, f, items...)
Errors ¶
The package exports sentinel errors for programmatic handling:
- ErrUnsupportedFormat — unknown format string
- ErrMissingInterface — items don't implement the required interface
- ErrInvalidTemplate — invalid go-template syntax
Index ¶
- Variables
- func IsSupported[T any](f Format) bool
- func Marshal[T any](f Format, items ...T) ([]byte, error)
- func Write[T any](w io.Writer, f Format, items ...T) error
- func WriteChan[T any](w io.Writer, f Format, ch <-chan T) error
- func WriteIter[T any](w io.Writer, f Format, seq iter.Seq[T]) error
- type Aligned
- type Alignment
- type BorderStyle
- type Bordered
- type Captioned
- type Delimited
- type Exported
- type Footered
- type Format
- type Formatter
- type Grouped
- type Headed
- type Indented
- type KeyValue
- type Lister
- type Mappable
- type Numbered
- type Paged
- type Quoted
- type Rower
- type Separator
- type Sorted
- type Styled
- type Titled
- type Truncated
- type Wrapped
Constants ¶
This section is empty.
Variables ¶
var ( ErrUnsupportedFormat = errors.New("unsupported format") ErrMissingInterface = errors.New("missing required interface") ErrInvalidTemplate = errors.New("invalid template") )
Sentinel errors for programmatic error handling.
Functions ¶
func IsSupported ¶
IsSupported reports whether type T implements the interfaces required by format f. JSON, YAML, and GoTemplate always return true.
func WriteChan ¶
WriteChan formats items from a channel and writes them to w. It is a thin wrapper around WriteIter.
func WriteIter ¶
WriteIter formats items from an iterator and writes them to w as they arrive. For formats where items are independent (JSONL, CSV, TSV, List, ENV, GoTemplate, Plain), each item is written immediately. For formats that need all data for layout (Table, Markdown, HTML), items are collected into a slice first. For JSON, items are streamed as array elements. For YAML, items are collected (the encoder needs a complete document).
Types ¶
type Aligned ¶
type Aligned interface {
Alignments() []Alignment
}
Aligned sets per-column alignment. Default: AlignLeft. Also used by Markdown for alignment markers.
type BorderStyle ¶
type BorderStyle int
BorderStyle controls table border characters.
const ( BorderRounded BorderStyle = iota // ╭─╮╰╯│┬┴├┤┼ BorderNone // No borders, space-separated columns BorderASCII // +-+| BorderHeavy // ┏━┓┗┛┃┳┻┣┫╋ BorderDouble // ╔═╗╚╝║╦╩╠╣╬ )
type Bordered ¶
type Bordered interface {
Border() BorderStyle
}
Bordered controls the table border style. Default: BorderRounded.
type Captioned ¶
type Captioned interface {
Caption() string
}
Captioned renders a line below the table. Default: no caption.
type Delimited ¶
type Delimited interface {
Delimiter() rune
}
Delimited controls the CSV field delimiter. Default: comma.
type Exported ¶
type Exported interface {
Export() bool
}
Exported prefixes env pairs with "export ". Default: no prefix. Use with Quoted for shell-safe output.
type Footered ¶
type Footered interface {
}
Footered renders a footer row below the table. Default: no footer.
type Format ¶
type Format string
Format represents an output format.
func Formats ¶
func Formats() []Format
Formats returns all supported static format names. GoTemplate is not included because it is parameterized.
func GoTemplate ¶
GoTemplate returns a Format that renders items using a Go text/template. Each item is executed against the template and written on its own line.
func ParseFormat ¶
ParseFormat parses a format string. Recognizes all static formats and go-template=<tmpl> strings.
type Formatter ¶
Formatter is an escape hatch checked per-item. If Format returns non-nil bytes, those bytes are written directly. If it returns (nil, nil), the item falls through to default rendering.
type Grouped ¶
type Grouped interface {
Group() string
}
Grouped returns a group key for the item. When consecutive items have different group keys, a separator line is inserted between them in Table format.
type Headed ¶
type Headed interface {
Header() []string
}
Headed provides column headers for CSV, Table, and Markdown. Without it, CSV has no header row and Table renders without column headers.
type Indented ¶
type Indented interface {
Indent() string
}
Indented controls JSON/YAML indentation. Without it, JSON is compact and YAML uses its default indent.
type Lister ¶
type Lister interface {
List() []string
}
Lister provides a flat list of strings. Required for List format.
type Mappable ¶
type Mappable interface {
Pairs() []KeyValue
}
Mappable provides key-value pairs. Required for ENV format.
type Numbered ¶
type Numbered interface {
NumberHeader() string
}
Numbered prepends a row number column. Default: no row numbers.
type Paged ¶
type Paged interface {
PageSize() int
}
Paged controls header repetition for Table format. The header row is re-printed every PageSize data rows.
type Quoted ¶
type Quoted interface {
Quote() bool
}
Quoted wraps env values in double quotes. Default: unquoted. Useful for values that may contain spaces or special characters.
type Rower ¶
type Rower interface {
Row() []string
}
Rower provides row data. Required for CSV, Table, and Markdown formats.
type Separator ¶
type Separator interface {
Sep() string
}
Separator controls the delimiter between list items. Default: newline.
type Sorted ¶
Sorted is a metadata-only interface that declares a default sort column. The package does NOT sort; callers (CLI frameworks) can read this to apply sorting before rendering.
type Styled ¶
Styled provides per-column style functions for Table format. Each function wraps the fully formatted cell string (after truncation and alignment). Nil entries mean no styling for that column. Style functions are applied as the last step before writing, so ANSI codes never affect width calculations.
type Titled ¶
type Titled interface {
Title() string
}
Titled renders a title above the table. Default: no title.