Documentation
¶
Overview ¶
Package system consolidates the boilerplate prelude every service repeats in its main(): .env loading, logger setup, startup banner, build-time log line, and a signal-cancellable context. It also owns the module-lifecycle loop (RunForever) so a service entrypoint is just Boot → wire → RunForever.
What it does NOT do:
- Open Mongo. Each service decides whether it needs it; call mongo.New(ctx) yourself after Boot when it does. Boot doesn't manage that lifetime so tests / CLIs / migration jobs can opt in selectively.
The HTTP server lives in this package too — NewServer returns a Module that drops into RunForever alongside any other lifecycle workers (NATS consumers, dev watchers, schedulers).
Index ¶
- Constants
- Variables
- func Boot(opts *bootOptions) context.Context
- func BootOptions(service string) *bootOptions
- func BuildInfo() string
- func Draining() bool
- func ListenAddr() string
- func ListenPort() int
- func RunForever(ctx context.Context, modules ...Module) error
- func ServiceName() string
- func SetDraining(v bool)
- func SourceEnv(key string) string
- type BuildInfoData
- type Module
- type Option
- type Server
- type ServerOptions
- type ShutdownModule
Constants ¶
const ( SourceDefault = "default" SourceOption = "option" )
Source labels used in the defaults lines.
const DefaultPort = 8080
DefaultPort is the listen port ListenAddr falls back to when neither HB_PORT nor Boot's Port option gives one.
const DefaultsMsg = "effective defaults"
DefaultsMsg is the message of the "effective defaults" log lines that Boot and the kit's constructors emit once at startup, one per area (attribute "area"), each value paired with its source ("default", "env <KEY>", "option"). Secrets are never logged, only whether they are set.
Variables ¶
var DefaultServerOptions = ServerOptions{
ReadHeaderTimeout: defaultReadHeaderTimeout,
ReadTimeout: defaultReadTimeout,
WriteTimeout: defaultWriteTimeout,
IdleTimeout: defaultIdleTimeout,
MaxHeaderBytes: defaultMaxHeaderBytes,
ShutdownGrace: defaultShutdownGrace,
}
DefaultServerOptions are the values every service uses unless it has a domain-specific reason to deviate. See the default* group above for the rationale of each field.
Functions ¶
func Boot ¶
Boot is the standard prelude every service runs in main(). One call instead of five, in a fixed order, returns the signal-cancellable context. Service name comes from opts.service (set by CreatebootOptions), so the entire boot config lives in one value and the call site stays a single argument:
ctx := system.Boot(system.CreatebootOptions("service-tools").
With(system.WithoutBanner()))
ctx := system.Boot(system.CreatebootOptions("service-edge").With(
system.Port(8080),
system.BannerExtras("watching: services/service-edge/..."),
))
Sequence:
- .env load (best-effort; production gets vars from the cluster).
- Logger from core/log, installed as the process default so context-bound loggers inherit the service tag.
- Banner with Local / Network URLs (when Port is set).
- EnvBuildTime log line — invaluable when telling whether a rollout "took" or k8s is still serving the old image.
- signal.NotifyContext for SIGINT / SIGTERM. Returned so callers can pass it to RunForever or compose with their own workers.
Passing nil opts panics — service name is required, and silently substituting a placeholder would scatter empty service tags across every downstream log/metric. Use CreatebootOptions(name) even when no other knobs are needed.
Calling Boot more than once in the same process is safe but only the first call installs the signal handler. Tests should treat Boot as a process-singleton.
func BootOptions ¶
func BootOptions(service string) *bootOptions
CreatebootOptions returns a bootOptions seeded with the service name, ready for With. Service is required at construction (rather than as an option) so it's impossible to call Boot with an empty service — every log line, banner, and metric elsewhere keys off this string.
opts := system.CreatebootOptions(constants.ServiceFoo).With(
system.Port(8080),
system.BannerExtras(site.BannerExtras()...),
)
ctx := system.Boot(opts)
func BuildInfo ¶
func BuildInfo() string
BuildInfo returns the combined "<version> · <pretty time>" string for boot logs and any non-HTML context that wants both pieces at once. HTML templates should call ReadBuildInfo() instead so the time can be wrapped in <time> and localised by JS. Returns "" when both halves are empty so callers can branch without painting a lonely separator.
func Draining ¶
func Draining() bool
Draining reports whether the process received its shutdown signal and is draining. Readiness handlers answer 503 while it is true so the load balancer stops routing new requests here; liveness must stay 200 (the process is healthy, just leaving).
func ListenAddr ¶
func ListenAddr() string
ListenAddr returns ":<ListenPort()>", the address NewServer uses when ServerOptions.Addr is empty.
func ListenPort ¶
func ListenPort() int
ListenPort returns the effective listen port: constants.EnvPort (HB_PORT) when it holds a positive integer, else the port given to Boot via the Port option, else DefaultPort.
func RunForever ¶
RunForever is the standard service entrypoint. It:
- Filters nil entries so callers can pass conditionally-built modules (e.g. `devServer`, which is nil in prod) directly, without an `if x != nil { append }` dance.
- Calls Register on every remaining module in declaration order. If any fails, no Shutdown is run (nothing started yet) and the error is returned.
- Blocks on ctx (the signal-cancellable context returned by Boot).
- On SIGTERM/SIGINT, flips Draining to true at once (readiness handlers answer 503 from then on), then waits the drain delay (constants.EnvShutdownDelay, default 5s) while still serving, so the load balancer stops routing to this instance before any listener closes.
- Calls Shutdown on every ShutdownModule in REVERSE order. The drain delay and the module shutdowns share one EnvShutdownTimeout budget (default 25s: 5s delay + up to 20s of module shutdown, under k8s' 30s terminationGracePeriodSeconds).
- Returns the first non-nil error from the shutdown phase, or nil if everything stopped cleanly.
Reverse order matters: if module B was registered after A, B's resources may depend on A's still being up. Tearing down in the reverse of construction is the safe default.
Typical wiring:
ctx := system.Boot("service-edge", system.WithPort(8080))
if err := system.RunForever(ctx,
system.NewServer(system.ServerOptions{Handler: handler}),
devServer, // may be nil; RunForever skips it
); err != nil {
log.Error("run", "err", err)
os.Exit(1)
}
func ServiceName ¶
func ServiceName() string
ServiceName returns the service name given to Boot, or "" before Boot ran.
func SetDraining ¶
func SetDraining(v bool)
SetDraining sets the flag Draining reports. RunForever sets it on the shutdown signal; a custom lifecycle (or a test of a readiness handler) may set it directly.
Types ¶
type BuildInfoData ¶
BuildInfoData carries the three forms of the build stamp a typical service needs at render time:
- Version — raw HB_BUILD_VERSION ("v1.0.487").
- Time — raw HB_BUILD_TIME in RFC 3339 ("2026-05-25T16:57:32Z"). Suitable for the `datetime` attribute of an HTML <time> tag so client-side JS can localise the stamp with `new Date(datetime).toLocaleString()`.
- TimePretty — "YYYY-MM-DD HH:MM UTC" — server-rendered fallback shown to no-JS visitors and to crawlers. A parse failure falls back to the raw env string so a hand-edited HB_BUILD_TIME still surfaces instead of vanishing silently.
Use Version + Time directly in HTML templates that wrap the time in <time datetime="...">; use BuildInfo() for the combined "version · pretty-UTC" string in boot logs and non-HTML contexts.
func ReadBuildInfo ¶
func ReadBuildInfo() BuildInfoData
ReadBuildInfo snapshots the build stamp from the HB_BUILD_* env vars (which system.Boot promotes from the BuildVersion / BuildTime options or any pre-existing env). Cheap enough to call per request, but typically captured once at startup and reused via closure so the env reads + RFC-3339 parse don't re-run on every render.
type Module ¶
Module is implemented by every worker that wants to register itself into a service. Register wires up NATS consumers / starts an HTTP listener / launches background goroutines, and returns immediately — long-lived work runs in goroutines anchored to the lifecycle ctx.
type Option ¶
Option is the unit bootOptions.With consumes. Every boot-time knob (port, banner extras, logger override, etc.) is exposed as a constructor in this package that returns an Option, and bootOptions.With dispatches by GetName to write the right private field. Adding a new knob means writing one constructor + one case in With — nothing else changes at the call site.
func BannerExtras ¶
BannerExtras appends arbitrary lines to the boxed banner — "watching: …", "🔥 Hot-reload: on", any human-readable startup hint. Multiple With(BannerExtras(...)) calls accumulate.
func Build ¶
Build is the convenience bundle for the common "I have both pieces" path. Returns a slice so callers can spread it into With:
With(system.Build(buildVersion, buildTime)...)
Equivalent to passing BuildVersion + BuildTime individually.
func BuildTime ¶
BuildTime sets the build-stamp Boot logs and that downstream code can read via HB_BUILD_TIME. Same injection convention as BuildVersion. Use RFC 3339 (`date -u +%Y-%m-%dT%H:%M:%SZ`) so the value is sortable in log search.
func BuildVersion ¶
BuildVersion sets the human-readable version string that Boot logs and that downstream code (template helpers, /healthz, …) can read via HB_BUILD_VERSION. Intended to be the ldflags-injected Go var from main:
go build -ldflags="-X main.buildVersion=v1.0.487" …
Empty strings and the conventional sentinels "dev" / "unknown" are ignored so a `go run` invocation without ldflags falls back to whatever HB_BUILD_VERSION already holds (often "").
func Port ¶
Port sets the listen port the banner prints in its Local / Network URL lines. Zero or unset means the banner falls back to the title-only Box (no URLs). The HTTP listener itself is the caller's job — wire NewServer into RunForever to bind it.
func WithLogger ¶
func WithLogger(l logger) Option
WithLogger overrides the logger Boot uses for its own boot-time log lines (the "build" record, primarily). Rare — usually you want the canonical one core/log builds for you, which Boot installs as the process default automatically.
Note: when WithLogger is used Boot does NOT call log.SetDefault. The caller is responsible for installing whatever process-wide default they want via log.SetDefault before or after Boot. This keeps the system package free of any direct logging-library dependency: the parameter is an interface, not *log.Logger, so Boot can't pass it to log.SetDefault on its own.
func WithoutBanner ¶
func WithoutBanner() Option
WithoutBanner skips the boxed banner. Use for one-shot CLIs and migration jobs whose output is the only thing that matters.
func WithoutDotenv ¶
func WithoutDotenv() Option
WithoutDotenv skips godotenv.Load. Use in tests or when the caller has already loaded a specific .env file.
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server is a hardened http.Server wrapped as a Module. Drops into RunForever next to NATS consumers, dev watchers, schedulers, and any other lifecycle workers. Construct with NewServer.
The shutdown path honours both the Module-level deadline (passed by RunForever via SHUTDOWN_TIMEOUT) and the per-server ShutdownGrace cap, whichever fires first. ListenAndServe runs in a goroutine started by Register; failures (port in use, permission denied) are surfaced when Shutdown drains the listener channel.
func NewServer ¶
func NewServer(opts ServerOptions) *Server
NewServer constructs a Server from ServerOptions. Validation is deferred to Register so a bad config surfaces at the same place as other module Register errors (uniform error path inside RunForever).
Typical wiring:
ctx := system.Boot("service-edge", system.WithPort(8080))
if err := system.RunForever(ctx,
system.NewServer(system.ServerOptions{Handler: handler}), // Addr: system.ListenAddr()
// …other modules
); err != nil { … }
func (*Server) Register ¶
Register starts ListenAndServe in a background goroutine and returns immediately, matching the Module contract: long-lived work runs in goroutines anchored to ctx. ctx isn't used directly — RunForever owns the lifecycle and triggers Shutdown — but receiving it keeps the interface uniform across modules.
type ServerOptions ¶
type ServerOptions struct {
Addr string // default ListenAddr(): ":" + HB_PORT, else Boot's Port, else 8080
Handler http.Handler // required
ReadHeaderTimeout time.Duration // default 10 s
ReadTimeout time.Duration // default 30 s
WriteTimeout time.Duration // default 30 s
IdleTimeout time.Duration // default 120 s
MaxHeaderBytes int // default 64 KiB
ShutdownGrace time.Duration // default 10 s
}
ServerOptions bundles every knob the server needs. Zero values fall back to the matching field in DefaultServerOptions, so the typical caller fills only Addr and Handler.
type ShutdownModule ¶
ShutdownModule is the optional second half. If a module holds resources that need orderly teardown (open HTTP server, in-flight NATS handlers, websocket clients), implement Shutdown — RunForever detects the interface via type assertion and calls it before the process exits.
shutdownCtx has a deadline (constants.EnvShutdownTimeout, default 25s — under k8s' 30s terminationGracePeriodSeconds). Honour it: if the deadline fires, return whatever you have rather than blocking forever.