Documentation
¶
Overview ¶
Package termrender provides terminal client detection and ANSI text rendering for serving styled text responses to CLI clients like curl, wget, and HTTPie.
Index ¶
- Variables
- func CrossRef(path string) string
- func FormatBandwidth(mbps int) string
- func FormatFreshness(t time.Time) string
- func FormatSpeed(mbps int) string
- func HasNoColor(input DetectInput) bool
- func ParseSections(raw string) map[string]bool
- func PolicyStyle(policy string) string
- func Register[T any](fn func(T, io.Writer, *Renderer) error)
- func RenderJSON(w io.Writer, data any) error
- func ShouldShowField(context, field string, width int) bool
- func ShouldShowSection(sections map[string]bool, name string) bool
- func SpeedStyle(mbps int) lipgloss.Style
- func TableBorder(mode RenderMode) lipgloss.Border
- func TruncateName(name string, maxWidth int) string
- type DetectInput
- type RenderMode
- type Renderer
- func (r *Renderer) Mode() RenderMode
- func (r *Renderer) NoColor() bool
- func (r *Renderer) RenderAboutPage(w io.Writer, data templates.DataFreshness, privacy templates.PrivacySync) error
- func (r *Renderer) RenderCampusDetail(w io.Writer, data templates.CampusDetail) error
- func (r *Renderer) RenderCarrierDetail(w io.Writer, data templates.CarrierDetail) error
- func (r *Renderer) RenderCompare(w io.Writer, data *templates.CompareData) error
- func (r *Renderer) RenderError(w io.Writer, statusCode int, title string, message string) error
- func (r *Renderer) RenderFacilityDetail(w io.Writer, data templates.FacilityDetail) error
- func (r *Renderer) RenderHelp(w io.Writer, freshness time.Time) error
- func (r *Renderer) RenderIXDetail(w io.Writer, data templates.IXDetail) error
- func (r *Renderer) RenderNetworkDetail(w io.Writer, data templates.NetworkDetail) error
- func (r *Renderer) RenderOrgDetail(w io.Writer, data templates.OrgDetail) error
- func (r *Renderer) RenderPage(w io.Writer, title string, data any) error
- func (r *Renderer) RenderSearch(w io.Writer, groups []templates.SearchGroup) error
- func (r *Renderer) RenderShort(w io.Writer, data any) error
- func (r *Renderer) RenderWHOIS(w io.Writer, _ string, data any) error
- func (r *Renderer) Write(w io.Writer, content string) error
- func (r *Renderer) Writef(w io.Writer, format string, args ...any) error
Constants ¶
This section is empty.
Variables ¶
var ( // ColorSpeedSub1G maps to Tailwind gray-400 for sub-1G port speeds. ColorSpeedSub1G = lipgloss.Color("245") // ColorSpeed1G maps to Tailwind neutral-300 for 1G port speeds. ColorSpeed1G = lipgloss.Color("250") // ColorSpeed10G maps to Tailwind blue-500 for 10G port speeds. ColorSpeed10G = lipgloss.Color("33") // ColorSpeed100G maps to Tailwind emerald-500 for 100G port speeds. ColorSpeed100G = lipgloss.Color("42") // ColorSpeed400G maps to Tailwind amber-500 for 400G+ port speeds. ColorSpeed400G = lipgloss.Color("214") )
Color constants mapping Tailwind CSS color tiers to ANSI 256-color codes. These correspond to the port speed color tiers used in the web UI (D-09).
var ( // ColorHeading is emerald for section headings. ColorHeading color.Color = lipgloss.Color("42") // ColorLabel is gray for field labels. ColorLabel color.Color = lipgloss.Color("245") // ColorValue is bright white for field values. ColorValue color.Color = lipgloss.Color("255") // ColorLink is blue for URLs and cross-references. ColorLink color.Color = lipgloss.Color("33") // ColorError is red for error messages. ColorError color.Color = lipgloss.Color("196") // ColorWarning is amber for warning messages. ColorWarning color.Color = lipgloss.Color("214") // ColorSuccess is green/emerald for success messages. ColorSuccess color.Color = lipgloss.Color("42") // ColorMuted is dim gray for secondary text. ColorMuted color.Color = lipgloss.Color("240") )
General-purpose color constants for terminal text rendering.
var ( // ColorPolicyOpen is green for Open peering policy. ColorPolicyOpen color.Color = lipgloss.Color("42") // ColorPolicySelective is yellow for Selective peering policy. ColorPolicySelective color.Color = lipgloss.Color("214") // ColorPolicyRestrictive is red for Restrictive peering policy. ColorPolicyRestrictive color.Color = lipgloss.Color("196") )
Peering policy color constants.
var ( // StyleHeading renders bold emerald text for section headings. StyleHeading = lipgloss.NewStyle().Bold(true).Foreground(ColorHeading) // StyleLabel renders gray text for field labels. StyleLabel = lipgloss.NewStyle().Foreground(ColorLabel) // StyleValue renders bright white text for field values. StyleValue = lipgloss.NewStyle().Foreground(ColorValue) // StyleMuted renders dim gray text for secondary content. StyleMuted = lipgloss.NewStyle().Foreground(ColorMuted) // StyleError renders bold red text for error messages. StyleError = lipgloss.NewStyle().Bold(true).Foreground(ColorError) // StyleLink renders underlined blue text for URLs and cross-references. StyleLink = lipgloss.NewStyle().Foreground(ColorLink).Underline(true) // StyleBold renders bold text without color. StyleBold = lipgloss.NewStyle().Bold(true) )
Predefined lipgloss styles for consistent terminal text formatting.
Functions ¶
func CrossRef ¶
CrossRef formats an inline cross-reference path styled with StyleLink. (RND-16, D-08) Example output: "[/ui/ix/31]" with link styling.
func FormatBandwidth ¶
FormatBandwidth formats aggregate bandwidth in Mbps as a human-readable string. Returns "1.5 Tbps" for >= 1M, "10 Gbps" for >= 1000, "500 Mbps" otherwise. Matches the web UI's formatAggregateBW. (RND-15)
func FormatFreshness ¶
FormatFreshness formats a sync timestamp as a styled footer line for terminal responses. Returns "Data: {RFC3339}" with leading and trailing newlines for visual separation. Returns "" for zero time (footer omitted). (DIF-02, D-13, D-14, D-15)
The output is intentionally free of wall-clock-relative phrasing ("N minutes ago"). The terminal footer is rendered into responses that are cached by the sync-time-keyed HTTP caching middleware, and any relative text would freeze at cache-creation time and mislead readers for up to a full sync interval. Readers who want a relative age can compute it locally from the absolute RFC3339 timestamp.
func FormatSpeed ¶
FormatSpeed converts a speed in Mbps to a human-readable string. Matches the web UI's formatSpeed: >= 1,000,000 as terabits, >= 1000 as gigabits, else megabits.
func HasNoColor ¶
func HasNoColor(input DetectInput) bool
HasNoColor reports whether the request includes a ?nocolor query parameter, which suppresses all ANSI escape codes regardless of render mode (D-04, RND-18).
func ParseSections ¶
ParseSections parses a comma-separated section filter string into a set of canonical section names. Returns nil if raw is empty or contains no recognized section names (nil means "show all sections").
func PolicyStyle ¶
PolicyStyle returns styled text for a peering policy value. (RND-13, D-03) Open=green (ColorPolicyOpen), Selective=yellow (ColorPolicySelective), Restrictive=red (ColorPolicyRestrictive), others=default value style.
func Register ¶ added in v1.9.0
Register associates a data type T with a render function for terminal output. Registered functions are called by RenderPage when the data argument matches type T.
func RenderJSON ¶
RenderJSON writes data as indented JSON to w. Used for ?format=json responses. The caller is responsible for setting appropriate Content-Type headers.
func ShouldShowField ¶
ShouldShowField reports whether a field should be rendered at a given terminal width. context identifies the entity-section (e.g., "net-ix"), field is the column name, and width is the terminal width in characters. Returns true if width is 0 (no restriction), the context is unknown, or the field is not listed (unlisted = always shown).
func ShouldShowSection ¶
ShouldShowSection reports whether a section should be rendered given the active section filter. If sections is nil (no filter), all sections are shown.
func SpeedStyle ¶
SpeedStyle returns a lipgloss style colored by port speed tier. (RND-12) Matches web UI tiers: sub-1G gray, 1G neutral, 10G blue, 100G emerald, 400G+ amber.
func TableBorder ¶
func TableBorder(mode RenderMode) lipgloss.Border
TableBorder returns the appropriate lipgloss border style for a given mode. Rich mode uses Unicode box-drawing characters; plain mode uses ASCII (D-10).
func TruncateName ¶ added in v1.9.0
TruncateName returns name truncated to maxWidth with "..." suffix. Returns name unchanged if it fits within maxWidth or maxWidth <= 3.
Types ¶
type DetectInput ¶
DetectInput holds parameters for detecting the render mode. Defined per CS-5 to bundle >2 function arguments.
type RenderMode ¶
type RenderMode int
RenderMode describes the output format for a response.
const ( // ModeHTML renders the standard web UI page. ModeHTML RenderMode = iota // ModeHTMX renders an htmx fragment (no layout shell). ModeHTMX // ModeRich renders ANSI-colored terminal output with Unicode box drawing. ModeRich // ModePlain renders plain ASCII text with no ANSI codes. ModePlain // ModeJSON renders the data as JSON. ModeJSON // ModeWHOIS renders RPSL-style key-value output. ModeWHOIS // ModeShort renders a single pipe-delimited summary line for scripting. ModeShort )
func Detect ¶
func Detect(input DetectInput) RenderMode
Detect returns the appropriate render mode based on the priority chain: query params > Accept header > User-Agent > HX-Request > default (HTML).
func (RenderMode) String ¶
func (m RenderMode) String() string
String returns a human-readable name for the render mode.
type Renderer ¶
type Renderer struct {
// Sections is a per-request section filter (nil = show all). Set by the
// caller after NewRenderer, before calling RenderPage.
Sections map[string]bool
// Width is a per-request width adaptation hint (0 = no restriction). Set
// by the caller after NewRenderer, before calling RenderPage.
Width int
// contains filtered or unexported fields
}
Renderer produces styled terminal text output with ANSI color control. It uses colorprofile.Writer to force the appropriate color profile for HTTP responses, since HTTP response writers are not TTYs and would otherwise auto-detect as NoTTY.
func NewRenderer ¶
func NewRenderer(mode RenderMode, noColor bool) *Renderer
NewRenderer creates a terminal renderer. mode controls ANSI/ASCII/JSON selection. noColor suppresses all ANSI codes regardless of mode.
func (*Renderer) Mode ¶
func (r *Renderer) Mode() RenderMode
Mode returns the renderer's output mode.
func (*Renderer) RenderAboutPage ¶ added in v1.12.0
func (r *Renderer) RenderAboutPage(w io.Writer, data templates.DataFreshness, privacy templates.PrivacySync) error
RenderAboutPage renders the About page as terminal output with project info, data freshness, the Phase 61 OBS-02 Privacy & Sync section, and a list of API endpoints. The Privacy & Sync section is placed between Data Age and API Endpoints per D-04 so operators see the auth posture adjacent to the freshness signal.
func (*Renderer) RenderCampusDetail ¶
RenderCampusDetail renders a campus entity as terminal output with minimal layout. Shows compact header with identity fields and facility list. (RND-06, D-03 minimal layout)
func (*Renderer) RenderCarrierDetail ¶
RenderCarrierDetail renders a carrier entity as terminal output with minimal layout. Shows compact header with identity fields and facility list. (RND-07, D-03 minimal layout)
func (*Renderer) RenderCompare ¶
RenderCompare renders a network comparison as terminal output showing shared IXPs, facilities, and campuses with per-network presence details. (RND-09)
func (*Renderer) RenderError ¶
RenderError writes a terminal-formatted error page with status code, title, message, and a hint pointing users to the help page.
func (*Renderer) RenderFacilityDetail ¶
RenderFacilityDetail renders a facility entity as terminal output with rich layout. Shows key-value header with address, network list, IX list, and carrier list. (RND-04, D-02 rich layout)
func (*Renderer) RenderHelp ¶
RenderHelp writes terminal help text listing available endpoints, query parameters, format options, and usage examples. Style inspired by wttr.in (D-13).
func (*Renderer) RenderIXDetail ¶
RenderIXDetail renders an IX entity as terminal output with rich layout. Shows key-value header, participant table with speed/RS/IPs, facility list, and prefix list. (RND-03, D-02 rich layout)
func (*Renderer) RenderNetworkDetail ¶
RenderNetworkDetail renders a network entity as whois-style terminal output with colored speed tiers, policy badges, RS indicators, and navigable cross-references. (RND-02, RND-14, RND-16, D-01 through D-09)
func (*Renderer) RenderOrgDetail ¶
RenderOrgDetail renders an organization entity as terminal output with minimal layout. Shows compact header with identity fields and simple name-only child entity lists. (RND-05, D-03 minimal layout)
func (*Renderer) RenderPage ¶
RenderPage renders a terminal page, dispatching to entity-specific renderers via the registered function map. Falls back to a generic stub for unrecognized types.
func (*Renderer) RenderSearch ¶
RenderSearch renders search results as a grouped text list for terminal clients. Results are grouped by entity type with headers showing total counts. Each result shows the entity name, subtitle (ASN or location), and detail URL. (RND-08, D-05 through D-07)
func (*Renderer) RenderShort ¶
RenderShort writes a single pipe-delimited summary line for the given entity. Designed for scripting and shell integration (?format=short). Each entity type produces a compact one-liner terminated by \n. (DIF-01, D-01 through D-05)
func (*Renderer) RenderWHOIS ¶
RenderWHOIS renders entity data in RPSL-like WHOIS format. Dispatches to per-entity WHOIS renderers based on data type. Returns an "unsupported" message for search/compare views. (RND-17, D-10 through D-15)