gox

package module
v0.2.2 Latest Latest
Warning

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

Go to latest
Published: Nov 18, 2026 License: MIT Imports: 24 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

gox

CI Go Reference

Go(x) is an opinionated Go service framework. Adopt it and stop deciding which logger, router, config loader, database driver, or observability stack to use: every service on gox looks the same, starts the same, shuts down the same, and shows up the same on dashboards.

It is built for services written with AI coding assistants. A small, symmetrical API, one project layout, self-explaining errors, and a single machine-readable reference (llm.txt) mean a model generates a correct service on the first try and spends its tokens on your domain, not on plumbing.

Go 1.26 or newer.

Two constraints that shape everything

  1. The common path is one import. A plain HTTP service imports only github.com/guilhermebr/gox. Lifecycle, config, logging, tracing, metrics, health, the admin server and the HTTP server live in the root.
  2. Heavy integrations are opt-in by import. Postgres, JWT, Supabase and server-rendered HTML are subpackages with an Enable() option and a From(app) accessor. A service that does not import gox/postgres never compiles pgx. CI proves it on every build.

A JSON API, one import

package main

import (
	"net/http"
	"os"

	"github.com/guilhermebr/gox"
)

func main() {
	a := gox.MustNew("hello", gox.HTTP())
	a.HandleFunc("GET /hello/{name}", func(w http.ResponseWriter, r *http.Request) {
		_ = gox.JSON(w, http.StatusOK, map[string]string{"hello": r.PathValue("name")})
	})
	if err := a.Run(); err != nil {
		os.Exit(1)
	}
}

Run it and you have structured JSON logs with request ids, traces, Prometheus metrics on :9090/metrics, /healthz and /readyz on both ports, pprof, a per-request timeout and body limit, one error envelope for everything, and a graceful drain on SIGTERM. You wrote none of that.

A service with Postgres, two imports

package main

import (
	"embed"
	"errors"
	"net/http"
	"os"
	"time"

	"github.com/jackc/pgx/v5"

	"github.com/guilhermebr/gox"
	"github.com/guilhermebr/gox/postgres"
)

//go:embed migrations/*.sql
var migrations embed.FS

type Config struct {
	gox.BaseConfig
	InvoiceTTL time.Duration `conf:"default:24h"`
}

func main() {
	var cfg Config
	a := gox.MustNew("billing",
		gox.WithConfig(&cfg),
		gox.HTTP(),
		postgres.Enable(postgres.WithMigrations(migrations)),
	)
	db := postgres.From(a)

	a.HandleFunc("GET /invoices/{id}", func(w http.ResponseWriter, r *http.Request) {
		var id string
		err := db.QueryRow(r.Context(), "SELECT id FROM invoices WHERE id = $1", r.PathValue("id")).Scan(&id)
		if errors.Is(err, pgx.ErrNoRows) {
			gox.Error(w, r, gox.NotFound("invoice %s", r.PathValue("id")))
			return
		}
		if err != nil {
			gox.Error(w, r, err)
			return
		}
		_ = gox.JSON(w, http.StatusOK, map[string]string{"id": id})
	})

	if err := a.Run(); err != nil {
		os.Exit(1)
	}
}

With BILLING_POSTGRES_URL set: the pool pings at boot (a lazy pool never reports healthy), the migration runs on a dedicated connection before /readyz turns green, queries are traced, pool stats are exported, and the pool closes last on shutdown.

A server-rendered HTML app on templ is the same shape with gox/web; see examples/web.

To push changes to browsers without polling, gox.HTTP(gox.WithSSE(...)) serves topic-based server-sent events and a.SSE().Publish sends them, to every replica with postgres.SSETransport; see examples/sse.

The opinions

gox chooses once so you do not. Each choice has an ADR in docs/decisions/.

gox chooses because
net/http and the Go 1.22 ServeMux models and people already know it; method and wildcard routing cover what routers were used for (ADR 0005)
log/slog, JSON in production, text in development stdlib, structured, with request and trace ids stamped from the context
ardanlabs/conf, one env prefix per service, --help lists everything one config pass, one source of truth, discoverable from the binary (ADR 0003)
OpenTelemetry traces and metrics, Prometheus on the admin port every service on the same dashboards with the same metric names
coded errors with a public-safe message and one JSON envelope clients see one shape from handlers and the framework alike; causes go to logs, never to clients (ADR 0004)
an explicit staged lifecycle, no DI container start order is fixed by stage, readable, and shutdown is the exact reverse (ADR 0002)
pgx plus golang-migrate on a dedicated connection what every consumer already used, minus the incident that starved a pool under a rolling deploy (ADR 0006)
templ, Alpine.js, HTMX 2, Tailwind standalone CLI, embedded hashed assets what the existing HTML apps converged on; no Node at build or run time (ADR 0007)
server-sent events with topics, fanned out over Postgres LISTEN/NOTIFY push over plain HTTP with the auth the service already has, and no broker to run (ADR 0016)
nested modules, one per feature a consumer's module graph contains only what it imports (ADR 0000)

Escape hatches

  • gox.Component(c) and a.Add(c) accept anything with Name, Start and Stop; implement Run for a blocking loop, Ready for readiness.
  • gox.WithMiddleware appends to the chain; gox.WithAuth fills the auth slot; gox.WithErrorMapper translates your own sentinels.
  • a.Mux() is the plain *http.ServeMux.
  • pkg/* is importable: pkg/lifecycle, pkg/config, pkg/log, pkg/errors, pkg/health, pkg/middleware, pkg/httpx, pkg/httpserver, pkg/httpclient, pkg/otel. Services rarely need them.

Writing a feature package

Every feature has the same shape: Config, Enable(opts...) gox.Option, From(a) T, With* options. Inside Enable, the gox.Builder gives you ConfigSection, Component, Setup, Finish, Middleware, ErrorRenderer and Set. docs/features.md walks through one.

Building blocks a service is made of (postgres, jobs, jwt, openapi, web) live at the top level. Clients for third-party services live under providers/, one module each (providers/mailgun, providers/posthog, providers/resend, providers/s3, providers/stripe, providers/supabase, providers/temporal, providers/workos; more cloud and SaaS APIs later).

Start a service

go install github.com/guilhermebr/gox/cmd/gox@latest
gox new billing --module github.com/acme/billing --postgres --web
cd billing && make run

gox new renders cmd/<name>/main.go, an example feature with a test, .env.example, a Makefile, a distroless Dockerfile, a lint config, a CI workflow, AGENTS.md and CLAUDE.md. --postgres adds a migrations package and postgres.Enable; --web adds a templ layout, a home page and embedded static assets. The result builds, tests, runs and answers /healthz with zero edits; a test in this repository proves it on every commit.

Documentation

  • llm.txt: the complete reference for models, generated from source.
  • docs/guide.md: build a service end to end.
  • docs/features.md: write your own Enable()/From() package.
  • docs/recipes/: one complete, build-checked example per task.
  • AGENTS.md: for agents working in this repository. Generated services get their own AGENTS.md and CLAUDE.md from the scaffold template.
  • examples/: minimal, http, postgres, sse, web.

Versioning

Semantic versioning per module: v0.x.y for the root, postgres/v0.x.y for a feature. Public API is deprecated for one minor version before it is removed.

Utilities

monetary (exact money arithmetic) and osrelease (Linux distribution detection) are plain libraries with no framework dependency.

Contributing

See CONTRIBUTING.md and AGENTS.md. make ci is the bar.

License

MIT. See LICENSE.

Documentation

Overview

Package gox is an opinionated, batteries-included base for Go services.

A plain HTTP service imports only this package. Heavy integrations (Postgres, Supabase, JWT, server-rendered HTML) live in their own subpackages and are opted into by importing them and passing their Enable() option to New.

Index

Constants

View Source
const (
	CodeOK                 = errors.CodeOK
	CodeCanceled           = errors.CodeCanceled
	CodeUnknown            = errors.CodeUnknown
	CodeInvalidArgument    = errors.CodeInvalidArgument
	CodeDeadlineExceeded   = errors.CodeDeadlineExceeded
	CodeNotFound           = errors.CodeNotFound
	CodeAlreadyExists      = errors.CodeAlreadyExists
	CodePermissionDenied   = errors.CodePermissionDenied
	CodeResourceExhausted  = errors.CodeResourceExhausted
	CodeFailedPrecondition = errors.CodeFailedPrecondition
	CodeAborted            = errors.CodeAborted
	CodeOutOfRange         = errors.CodeOutOfRange
	CodeUnimplemented      = errors.CodeUnimplemented
	CodeInternal           = errors.CodeInternal
	CodeUnavailable        = errors.CodeUnavailable
	CodeDataLoss           = errors.CodeDataLoss
	CodeUnauthenticated    = errors.CodeUnauthenticated
)

Codes.

View Source
const SSEResyncEvent = sse.ResyncEvent

SSEResyncEvent is the event type a subscriber receives when updates meant for it are gone (its Last-Event-ID left the history, or the transport lost updates while reconnecting): the client should refetch what it shows.

Variables

This section is empty.

Functions

func Aborted

func Aborted(format string, args ...any) *errors.Error

Aborted creates a 409 error: a concurrency conflict; the client may retry.

func AlreadyExists

func AlreadyExists(format string, args ...any) *errors.Error

AlreadyExists creates a 409 error: the resource already exists.

func Canceled

func Canceled(format string, args ...any) *errors.Error

Canceled creates a 499 error: the client went away.

func ClientIP

func ClientIP(r *http.Request) string

ClientIP returns the address of the client behind the proxies listed in HTTP_TRUSTED_PROXIES; without any, the peer address. Use it for rate limits, audit trails and abuse reports, never r.RemoteAddr or a raw X-Forwarded-For.

func DataLoss

func DataLoss(format string, args ...any) *errors.Error

DataLoss creates a 500 error.

func DeadlineExceeded

func DeadlineExceeded(format string, args ...any) *errors.Error

DeadlineExceeded creates a 504 error.

func Decode

func Decode(r *http.Request, v any) error

Decode reads a strict JSON body into v. Unknown fields, trailing data, empty bodies and bodies over HTTP_MAX_BODY_BYTES are invalid-argument errors ready for Error.

func EncodeCursor

func EncodeCursor(v any) (string, error)

EncodeCursor turns the sort key of the last item of a page into the opaque cursor clients send back as after; Page.Cursor decodes it.

func Error

func Error(w http.ResponseWriter, r *http.Request, err error)

Error renders err as the standard envelope: the app's error mappers are applied, the status comes from the error's code, the request id is stamped, and server-side failures are logged with their cause. Client errors are not logged.

func FailedPrecondition

func FailedPrecondition(format string, args ...any) *errors.Error

FailedPrecondition creates a 400 error: the system is not in the required state.

func HTTPStatus

func HTTPStatus(err error) int

HTTPStatus returns the HTTP status err renders as.

func Internal

func Internal(format string, args ...any) *errors.Error

Internal creates a 500 error with a public-safe message.

func InvalidArgument

func InvalidArgument(format string, args ...any) *errors.Error

InvalidArgument creates a 400 error: the request is malformed or fails validation.

func JSON

func JSON(w http.ResponseWriter, status int, v any) error

JSON writes v as JSON with the given status.

func LoadConfig

func LoadConfig(name string, dst any) error

LoadConfig loads dst (which must embed BaseConfig) from the environment under the service's default prefix, without building an App. Use it when a value in the config decides which options to pass to New, such as a ROLE that selects components. New loads the same struct again; that is cheap and keeps one source of truth.

func MustValue

func MustValue[T any](a *App, key any, accessor, option string) T

MustValue is what feature accessors use: it returns the stored value or panics with the standard message naming the accessor that was called and the option that was missing, for example "gox: postgres.From called but postgres.Enable() was not passed to gox.New".

func NewError

func NewError(code Code, msg string) *errors.Error

NewError creates a coded error with a public-safe message.

func NotFound

func NotFound(format string, args ...any) *errors.Error

NotFound creates a 404 error.

func OutOfRange

func OutOfRange(format string, args ...any) *errors.Error

OutOfRange creates a 400 error.

func PermissionDenied

func PermissionDenied(format string, args ...any) *errors.Error

PermissionDenied creates a 403 error.

func ProblemJSON

func ProblemJSON(w http.ResponseWriter, r *http.Request, status int, env Envelope) bool

ProblemJSON is an ErrorRenderer writing RFC 9457 problem details (application/problem+json): title, status, detail, plus code, request_id and every detail of the error as extension members.

func RequestID

func RequestID(r *http.Request) string

RequestID returns the id of this request: the one echoed in X-Request-ID and stamped on every log line. Use it to correlate rows the handler writes.

func ResourceExhausted

func ResourceExhausted(format string, args ...any) *errors.Error

ResourceExhausted creates a 429 error.

func Unauthenticated

func Unauthenticated(format string, args ...any) *errors.Error

Unauthenticated creates a 401 error.

func Unavailable

func Unavailable(format string, args ...any) *errors.Error

Unavailable creates a 503 error: retry later.

func Unimplemented

func Unimplemented(format string, args ...any) *errors.Error

Unimplemented creates a 501 error.

func Unknown

func Unknown(format string, args ...any) *errors.Error

Unknown creates a 500 error of unknown cause.

func Value

func Value[T any](a *App, key any) (T, bool)

Value is the typed form of App.Value.

func WrapError

func WrapError(cause error, code Code, msg string) *errors.Error

WrapError keeps cause for errors.Is and logs while msg is what clients see.

Types

type App

type App struct {
	// contains filtered or unexported fields
}

App is a built service: config loaded, logger ready, components constructed. Run starts it.

func MustNew

func MustNew(name string, opts ...Option) *App

MustNew is New for main(): --help and --version print and exit 0, any other error prints to stderr and exits 1.

func New

func New(name string, opts ...Option) (*App, error)

New builds an App: it applies the options, loads and validates config in one pass, builds the logger, runs every component factory, and wires the admin server. Nothing is started until Run. On error the returned error names what to fix.

func (*App) Add

func (a *App) Add(cs ...lifecycle.Component)

Add registers user components at StageUser after New and before Run.

func (*App) Config

func (a *App) Config() BaseConfig

Config returns the framework configuration. A service's own fields live in the struct it passed to WithConfig.

func (*App) ConfigPrefix

func (a *App) ConfigPrefix() string

ConfigPrefix returns the environment prefix config was loaded under ("BILLING", or "" for unprefixed), so features can name variables in their own error messages.

func (*App) HTTPClient

func (a *App) HTTPClient() *http.Client

HTTPClient returns the default outbound client. It panics if HTTPClient() was not declared.

func (*App) HandleFunc

func (a *App) HandleFunc(pattern string, h http.HandlerFunc)

HandleFunc registers a handler on the public mux using Go 1.22 patterns such as "GET /invoices/{id}".

func (*App) HasHTTP

func (a *App) HasHTTP() bool

HasHTTP reports whether HTTP() was declared. Feature packages that decorate the public server check it to give a precise error.

func (*App) HasHTTPClient

func (a *App) HasHTTPClient() bool

HasHTTPClient reports whether HTTPClient() was declared.

func (*App) Health

func (a *App) Health() *health.Registry

Health returns the registry behind /healthz and /readyz. Register extra checks on it before Run.

func (*App) Log

func (a *App) Log() *slog.Logger

Log returns the service logger.

func (*App) MapError

func (a *App) MapError(err error) error

MapError applies the registered mappers to err. gox.Error calls it; a service can call it too when rendering errors itself.

func (*App) Mux

func (a *App) Mux() *http.ServeMux

Mux returns the public ServeMux. Register routes on it before Run. It panics if HTTP() was not declared.

func (*App) Name

func (a *App) Name() string

Name returns the service name given to New.

func (*App) Run

func (a *App) Run() error

Run starts the app and blocks until SIGINT or SIGTERM, or until a component fails fatally. It returns nil after a clean shutdown.

func (*App) RunContext

func (a *App) RunContext(ctx context.Context) error

RunContext is Run with a caller-supplied context: cancel it to shut down.

func (*App) SSE added in v0.2.0

func (a *App) SSE() *SSEHub

SSE returns the server-sent events hub. It panics if WithSSE was not passed to HTTP().

func (*App) Value

func (a *App) Value(key any) (any, bool)

Value returns a value stored by a feature package's Enable option.

type BaseConfig

type BaseConfig = config.Base

BaseConfig is the configuration every service has. Embed it in your own config struct and pass that to WithConfig.

type Builder

type Builder struct {
	// contains filtered or unexported fields
}

Builder is the extension API feature packages use inside their Enable() option. Services never touch it directly.

func (*Builder) Component

func (b *Builder) Component(stage Stage, fn func(a *App) (lifecycle.Component, error))

Component registers a factory that runs at the end of New, after config and logging are ready, in stage order. The component it returns is started by Run.

func (*Builder) ConfigSection

func (b *Builder) ConfigSection(name string, dst any, declaredBy string)

ConfigSection registers a feature's config struct. name becomes the env sub-prefix: section "POSTGRES" under service prefix "BILLING" reads BILLING_POSTGRES_*. declaredBy names the option (for --help and errors).

func (*Builder) ErrorRenderer

func (b *Builder) ErrorRenderer(fn httpx.ErrorRenderer)

ErrorRenderer registers a renderer for error responses (an HTML error page). It is installed above the whole chain, so panics, timeouts and unmatched routes reach it too. Renderers are tried in registration order; the first to return true wins, otherwise the JSON envelope is written.

func (*Builder) Finish

func (b *Builder) Finish(fn func(a *App) error)

Finish registers a function that runs at the end of New, after every component factory. It is for features that decorate what another feature built (web mounts onto the mux HTTP() created) without depending on the order options were passed in.

func (*Builder) Middleware

func (b *Builder) Middleware(mw ...Middleware)

Middleware adds middleware a feature package needs on every request. It runs after the default chain and before the auth slot and the service's own WithMiddleware, so auth can rely on what the feature set up (a session, for example).

func (*Builder) Set

func (b *Builder) Set(key, value any)

Set stores a value feature packages expose through their From accessor. Keys are unexported types owned by the feature package.

func (*Builder) Setup

func (b *Builder) Setup(fn func(a *App) error)

Setup registers a function that runs at the end of New, after config and logging are ready and before any component factory. It is for features that produce a value without a lifecycle (a JWT service, a codec); use Component for anything that starts or stops.

type CORSConfig

type CORSConfig = middleware.CORSConfig

CORSConfig configures WithCORS.

type Code

type Code = errors.Code

Code classifies a coded error.

func CodeOf

func CodeOf(err error) Code

CodeOf returns the code of err through wrapping: OK for nil, Unknown for foreign errors.

type Envelope

type Envelope = errors.Envelope

Envelope is the JSON error body every gox response uses.

type ErrorMapper

type ErrorMapper = errors.Mapper

ErrorMapper translates a service's own errors into coded errors at the boundary. See WithErrorMapper.

type ErrorRenderer

type ErrorRenderer = httpx.ErrorRenderer

ErrorRenderer writes an error response in place of the JSON envelope; it returns false to decline a request.

type HTTPOption

type HTTPOption func(*httpOptions)

HTTPOption configures the public HTTP server declared with HTTP().

func WithCORS

func WithCORS(cfg CORSConfig) HTTPOption

WithCORS enables CORS for the given configuration. It is never on by default.

func WithSPA

func WithSPA(cfg SPAConfig) HTTPOption

WithSPA serves a single-page application from the same origin as the API: files from cfg.FS at their paths, index.html for every other GET so client-side routes deep-link, and the error envelope for unmatched requests under cfg.ServerPrefixes. Registered routes always win. With it, a request with the wrong method for a route is a 404, not a 405.

func WithSSE added in v0.2.0

func WithSSE(cfg SSEConfig) HTTPOption

WithSSE serves topic-based server-sent events, in the spirit of Mercure: clients subscribe with GET <Path>?topic=… (an exact topic, a template such as /orders/{id} or /files/{path...}, or *), the service publishes with a.SSE().Publish, and a reconnecting client resumes from Last-Event-ID, or gets an SSEResyncEvent when what it missed is gone. The subscription route is registered with middleware.Streaming, so like any Streaming route it is exempt from HTTP_REQUEST_TIMEOUT and HTTP_WRITE_TIMEOUT; on shutdown every stream ends so the server can drain. It enables a.SSE.

type Middleware

type Middleware = middleware.Middleware

Middleware wraps an http.Handler. Handlers are plain net/http.

func RateLimit

func RateLimit(limit int, window time.Duration) Middleware

RateLimit allows limit requests per window for each client IP and answers the rest with a 429 and Retry-After. Wrap the routes that need it (login, signup, password reset): a.Mux().Handle("POST /login", gox.RateLimit(10, time.Minute)(h)). The count is per process.

type Option

type Option func(*Builder) error

Option declares one thing the app is made of or one behaviour of it.

func Component

func Component(c lifecycle.Component) Option

Component adds any user component at StageUser. It is the escape hatch for things gox has no option for.

func HTTP

func HTTP(opts ...HTTPOption) Option

HTTP declares the public HTTP server: a net/http ServeMux behind the default middleware chain, /healthz and /readyz on the public port, and 404/405 rendered as the error envelope. It enables a.Mux and a.HandleFunc. A route registered with middleware.Streaming is exempt from the request timeout and the server's write deadline, and when shutdown begins its request context is canceled and a write to a stalled client fails, so the server can drain.

Chain: error renderers → route capture → stream shutdown → recovery → request id → client ip → tracing → metrics → logging → timeout → max bytes → security headers → CORS (WithCORS) → cross-origin protection → feature middleware (Builder.Middleware) → auth (WithAuth) → WithMiddleware → mux. Timeouts and the body limit come from HTTP_* config.

func HTTPClient

func HTTPClient() Option

HTTPClient declares the default outbound client: timeouts and pool limits from HTTP_CLIENT_* config, trace and request-id propagation, and "User-Agent: <service>/<version>". It enables a.HTTPClient.

func Periodic

func Periodic(name string, every time.Duration, fn func(context.Context) error) Option

Periodic runs fn every interval as a component: staggered first run, panic recovery, errors logged, stopped with the app.

func WithAuth

func WithAuth(mw Middleware) Option

WithAuth fills the auth slot of the chain: it runs after the default middleware and before WithMiddleware, for every route including the health probes, so an auth middleware should let those through.

func WithConfig

func WithConfig(dst any) Option

WithConfig registers the service's own config struct, which must embed BaseConfig. It is loaded and validated in the same pass as everything else.

func WithConfigPrefix

func WithConfigPrefix(p string) Option

WithConfigPrefix sets the environment prefix. The default is the uppercased service name; "" means unprefixed variables (HTTP_ADDR, ...).

func WithEnvAlias

func WithEnvAlias(name, alias string) Option

WithEnvAlias makes the variable name (without the service prefix, such as "POSTGRES_URL") fall back to another environment variable when it is not set: the name a platform injects ("DATABASE_URL") or one a service already deployed under. The service's own variable always wins.

func WithErrorMapper

func WithErrorMapper(m ErrorMapper) Option

WithErrorMapper registers a mapper applied by gox.Error before rendering, so a service keeps its domain sentinels and maps them once.

func WithErrorRenderer

func WithErrorRenderer(fn ErrorRenderer) Option

WithErrorRenderer replaces the JSON envelope for every error response, from handlers (gox.Error) and from the framework (404, 405, panics, timeouts, body limits) alike. Use it when clients expect another shape: gox.ProblemJSON, or a function that picks a shape by path. Renderers of feature packages, such as gox/web's HTML error pages, still see the request first.

func WithLogger

func WithLogger(l *slog.Logger) Option

WithLogger replaces the logger gox would build from config.

func WithMiddleware

func WithMiddleware(mw ...Middleware) Option

WithMiddleware appends middleware after the default chain (and after the auth slot), outermost first.

func WithShutdownTimeout

func WithShutdownTimeout(d time.Duration) Option

WithShutdownTimeout sets the default per-component stop budget. The SHUTDOWN_TIMEOUT variable still overrides it.

func WithVersion

func WithVersion(v string) Option

WithVersion sets the build version reported in logs and on /version.

func WithoutAdminServer

func WithoutAdminServer() Option

WithoutAdminServer disables the ops server.

type Page

type Page = httpx.Page

Page is a keyset pagination request (?after=<cursor>&limit=<n>).

func ParsePage

func ParsePage(r *http.Request, def, ceiling int) (Page, error)

ParsePage reads after and limit from the query: a missing limit is def, a larger one is capped at ceiling.

type SPAConfig

type SPAConfig = httpserver.SPAConfig

SPAConfig describes a single-page application served next to the API.

type SSEConfig added in v0.2.0

type SSEConfig struct {
	// Path subscribers connect to with GET ?topic=. Default: /events.
	Path string
	// Authorize decides which private updates a subscriber receives: an
	// update with Private set reaches the subscription made by r only if
	// Authorize returns true for one of its topics. It sees the request with
	// everything the chain put there (jwt.ClaimsFromContext, web.SessionFrom);
	// answers are cached per topic for a minute. Without it, private updates
	// reach no one. Who may subscribe at all is the chain's business
	// (WithAuth), checked again on every reconnect (see MaxAge).
	Authorize func(r *http.Request, topic string) bool
	// Transport fans updates out across replicas, built after the
	// datastores so it can use them: pass postgres.SSETransport. Default:
	// none, updates reach only this process's subscribers.
	Transport func(a *App) (SSETransport, error)
	// Heartbeat is the interval of the keep-alive comment that stops
	// proxies closing idle streams. Default: 15s.
	Heartbeat time.Duration
	// WriteTimeout bounds each write to a subscriber; a client that stalls
	// longer is disconnected. Default: 10s.
	WriteTimeout time.Duration
	// MaxAge ends a stream after this long (less up to 10% jitter); the
	// client reconnects with Last-Event-ID through the middleware chain
	// again, so an expired token or a closed session stops the stream.
	// Default: 15m; negative keeps streams open indefinitely.
	MaxAge time.Duration
	// Buffer is the number of updates queued per subscriber; one that falls
	// further behind is disconnected and resumes with Last-Event-ID.
	// Default: 64.
	Buffer int
	// History is the number of recent updates kept in memory for
	// Last-Event-ID replay. Default: 1000; negative disables replay.
	History int
	// MaxTopics caps the topic selectors of one subscription. Default: 32.
	MaxTopics int
	// MaxSubscribers caps the open streams of this process; more are
	// refused with 503 and Retry-After. Default: 10000; negative means no
	// cap.
	MaxSubscribers int
}

SSEConfig configures WithSSE. Zero values take the defaults noted per field.

type SSEHub added in v0.2.0

type SSEHub = sse.Hub

SSEHub fans server-sent events out to subscribers; get it with a.SSE().

type SSETransport added in v0.2.0

type SSETransport = sse.Transport

SSETransport carries published updates to every replica of the service; postgres.SSETransport is one.

type SSEUpdate added in v0.2.0

type SSEUpdate = sse.Update

SSEUpdate is one event published to the subscribers of its topics.

type Stage

type Stage int

Stage orders component start-up. Lower stages start first and stop last. Config, logging and telemetry are not components: they are ready before any factory runs.

const (
	StageDatastore Stage = iota + 10 // databases, caches, message brokers
	StageClient                      // clients of other services
	StageUser                        // the service's own components
	StageServer                      // public listeners

)

Stages. Feature packages pick the one that matches what they provide.

Directories

Path Synopsis
cmd
gox command
Command gox is the framework's CLI.
Command gox is the framework's CLI.
gox/internal/llmdoc
Package llmdoc generates llm.txt: the one file a model needs to build a service on gox.
Package llmdoc generates llm.txt: the one file a model needs to build a service on gox.
gox/internal/scaffold
Package scaffold renders a new service from the embedded template: `gox new <name> [--postgres] [--web]`.
Package scaffold renders a new service from the embedded template: `gox new <name> [--postgres] [--web]`.
gox/internal/scaffold/_template/base/internal/hello
Package hello is the example feature: replace it with your own.
Package hello is the example feature: replace it with your own.
gox/internal/scaffold/_template/postgres/migrations
Package migrations embeds the SQL migration files.
Package migrations embeds the SQL migration files.
gox/internal/scaffold/_template/web/static
Package static embeds the site's assets.
Package static embeds the site's assets.
http module
jobs module
jwt module
logger module
monetary module
openapi module
pkg
admin
Package admin is the ops server every gox service runs on a separate port: /healthz, /readyz, /version and /debug/pprof, plus whatever the root mounts (pkg/otel adds /metrics).
Package admin is the ops server every gox service runs on a separate port: /healthz, /readyz, /version and /debug/pprof, plus whatever the root mounts (pkg/otel adds /metrics).
config
Package config loads and validates a service's configuration in one pass: the framework's Base, the service's own struct (which embeds Base), and every config section a feature package registered, all under one env prefix.
Package config loads and validates a service's configuration in one pass: the framework's Base, the service's own struct (which embeds Base), and every config section a feature package registered, all under one env prefix.
errors
Package errors is the canonical error model for gox services: an error carries a Code (mirroring gRPC status codes), a public-safe message, and optional details, and maps to an HTTP status and a JSON envelope in one documented way.
Package errors is the canonical error model for gox services: an error carries a Code (mirroring gRPC status codes), a public-safe message, and optional details, and maps to an HTTP status and a JSON envelope in one documented way.
health
Package health is a registry of named liveness and readiness checks with JSON handlers for /healthz and /readyz.
Package health is a registry of named liveness and readiness checks with JSON handlers for /healthz and /readyz.
httpclient
Package httpclient builds the outbound http.Client every gox service uses: timeouts and pool limits from config, OpenTelemetry trace propagation, request-id propagation, a service User-Agent, and opt-in retries for idempotent requests.
Package httpclient builds the outbound http.Client every gox service uses: timeouts and pool limits from config, OpenTelemetry trace propagation, request-id propagation, a service User-Agent, and opt-in retries for idempotent requests.
httpserver
Package httpserver is the public HTTP server component: a net/http Server with sane timeouts over a Go 1.22+ ServeMux, health probes on the public port, and 404/405 rendered as the standard error envelope.
Package httpserver is the public HTTP server component: a net/http Server with sane timeouts over a Go 1.22+ ServeMux, health probes on the public port, and 404/405 rendered as the standard error envelope.
httpx
Package httpx holds the three helpers every handler uses (JSON, Error, Decode) and the envelope writer the middleware chain shares with them, so a client sees one error shape whether a handler or the framework produced it.
Package httpx holds the three helpers every handler uses (JSON, Error, Decode) and the envelope writer the middleware chain shares with them, so a client sees one error shape whether a handler or the framework produced it.
i18n
Package i18n translates the strings a server owns: error messages, mail subjects, labels injected into a page.
Package i18n translates the strings a server owns: error messages, mail subjects, labels injected into a page.
lifecycle
Package lifecycle defines the Component contract every gox-managed piece of a service implements, and a Manager that starts components in stage order, stops them in reverse with a per-component budget, and surfaces the first fatal error from any long-running component.
Package lifecycle defines the Component contract every gox-managed piece of a service implements, and a Manager that starts components in stage order, stops them in reverse with a per-component budget, and surfaces the first fatal error from any long-running component.
log
Package log builds the slog.Logger every gox service uses: JSON in production, text in development, and request-scoped fields stamped on every record from the context.
Package log builds the slog.Logger every gox service uses: JSON in production, text in development, and request-scoped fields stamped on every record from the context.
mail
Package mail is the provider-neutral side of sending email: the Message every mail provider accepts (providers/mailgun, providers/resend), a Sender interface, an SMTP sender for development and self-hosted relays, a guard that keeps a staging environment from mailing real people, and a recorder for tests.
Package mail is the provider-neutral side of sending email: the Message every mail provider accepts (providers/mailgun, providers/resend), a Sender interface, an SMTP sender for development and self-hosted relays, a guard that keeps a staging environment from mailing real people, and a recorder for tests.
middleware
Package middleware provides the HTTP middleware every gox service runs and the Chain that orders them.
Package middleware provides the HTTP middleware every gox service runs and the Chain that orders them.
otel
Package otel sets up OpenTelemetry for a service: a tracer provider that exports over OTLP when enabled, a meter provider that always feeds a Prometheus handler for the admin server (and OTLP when enabled), W3C propagation, and a hook that stamps trace and span ids on log records.
Package otel sets up OpenTelemetry for a service: a tracer provider that exports over OTLP when enabled, a meter provider that always feeds a Prometheus handler for the admin server (and OTLP when enabled), W3C propagation, and a hook that stamps trace and span ids on log records.
sse
Package sse is a topic-based server-sent events hub in the spirit of Mercure: clients subscribe with GET ?topic=… (exact topics, {name} segment templates, or *), the service publishes Updates, private updates reach only the subscribers Authorize allows, and a reconnecting client resumes from Last-Event-ID.
Package sse is a topic-based server-sent events hub in the spirit of Mercure: clients subscribe with GET ?topic=… (exact topics, {name} segment templates, or *), the service publishes Updates, private updates reach only the subscribers Authorize allows, and a reconnecting client resumes from Last-Event-ID.
storage
Package storage is the backend-neutral side of object storage: the Bucket interface every storage provider implements (providers/s3), and signed upload tokens for the direct-upload handshake, where a browser uploads straight to the bucket and then tells the service which object it sent.
Package storage is the backend-neutral side of object storage: the Bucket interface every storage provider implements (providers/s3), and signed upload tokens for the direct-upload handshake, where a browser uploads straight to the bucket and then tells the service which object it sent.
storage/storagetest
Package storagetest is an in-memory storage.Bucket for tests.
Package storagetest is an in-memory storage.Bucket for tests.
postgres module
providers
mailgun module
posthog module
resend module
s3 module
stripe module
supabase module
temporal module
workos module
supabase module
web module

Jump to

Keyboard shortcuts

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