Lightweight building blocks for polished Go console output.
console is a small toolkit for the output layer shared by command-line applications: semantic messages, coordinated writers, ANSI-aware text, composable layout, bordered and compact tables, trees, prompts, loaders, and progress. It is deliberately not a full-screen TUI framework. There is no event loop, raw-mode ownership, command parser, subprocess runner, or logging pipeline to adopt.
Installation
Requires Go 1.25 or newer.
go get github.com/goforj/console
Quick start
package main
import "github.com/goforj/console"
func main() {
console.Action("Building application")
// · Building application
console.Infof("Environment: %s", "development")
// · Environment: development
console.Success("Application ready")
// ✔ Application ready
}
Common operations are available both as package-level helpers and as methods on *Console. The examples lead with the concise package helpers, which use the process-wide default console. Libraries and applications that need isolated writers or independent runtime policy should construct an instance instead. Construction is the only naming exception: package helpers use console.NewLoader and console.NewProgress, while instances use Loader and Progress.
var output bytes.Buffer
color := false
console.SetDefault(console.New(console.Config{
Stdout: &output,
Stderr: &output,
ColorEnabled: &color,
}))
console.Warn("Configuration is incomplete")
fmt.Print(output.String())
// ! Configuration is incomplete
Set ColorEnabled explicitly when output policy should ignore environment and TTY detection:
var output bytes.Buffer
forceColor := true
unicode := true
console.SetDefault(console.New(console.Config{
Stdout: &output,
ColorEnabled: &forceColor,
UnicodeEnabled: &unicode,
}))
console.Success("ANSI styling is forced")
fmt.Printf("%q\n", strings.TrimSuffix(output.String(), "\n"))
// "\x1b[32m✔\x1b[0m ANSI styling is forced"
What it provides
- Semantic action, information, success, warning, error, fatal, and debug messages.
- Plain printing and
io.Writer adapters that coordinate with prompts and live displays.
- Automatic ANSI color policy with
NO_COLOR, CLICOLOR, CLICOLOR_FORCE, and TTY awareness.
- ANSI-aware width, wrapping, end and middle truncation, indentation, and left/right/center padding.
- Printing and render-only forms of sections, rules, key/value summaries, lists, boxes, tables, and trees.
- Bordered tables by default, plus one compact form, fixed widths, alignment, wrapping, and ASCII fallbacks.
- Line-oriented questions, defaults, confirmation, numbered choices, and non-echoed secret input.
- Concurrency-safe loaders and determinate progress that become stable semantic lines when redirected.
- Optional terminal-owned progress indicators for terminal tabs, windows, and taskbars that support OSC 9;4.
- Configurable writers, input, marks, terminal hooks, environment lookup, and exit behavior.
Design principles
- Stay lightweight. The two focused direct dependencies are
golang.org/x/term for terminal integration and github.com/rivo/uniseg for grapheme-aware cell measurement.
- Stay line-oriented. Alternate screens, raw key events, cursor navigation, fuzzy selection, and multiple live widgets belong in a TUI package.
- Keep output composable.
Console owns presentation policy, not structured logging, command routing, or application lifecycle.
- Prefer durable logs outside a TTY. Loaders and progress never leak carriage returns or erase sequences into redirected output.
- Treat layout as terminal cells. ANSI sequences are zero-width; combining marks, CJK text, and common emoji are measured for console alignment.
- Offer one strong default. Options cover common adjustments such as width, compact tables, and alignment without introducing themes or a styling matrix.
- Make testing ordinary. Writers, input, environment lookup, terminal detection, terminal size, and process exit are injectable.
- Fail fast on invalid wiring.
SetDefault(nil) panics instead of leaving package helpers silently unusable.
Layout
Layout helpers write through a Console. Their RenderSection, RenderRule, RenderKeyValues, RenderList, RenderTree, RenderBox, and RenderTable counterparts return the same presentation without a trailing newline, ready for composition.
color := false
unicode := true
console.SetDefault(console.New(console.Config{
ColorEnabled: &color,
UnicodeEnabled: &unicode,
}))
fmt.Println(console.RenderBox(
"All services healthy.",
console.BoxTitle("Status"),
console.BoxWidth(26),
))
// ┌─ Status ───────────────┐
// │ All services healthy. │
// └────────────────────────┘
Tables are bordered and content-preserving by default: columns shrink and wrap when needed. TableCompact, TableWidths, TableRightAlign, and TableCenterAlign cover the common presentation changes without exposing a theme system or a large style vocabulary. Trees intentionally have no options beyond the console's Unicode/ASCII policy.
Borders, marks, list bullets, tree connectors, progress bars, and loader frames have ASCII fallbacks. Set UnicodeEnabled to false when targeting a constrained terminal; text measurement remains Unicode-aware.
Loaders and progress
Constructing a loader or progress display has no side effects. Start claims the console's single transient line when animation is possible; another live loader or progress display receives ErrTransientActive.
var output bytes.Buffer
color := false
animations := false
unicode := true
console.SetDefault(console.New(console.Config{
Stdout: &output,
ColorEnabled: &color,
UnicodeEnabled: &unicode,
AnimationsEnabled: &animations,
}))
loader := console.NewLoader("Downloading modules")
if err := loader.Start(); err != nil {
console.Error(err.Error())
return
}
defer loader.Stop()
loader.Update("Verifying modules")
loader.Success("Modules ready")
fmt.Print(output.String())
// · Downloading modules
// ✔ Modules ready
On a terminal a loader animates in place, while progress uses one adaptive bar with a percentage. Narrow terminals fall back to message and percentage. With automatic policy, redirected output and conventional truthy CI environments use only a start line and the final success or error, so captured logs stay useful. AnimationsEnabled can explicitly opt a terminal back into animation.
Set TerminalProgressEnabled to true to mirror loader and progress lifecycles through the OSC 9;4 terminal progress protocol. Loaders publish indeterminate activity, determinate progress publishes its current percentage, and every terminal outcome clears the indicator. Supporting terminal emulators decide whether that appears in a tab, window edge, or operating-system taskbar; unsupported terminals ignore the sequence. The option is independent of AnimationsEnabled, still requires terminal output with ANSI support, and never writes control sequences to redirected output.
Representative terminal snapshots are shown below; each display redraws one physical line rather than appending these frames. The last line is the exact Unicode rendering at a width of 14 cells.
⠸ Verifying modules
Packaging release [██████████████░░░░░░░░░░] 60%
Packaging… 60%
Stop, Success, Warn, and Fail are idempotent terminal operations; the first one wins. Complete output lines temporarily clear and redraw the active transient display. Partial Print/Printf output and prompts pause live output until the line completes or input returns.
After Start succeeds, immediately defer loader.Stop() or defer progress.Stop(). An explicit success or failure wins first, while the deferred stop safely releases the transient line on an early return.
Progress follows the same lifecycle: Set, Add, and Update change live state, while Step(current, message) atomically sets the absolute completed amount and message. Use Add for relative increments. Complete, Fail, or Stop finishes it, and the first terminal operation wins. Reaching the total does not implicitly report success.
Prompts
Prompts refuse to read when the configured input and output are not terminals—or when a conventional truthy CI value is present—returning ErrNonInteractive instead of unexpectedly blocking automation. Tests and intentional scripted input can opt in explicitly:
var output bytes.Buffer
interactive := true
color := false
unicode := true
console.SetDefault(console.New(console.Config{
Stdin: strings.NewReader("yes\n"),
Stdout: &output,
InteractiveEnabled: &interactive,
ColorEnabled: &color,
UnicodeEnabled: &unicode,
}))
confirmed, err := console.Confirm("Deploy now", false)
fmt.Println(strings.TrimSpace(output.String()))
// › Deploy now [y/N]:
fmt.Println(confirmed, err)
// true <nil>
The prompt reader is retained for the lifetime of the console, so sequential prompts do not lose input to buffering.
While a prompt waits for input, complete writes from other goroutines wait rather than overwrite the live input line.
AskSecret uses terminal password input and never falls back to an echoed line. Tests and custom terminal integrations can inject Config.ReadSecret; the returned value is never printed by the package.
Choose returns the selected value. Use ChooseIndex when the zero-based position is more useful for looking up related configuration.
Output behavior
Action, info, success, warning, and debug messages go to stdout. Error and fatal messages go to stderr. Fatal and Fatalf are the only helpers that exit; their exit function is configurable.
Marks follow the capability of their destination, so error styling is decided from stderr independently of stdout.
Color selection follows this precedence:
Config.ColorEnabled when set.
NO_COLOR disables styling.
- A nonzero
CLICOLOR_FORCE enables styling.
CLICOLOR=0 or TERM=dumb disables styling.
- Otherwise the destination must expose a terminal file descriptor with ANSI support.
On Windows, ANSI support is probed without leaving console mode changed. ANSI-bearing writes temporarily enable virtual-terminal processing and restore the original mode before returning.
Debug output is enabled by a nonzero FORJ_DEBUG, APP_DEBUG, or DEBUG value unless Config.DebugEnabled overrides it.
Runnable examples