gonsole

package module
v0.6.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 7, 2026 License: Apache-2.0 Imports: 22 Imported by: 0

Documentation

Overview

Package gonsole runs the command line of a Go program built from core commands, settings and compiled plugins.

Index

Constants

View Source
const ExitDone = 0

ExitDone is the code of a finished command, a help page or a dry run.

View Source
const ExitFailed = 1

ExitFailed is the code of a command that ran and failed.

View Source
const ExitMisused = 2

ExitMisused is the code of a command line the program cannot read.

Variables

View Source
var ErrGraceRanOut = errors.New("gonsole: the shutdown grace ran out")

ErrGraceRanOut is the cause context.Cause reports for a request Serve cancels after the shutdown grace.

View Source
var ErrMisused = errors.New("gonsole: misused")

ErrMisused marks an error the program answers with ExitMisused.

View Source
var ErrStillServing = errors.New("gonsole: requests still running after the cancel grace")

ErrStillServing reports requests still running when the cancel grace ended.

Functions

func BaseCommands added in v0.4.0

func BaseCommands() []string

BaseCommands returns the names the engine owns as commands and as namespaces in every program.

func Main

func Main(p Program) int

Main runs p over os.Args[1:] and the standard streams under a context the first SIGINT or SIGTERM ends.

func Misuse

func Misuse(err error) error

Misuse returns err wrapped with ErrMisused.

func NewServer

func NewServer(addr string, handler http.Handler, t Timeouts) *http.Server

NewServer returns an HTTP server for handler at addr under the timeouts.

func Parse

func Parse[T any](e Env, name string, fallback T, parse func(string) (T, error)) (T, error)

Parse returns the setting read by parse, the fallback when it is empty, any error naming the setting.

func Serve

func Serve(
	ctx context.Context, srv *http.Server, t Timeouts, stop func(context.Context) error, logger *slog.Logger,
) error

Serve serves srv until ctx ends or serving fails, then drains it, cancelling what outlasts the grace, and calls stop.

func StopHost added in v0.4.0

func StopHost(ctx context.Context, host PluginHost, grace time.Duration) error

StopHost stops host within grace, whether or not ctx has ended, refusing a grace that is not above zero.

Types

type Bound

type Bound func(*limits)

Bound narrows what a Count, Counts or Duration setting accepts, each reader ignoring a bound made for another.

func AllowZero

func AllowZero() Bound

AllowZero accepts zero beside the values above it.

func AtMost

func AtMost(highest int64) Bound

AtMost refuses a value above highest.

func Entries added in v0.5.0

func Entries(fewest, most int) Bound

Entries refuses a Counts setting that lists fewer than fewest or more than most numbers.

func WholeMilliseconds added in v0.5.0

func WholeMilliseconds() Bound

WholeMilliseconds refuses a Duration setting that is not a whole number of milliseconds.

type Call

type Call struct {
	// Args holds the positional arguments, one per name in Command.Args.
	Args []string
	// Flags maps each of the command's own flags the line set to its value, the engine flags left out.
	Flags map[string]string
	// Stdin is the input a command reads, such as a password.
	Stdin io.Reader
	// Stdout is where a command writes its answer.
	Stdout io.Writer
	// Stderr is where a command writes progress and warnings.
	Stderr io.Writer
	// Env reads the program's settings.
	Env Env
	// JSON reports whether -json was passed.
	JSON bool
	// Apply reports whether the run applies its writes.
	Apply bool
	// Actor is the account the -as flag names.
	Actor string
	// Describe reports a run that needs only command descriptors.
	Describe bool
	// contains filtered or unexported fields
}

Call is what one run of a command receives.

func (Call) DatabaseURL

func (c Call) DatabaseURL() (string, error)

DatabaseURL returns the program's database address, an error naming an empty setting unless the call describes.

func (Call) Encode

func (c Call) Encode(v any) error

Encode writes v to Stdout as one indented JSON document.

func (Call) Plugins

func (c Call) Plugins(ctx context.Context) (Loaded, error)

Plugins returns the registered plugins' command groups and schema steps.

type Command

type Command struct {
	// Name is the full name, such as status or report:create, in lowercase words joined by hyphens.
	Name string
	// Summary is the one line the listing prints beside the name.
	Summary string
	// Args names the positional arguments in order, each one required.
	Args []string
	// Flags declares the command's own flags, nil for none.
	Flags func(fs *flag.FlagSet)
	// Needs names the command's own flags the line must set to a text that is not blank, nil for none.
	Needs []string
	// Writes marks a command that writes to the database.
	Writes bool
	// JSON marks a command that answers one JSON document.
	JSON bool
	// Migrates marks a core command the core schema steps run before.
	Migrates bool
	// Capability names the capability the acting account must hold, empty for none.
	Capability string
	// Run does the command's work.
	Run func(ctx context.Context, call Call) error
}

Command is one command a program or a plugin offers.

type Env

type Env struct {
	// Prefix starts every setting name, such as MYAPP_.
	Prefix string
	// Getenv reads one variable, nil reading every variable as empty.
	Getenv func(string) string
}

Env reads settings under one prefix.

func (Env) Count

func (e Env) Count(name string, fallback int, bounds ...Bound) (int, error)

Count returns the setting as a whole number above zero, the fallback when it is empty.

func (Env) Counts added in v0.5.0

func (e Env) Counts(name string, fallback []int, bounds ...Bound) ([]int, error)

Counts returns the setting as rising whole numbers above zero split by commas, the fallback when it is empty.

func (Env) Duration

func (e Env) Duration(name string, fallback time.Duration, bounds ...Bound) (time.Duration, error)

Duration returns the setting as a duration above zero, the fallback when it is empty.

func (Env) Flag

func (e Env) Flag(name string, fallback bool) (bool, error)

Flag returns the setting as true or false, the fallback when it is empty.

func (Env) Key

func (e Env) Key(name string) string

Key returns the full name of the setting called name.

func (Env) Required

func (e Env) Required(name string) (string, error)

Required returns the setting's value, an error naming it when it is empty.

func (Env) Timeouts

func (e Env) Timeouts(fallback Timeouts) (Timeouts, error)

Timeouts returns the HTTP timeouts and the shutdown graces, each falling back to fallback.

func (Env) Value

func (e Env) Value(name string) string

Value returns the setting's value with surrounding spaces trimmed, empty when it is unset.

func (Env) Within

func (e Env) Within(more string) Env

Within returns the settings under the prefix followed by more.

type Group

type Group struct {
	// Namespace is the plugin id every command name in the group starts with.
	Namespace string
	// Commands are the plugin's commands.
	Commands []Command
}

Group is the commands one plugin offers under the namespace equal to its id.

func Walk

func Walk[P interface{ ID() string }](plugins []P) ([]Group, error)

Walk returns the command groups of the plugins that implement Provider and an error naming each one that panicked.

type Loaded

type Loaded struct {
	// Groups are the command groups, one per plugin that offers commands.
	Groups []Group
	// Migrate applies every plugin's schema in registration order.
	Migrate func(ctx context.Context) error
	// Seed stores every plugin's demo data in registration order.
	Seed func(ctx context.Context) error
	// Failed joins the errors of plugins that failed to register or to describe their commands.
	Failed error
	// Release stops every registered plugin and closes what registering opened.
	Release func(ctx context.Context) error
}

Loaded is what registering the plugins answers.

func Hosted added in v0.3.0

func Hosted[P interface{ ID() string }](
	plugins []P, host PluginHost, failed error, grace time.Duration, done func(),
) Loaded

Hosted returns what registering answers for plugins host runs, its Release stopping host within grace, then done.

type PluginHost added in v0.3.0

type PluginHost interface {
	// Migrate applies every plugin's schema.
	Migrate(ctx context.Context) error
	// Seed stores every plugin's demo data.
	Seed(ctx context.Context) error
	// Stop releases what every plugin holds.
	Stop(ctx context.Context) error
}

PluginHost migrates, seeds and stops the plugins a program registered.

type Program

type Program struct {
	// Name is the executable name, the first word of every usage line and error.
	Name string
	// Title is the line the listing opens with.
	Title string
	// Version is the version the version command prints.
	Version string
	// Footer is the text the listing closes with.
	Footer string
	// Env reads the program's settings under its prefix.
	Env Env
	// Database is the name of the setting that holds the database address.
	Database string
	// Reserved lists namespaces core keeps before any of its commands uses them.
	Reserved []string
	// Renamed maps an old two word spelling to the full name of the command that replaced it.
	Renamed map[string]string
	// BareServes reports whether a run that names no command serves instead of printing the listing.
	BareServes bool
	// Serve runs the server.
	Serve func(ctx context.Context, call Call) error
	// Validate reads and checks every core setting.
	Validate func(ctx context.Context, call Call) error
	// Migrations are the core schema steps in the order they apply.
	Migrations []Step
	// Lock holds the database against concurrent migrations and returns its release.
	Lock func(ctx context.Context, databaseURL string) (func(context.Context) error, error)
	// Seed stores the core demo data over a migrated schema.
	Seed func(ctx context.Context, call Call) error
	// Commands are the program's own commands, each named alone or as namespace:command.
	Commands []Command
	// Plugins registers the compiled plugins and starts none of them.
	Plugins func(ctx context.Context, call Call) (Loaded, error)
	// Authorize refuses the call's actor when that account lacks capability.
	Authorize func(ctx context.Context, call Call, capability string) error
	// Record stores one entry naming the actor and the command it applied.
	Record func(ctx context.Context, call Call, command string) error
}

Program is one executable's command line.

func (Program) Check

func (p Program) Check(loaded Loaded) error

Check returns every offence against the naming rules in the program and the loaded plugins.

func (Program) Run

func (p Program) Run(ctx context.Context, args []string, stdin io.Reader, stdout, stderr io.Writer) int

Run runs the command args name and returns the exit code.

type Provider

type Provider interface {
	// Commands returns the plugin's commands.
	Commands() []Command
}

Provider is implemented by plugins that offer commands under the namespace equal to their id.

type Step

type Step struct {
	// Name is the step's name in its output line.
	Name string
	// Run applies the step against the database at databaseURL.
	Run func(ctx context.Context, databaseURL string) error
}

Step is one named schema step.

type Timeouts

type Timeouts struct {
	// ReadHeader bounds reading one request's headers, the HTTP_READ_HEADER_TIMEOUT setting.
	ReadHeader time.Duration
	// Read bounds reading one whole request, the HTTP_READ_TIMEOUT setting.
	Read time.Duration
	// Idle bounds how long a kept alive connection waits for its next request, the HTTP_IDLE_TIMEOUT setting.
	Idle time.Duration
	// Grace bounds how long open requests get to finish once the run ends, the SHUTDOWN_GRACE setting.
	Grace time.Duration
	// CancelGrace bounds how long the requests cancelled after the grace get to end, the SHUTDOWN_CANCEL_GRACE setting.
	CancelGrace time.Duration
	// StopGrace bounds the stop of what the server serves, the SHUTDOWN_STOP_GRACE setting.
	StopGrace time.Duration
}

Timeouts are the HTTP timeouts and the shutdown graces one server runs under.

Directories

Path Synopsis
auth module
internal
exampleapp
Package exampleapp builds the example program the module's tests run as its own process.
Package exampleapp builds the example program the module's tests run as its own process.
Package locale reads a setting that names a locale as a BCP 47 language tag.
Package locale reads a setting that names a locale as a BCP 47 language tag.
Package testkit runs programs built on gonsole from tests, in process and as built binaries.
Package testkit runs programs built on gonsole from tests, in process and as built binaries.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL