bootstrap

package
v3.0.1 Latest Latest
Warning

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

Go to latest
Published: May 19, 2026 License: Apache-2.0 Imports: 33 Imported by: 0

Documentation

Overview

Package bootstrap composes common contrib adapters and core middleware into application profiles.

System endpoints and pprof profiles -----------------------------------

`MountSystemEndpoints` and `MountSystemEndpointsTo` preserve v2 convenience behavior where pprof is disabled unless explicitly enabled. Prefer `MountSystemEndpointsToWithAdmin` for new wiring that includes detailed health, pprof, or metrics so operator-only routes require an explicit authorization or internal-network wrapper.

Development wiring example:

bootstrap.MountSystemEndpointsToWithProfile(router, bootstrap.SystemEndpoints{
	Health:  health.NewHandler(nil),
	Pprof:   pprof.Handler(),
	Version: version.NewHandler(version.Config{}),
}, "development")

Production wiring example:

bootstrap.MountSystemEndpointsToWithProfile(router, bootstrap.SystemEndpoints{
	Health: health.NewHandler(nil),
	Pprof:  pprof.Handler(),
}, "production")

Admin wiring example:

err := bootstrap.MountSystemEndpointsToWithAdmin(router, bootstrap.SystemEndpoints{
	Health:  healthHandler,
	Metrics: bootstrap.PrometheusMetricsHandler(),
	Pprof:   pprof.Handler(),
}, bootstrap.SystemEndpointAdminOptions{
	RequireAdmin: requireAdmin,
	EnablePprof:  true,
})
if err != nil {
	return err
}

In production profiles, pass `bootstrap.SystemEndpointOptions{EnablePprof:true}` when there is an explicit policy decision to expose profiling.

Middleware order ----------------

`ProfileStrictAPI` records its middleware stages in `Profile.MiddlewareOrder`. The default router validates that the production order keeps request IDs, recovery, tracing, secure headers, rate limits, body/query limits, JSON enforcement, timeout, request logging, and metrics in the expected sequence. Services that compose custom routers can use `RequireMiddlewareOrder` as a startup check. SaaS API services that add route-policy middleware outside the transport profile can use `StrictSaaSAPIMiddlewareOrder` to require auth, tenant, and idempotency stages after metrics.

Lifecycle ---------

`APIServiceConfig.StartupChecks` validates wiring before serving traffic. `APIServiceConfig.AdminAddr` starts a separate admin listener; the public handler keeps only public health/docs/version routes while the admin handler serves detailed health, metrics, and pprof behind the configured admin wrapper. `APIServiceConfig.BackgroundTasks` runs named tasks such as health refresh schedulers with the service context; a task error fails the service and triggers graceful shutdown. `APIServiceConfig.ShutdownHooks` releases named resources after the HTTP server exits, using a fresh timeout derived from the Start context with cancellation stripped so shutdown work can complete.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func HardenedServer

func HardenedServer(addr string, handler http.Handler, opts ...ServerOption) *http.Server

HardenedServer builds an http.Server with safe defaults and optional overrides.

func MountSystemEndpoints

func MountSystemEndpoints(r ports.HTTPRouter, se SystemEndpoints)

MountSystemEndpoints registers health, docs, version, and metrics endpoints. It preserves v2 convenience behavior; prefer MountSystemEndpointsToWithAdmin when mounting metrics, pprof, or detailed health from new wiring.

func MountSystemEndpointsTo

func MountSystemEndpointsTo(r ports.MethodRouteRegistrar, se SystemEndpoints)

MountSystemEndpointsTo registers system endpoints on a minimal GET-only surface. It preserves v2 convenience behavior; prefer MountSystemEndpointsToWithAdmin when mounting metrics, pprof, or detailed health from new wiring.

func MountSystemEndpointsToWithAdmin

func MountSystemEndpointsToWithAdmin(r ports.MethodRouteRegistrar, se SystemEndpoints, opts SystemEndpointAdminOptions) error

MountSystemEndpointsToWithAdmin mounts public health, docs, and version routes normally while mounting operator-only detailed health, metrics, and optional pprof routes behind an explicit authorization or internal-network wrapper.

func MountSystemEndpointsToWithOptions

func MountSystemEndpointsToWithOptions(r ports.MethodRouteRegistrar, se SystemEndpoints, opts SystemEndpointOptions)

MountSystemEndpointsToWithOptions mounts system endpoints with explicit runtime options. It preserves v2 convenience behavior; prefer MountSystemEndpointsToWithAdmin when mounting metrics, pprof, or detailed health from new wiring.

func MountSystemEndpointsToWithProfile

func MountSystemEndpointsToWithProfile(r ports.MethodRouteRegistrar, se SystemEndpoints, profile string)

MountSystemEndpointsToWithProfile mounts system endpoints only if the profile explicitly opts pprof in. This keeps production/staging defaults off by default.

func NewDefaultRouter

func NewDefaultRouter(log ports.Logger) (ports.HTTPRouter, error)

NewDefaultRouter constructs a router with a sensible default middleware stack.

func NewDefaultRouterWithConfig

func NewDefaultRouterWithConfig(log ports.Logger, cfg DefaultRouterConfig) (ports.HTTPRouter, error)

NewDefaultRouterWithConfig constructs a router from explicit configuration.

func NewMigrator

func NewMigrator(dsn, table string, lockKey int64, allowDown bool, log ports.Logger, dirs []string, embedded []fs.FS) (ports.Migrator, error)

NewMigrator builds a migrator with either directories or embedded FS sources.

func NewMigratorWithContext

func NewMigratorWithContext(ctx context.Context, dsn, table string, lockKey int64, allowDown bool, log ports.Logger, dirs []string, embedded []fs.FS) (ports.Migrator, error)

NewMigratorWithContext builds a migrator with either directories or embedded FS sources.

func OpenAndPingDB

func OpenAndPingDB(ctx context.Context, dsn string, timeout time.Duration) (ports.DatabasePool, error)

OpenAndPingDB opens a DB pool and verifies connectivity with a short timeout.

func OpenPoolOrExit

func OpenPoolOrExit(ctx context.Context, dsn string, timeout time.Duration, log ports.Logger) ports.DatabasePool

OpenPoolOrExit opens a DB pool and terminates the process if it fails.

func PrometheusMetricsHandler

func PrometheusMetricsHandler() http.Handler

PrometheusMetricsHandler returns the standard Prometheus metrics handler for explicit mounting on specs.Metrics.

func RunDown

func RunDown(ctx context.Context, m ports.Migrator, dir string) error

RunDown runs migrations down with context and directory path.

func RunMigrations

func RunMigrations(ctx context.Context, cfg config.Config, log ports.Logger, embedded []fs.FS) (err error)

RunMigrations runs startup migrations using config defaults and returns errors to the caller. Reusable library code should prefer this function.

func RunMigrationsOrExit

func RunMigrationsOrExit(ctx context.Context, cfg config.Config, log ports.Logger, embedded []fs.FS)

RunMigrationsOrExit runs startup migrations using config defaults or exits on failure. This helper is intended for binaries; reusable library code should prefer RunMigrations.

func RunUp

func RunUp(ctx context.Context, m ports.Migrator, dir string) error

RunUp runs migrations up with context and directory path.

func StartServer

func StartServer(
	ctx context.Context,
	addr string,
	handler http.Handler,
	log ports.Logger,
) error

StartServer runs an HTTP server and performs graceful shutdown when the context is canceled.

func StartServerOrExit

func StartServerOrExit(
	ctx context.Context,
	addr string,
	handler http.Handler,
	log ports.Logger,
)

StartServerOrExit runs the HTTP server and exits the process when it fails.

func Status

func Status(ctx context.Context, m ports.Migrator, dir string) (string, error)

Status returns a text status of migrations.

func ValidateMiddlewareOrder

func ValidateMiddlewareOrder(order []MiddlewareStage, required ...MiddlewareStage) error

ValidateMiddlewareOrder verifies that the required stages appear in the given order. The check allows extra stages between required stages so applications can add route- or deployment-specific middleware without losing the baseline production ordering contract.

func WithTimeout

func WithTimeout(parent context.Context, d time.Duration) (context.Context, context.CancelFunc)

WithTimeout derives a context with a default timeout for long-running migration ops.

Types

type APIService

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

APIService is a reusable HTTP API composition root for generated services.

func NewAPIService

func NewAPIService(config APIServiceConfig) (*APIService, error)

NewAPIService validates wiring, builds default router/profile when needed, mounts routes and system endpoints, and returns a runnable service.

func (*APIService) AdminHandler

func (s *APIService) AdminHandler() http.Handler

AdminHandler returns the composed admin HTTP handler when AdminAddr is configured.

func (*APIService) Handler

func (s *APIService) Handler() http.Handler

Handler returns the composed HTTP handler.

func (*APIService) Start

func (s *APIService) Start(ctx context.Context) error

Start starts the HTTP server and shuts down when ctx is canceled.

type APIServiceConfig

type APIServiceConfig struct {
	Addr                    string
	AdminAddr               string
	Log                     ports.Logger
	Router                  ports.HTTPRouter
	AdminRouter             ports.HTTPRouter
	RegisterRoutes          func(ports.HTTPRouter) error
	SystemEndpoints         SystemEndpoints
	Admin                   SystemEndpointAdminOptions
	MiddlewareOrder         []MiddlewareStage
	RequiredMiddlewareOrder []MiddlewareStage
	ServerOptions           []ServerOption
	StartupChecks           []StartupCheck
	ShutdownHooks           []ShutdownHook
	BackgroundTasks         []BackgroundTask
}

APIServiceConfig configures a reusable production API composition root.

type BackgroundTask

type BackgroundTask struct {
	Name string
	Run  func(context.Context) error
}

BackgroundTask runs with the API service lifecycle. Returning a non-context cancellation error fails the service and starts graceful shutdown.

type DefaultRouterConfig

type DefaultRouterConfig struct {
	RateLimit      rateln.Options
	TrustedProxies []netip.Prefix
	Metrics        metricsmw.MetricsRecorder
}

DefaultRouterConfig defines the inputs used by NewDefaultRouterWithConfig.

func DefaultRouterConfigFromEnv

func DefaultRouterConfigFromEnv(env ports.EnvVar) (DefaultRouterConfig, error)

DefaultRouterConfigFromEnv loads router defaults from environment variables.

type MiddlewareStage

type MiddlewareStage string

MiddlewareStage names a middleware responsibility in a bootstrap profile.

const (
	MiddlewareRequestID      MiddlewareStage = "request_id"
	MiddlewareRecovery       MiddlewareStage = "recovery"
	MiddlewareTracing        MiddlewareStage = "tracing"
	MiddlewareCORS           MiddlewareStage = "cors"
	MiddlewareSecureHeaders  MiddlewareStage = "secure_headers"
	MiddlewareRateLimit      MiddlewareStage = "rate_limit"
	MiddlewareBodyLimit      MiddlewareStage = "body_limit"
	MiddlewareQueryLimit     MiddlewareStage = "query_limit"
	MiddlewareJSON           MiddlewareStage = "json"
	MiddlewareTimeout        MiddlewareStage = "timeout"
	MiddlewareRequestLogging MiddlewareStage = "request_logging"
	MiddlewareMetrics        MiddlewareStage = "metrics"
	MiddlewareAuth           MiddlewareStage = "auth"
	MiddlewareTenant         MiddlewareStage = "tenant"
	MiddlewareIdempotency    MiddlewareStage = "idempotency"
)

func DevMiddlewareOrder

func DevMiddlewareOrder() []MiddlewareStage

DevMiddlewareOrder returns the development profile middleware sequence.

func StrictAPIMiddlewareOrder

func StrictAPIMiddlewareOrder() []MiddlewareStage

StrictAPIMiddlewareOrder returns the required production API middleware sequence. Extra stages such as CORS may appear between these stages.

func StrictSaaSAPIMiddlewareOrder

func StrictSaaSAPIMiddlewareOrder() []MiddlewareStage

StrictSaaSAPIMiddlewareOrder returns the production SaaS API middleware sequence, including route-policy stages commonly applied outside the transport profile.

type Profile

type Profile struct {
	Middlewares     []func(http.Handler) http.Handler
	MiddlewareOrder []MiddlewareStage
	ServerOptions   []ServerOption
}

Profile describes a middleware stack and server options.

func ProfileDev

func ProfileDev(log ports.Logger, opts ...ProfileOption) (Profile, error)

ProfileDev builds a developer-friendly profile with relaxed protections.

func ProfileStrictAPI

func ProfileStrictAPI(log ports.Logger, opts ...ProfileOption) (Profile, error)

ProfileStrictAPI builds a hardened API profile.

func (Profile) Apply

func (p Profile) Apply(r ports.HTTPRouter)

Apply attaches the profile middlewares to the router.

func (Profile) ApplyTo

func (p Profile) ApplyTo(r ports.MiddlewareChain)

ApplyTo attaches the profile middlewares to a minimal middleware chain.

type ProfileOption

type ProfileOption func(*profileConfig)

ProfileOption customizes profile defaults.

func WithCORSOptions

func WithCORSOptions(opts ports.CORSOptions) ProfileOption

WithCORSOptions overrides CORS options.

func WithIdentityResolver

func WithIdentityResolver(resolver identity.Resolver) ProfileOption

WithIdentityResolver sets the trusted proxy resolver used by middleware.

func WithJSONStrict

func WithJSONStrict(strict bool) ProfileOption

WithJSONStrict toggles strict JSON parsing.

func WithMaxBodyBytes

func WithMaxBodyBytes(n int64) ProfileOption

WithMaxBodyBytes overrides max request body size.

func WithMetricsRecorder

func WithMetricsRecorder(rec metricsmw.MetricsRecorder) ProfileOption

WithMetricsRecorder sets the metrics recorder.

func WithOTelOptions

func WithOTelOptions(opts oteltrace.Options) ProfileOption

WithOTelOptions overrides OpenTelemetry middleware options.

func WithQueryLimitsDisabled

func WithQueryLimitsDisabled() ProfileOption

WithQueryLimitsDisabled disables query parameter guardrails.

func WithQueryLimitsOptions

func WithQueryLimitsOptions(opts querylimits.Options) ProfileOption

WithQueryLimitsOptions overrides query parameter limits.

func WithRateLimitDisabled

func WithRateLimitDisabled() ProfileOption

WithRateLimitDisabled disables rate limiting.

func WithRateLimitOptions

func WithRateLimitOptions(opts rateln.Options) ProfileOption

WithRateLimitOptions overrides rate limiting settings.

func WithRequestLogOptions

func WithRequestLogOptions(opts ...requestlog.Option) ProfileOption

WithRequestLogOptions appends request log options.

func WithRequestTimeout

func WithRequestTimeout(d time.Duration) ProfileOption

WithRequestTimeout overrides per-request timeout.

func WithSecureOptions

func WithSecureOptions(opts ...securemw.Option) ProfileOption

WithSecureOptions appends secure middleware options.

type ServerOption

type ServerOption func(*http.Server)

ServerOption configures an http.Server instance.

func WithIdleTimeout

func WithIdleTimeout(d time.Duration) ServerOption

WithIdleTimeout overrides IdleTimeout.

func WithMaxHeaderBytes

func WithMaxHeaderBytes(n int) ServerOption

WithMaxHeaderBytes overrides MaxHeaderBytes.

func WithReadHeaderTimeout

func WithReadHeaderTimeout(d time.Duration) ServerOption

WithReadHeaderTimeout overrides ReadHeaderTimeout.

func WithReadTimeout

func WithReadTimeout(d time.Duration) ServerOption

WithReadTimeout overrides ReadTimeout.

func WithWriteTimeout

func WithWriteTimeout(d time.Duration) ServerOption

WithWriteTimeout overrides WriteTimeout.

type ShutdownHook

type ShutdownHook struct {
	Name string
	Hook func(context.Context) error
}

ShutdownHook releases resources when APIService.Start returns after a graceful shutdown or server failure.

type StartupCheck

type StartupCheck struct {
	Name  string
	Check func(context.Context) error
}

StartupCheck validates application wiring before the service starts.

func RequireMiddlewareOrder

func RequireMiddlewareOrder(name string, order []MiddlewareStage, required ...MiddlewareStage) StartupCheck

RequireMiddlewareOrder builds a startup check for applications that compose custom routers or route-level middleware outside the default bootstrap profile.

type SystemEndpointAdminOptions

type SystemEndpointAdminOptions struct {
	RequireAdmin func(http.Handler) http.Handler
	EnablePprof  bool
}

SystemEndpointAdminOptions configures safe admin mounting for operator-only system endpoints.

type SystemEndpointOptions

type SystemEndpointOptions struct {
	EnablePprof bool
}

type SystemEndpointProfile

type SystemEndpointProfile string
const (
	SystemProfileProduction  SystemEndpointProfile = "production"
	SystemProfileStaging     SystemEndpointProfile = "staging"
	SystemProfileDevelopment SystemEndpointProfile = "development"
	SystemProfileTest        SystemEndpointProfile = "test"
)

type SystemEndpoints

type SystemEndpoints struct {
	Health  *health.Handler
	Docs    *docs.Handler
	Version *version.Handler
	Pprof   http.Handler
	Metrics http.Handler
}

SystemEndpoints bundles handlers/config for mounting.

Jump to

Keyboard shortcuts

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