credo

package module
v0.22.0 Latest Latest
Warning

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

Go to latest
Published: Oct 6, 2026 License: MIT Imports: 57 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

Credo

An all-in-one Go web framework for modern, enterprise-grade applications.

Go Version License Go Report Card GoDoc

Status: Beta -- Core APIs are stable enough for real application development. Breaking changes may still happen before v1, but should be documented with migration notes. Feedback from active pilot projects continues to shape the framework.

What Credo Optimizes For

  • All-in-one: router, DI, config, validation, observability, data access -- one cohesive framework.
  • Enterprise defaults: Clean Architecture is the recommended path (documented and supported by the DI design), but not enforced.
  • Errors are values: handlers return error; centralized classification renders a small success:false JSON envelope, with RFC 9457 available as an opt-in renderer.
  • Typed config snapshot: config is loaded once at startup and injected as typed structs via DI; SIGHUP/app.Reload re-reads it and notifies typed per-section subscribers, with file-based TLS certificates rotating on every reload.
  • Integrated-first, explicit boundaries: framework infrastructure is wired by convention; app deps and typed config stay visible and override-friendly.
  • stdlib boundary compatibility: *credo.App is an http.Handler; stdlib middleware can be adapted.

Why Credo Exists

Go teams often assemble production web applications from many excellent but separate libraries: routing, configuration, dependency injection, validation, observability, data access, workers, and middleware. Credo packages those concerns into one integrated framework so teams can spend less time maintaining glue code and more time building application logic.

The project is early but actively maintained, with a focus on clear APIs, documented architecture decisions, security-conscious upstream adaptation, and production-oriented defaults for modern Go services.

Maturity by Area

Credo is Beta overall. Shipped packages are usable for real development; the table below is explicit about what has shipped and what is still on the roadmap. Planned areas exist only as roadmap entries in TODO.md; the module contains no placeholder directories, so nothing is importable before real code lands. Every importable package repeats its label as a machine-readable Maturity: <label> line at the end of its package documentation (go doc <pkg>), and maturity_test.go checks that those lines agree with this table.

Area Status
Routing, Context, Handlers, Middleware Beta
Dependency Injection (Provide/Resolve, Infra) Beta
Configuration (config, typed snapshot) Beta
Validation Beta
Authentication (JWT / Basic / API key) Beta
Internationalization (i18n) Beta
Health checks Beta
Data access — contracts (store) Beta
Data access — Bun SQL wrapper + migrations (store/sqldb) Beta
Background workers + cron (worker) Beta
Pagination Beta
Outbound HTTP client (httpclient) Beta
Server WebSocket adapter (websocket) Beta
Observability — structured logging (slog via Infra) Beta
Observability — tracing (OpenTelemetry) Planned
Observability — metrics (Prometheus) Planned
pubsub (incl. in-process events) · grpc · openapi · admin server · CLI Planned

Accepted Pre-v1 Changes

Bootstrap/DI (DI minor), router parameter-name (router minor), built-in HTTP feature (HTTP minor) and URL round-trip (wire minor) changes implemented 2026-09-05. All contracts are recorded in the migration guide and the ADRs and specs it links; progress lives in TODO.md. The quick start and examples below use the shipped APIs, and the example migration notes explain what changed in them.

Installation

go get github.com/credo-go/credo@latest

Requires Go 1.27+. Credo tracks the current Go release to build on the modern standard library (e.g. os.Root, structured log/slog) and language features — the 1.27 floor is driven by generic methods (app.Provide[T], q.Page[T], ctx.GetUser[T]). It targets new and actively-maintained services rather than legacy codebases pinned to older toolchains — enterprise-grade in capability, modern in its baseline.

Quick Start

package main

import (
    "log"

    "github.com/credo-go/credo"
)

func main() {
    // Create the app (auto-loads config from files, .env, and env vars).
    app, err := credo.New()
    if err != nil {
        log.Fatal(err)
    }

    app.GET("/", func(ctx *credo.Context) error {
        return ctx.Response().JSON(200, map[string]string{"message": "Hello, Credo!"})
    })

    // RFC 10008 QUERY carries a structured, safe/idempotent query in the body.
    // Clients must label it with Content-Type (for example application/json).
    app.QUERY("/search", func(ctx *credo.Context) error {
        var query struct {
            Term string `json:"term"`
        }
        if err := ctx.Request().BindBody(&query); err != nil {
            return err
        }
        return ctx.Response().JSON(200, query)
    })

    // Panic recovery is on by default. Request IDs and access logging are
    // explicit features: app.UseRequestID() and app.UseAccessLog(cfg...),
    // where AccessLogConfig carries the Skipper, MinLevel and ResultFilter.
    // Silence a route/group with the MetaAccessLog route meta; health probes
    // are silent by default.

    // Server settings come from framework-internal server config.
    // Example: set `CREDO_SERVER__PORT=8080`.
    //
    // Run blocks until SIGINT/SIGTERM, then drains in-flight requests
    // gracefully. For caller-driven cancellation (tests, custom signals),
    // use app.RunContext(ctx) instead.
    //
    // For HTTPS, configure TLS at construction — credo.WithTLSFiles(cert, key)
    // or credo.WithTLSConfig(cfg) (or the server.tls.* config keys) — and Run
    // serves TLS automatically; there is no separate RunTLS. Add
    // credo.WithHTTPRedirect(":80") to redirect plaintext HTTP to HTTPS.
    if err := app.Run(); err != nil {
        log.Fatal(err)
    }
}

For explicit config control, load it first with config.Load(...) and pass it to credo.New(credo.WithRawConfig(raw)); this bypasses the default auto-load.

Copyable YAML/JSON configuration and English/Turkish locale catalogs live in examples/references. Runnable applications remain separate under examples/hello and examples/saas.

Config: Typed Snapshot (Anti-Pattern-Free)

Credo positions config as a startup-time snapshot, not a runtime service. String keys should appear only at module boundaries; everything beyond that boundary is typed.

type DatabaseConfig struct {
    DSN string
}

func SetupDatabase(app *credo.App, rawCfg credo.RawConfig) error {
    var cfg DatabaseConfig
    if err := rawCfg.Unmarshal("databases.default", &cfg); err != nil {
        return err
    }
    return app.ProvideValue(&cfg)
}

Field names map to snake_case config keys automatically, so struct tags are optional — add a credo:"..." tag only when the key differs from the field's snake_case name.

Dependency Injection

Credo uses generics-based DI. Cross-cutting infrastructure is carried explicitly via credo.Infra; business dependencies (including typed config) are normal constructor parameters. Single-interface wiring uses Alias[I, T], and ordered interface collections use BindMany[I, T] + ResolveAll[I] or []I constructor injection.

func NewOrderService(infra credo.Infra, cfg *OrderConfig, repo OrderRepo) *OrderService {
    infra.Logger.Info("order service initialized")
    return &OrderService{cfg: cfg, repo: repo}
}

Documentation

  • User guide: docs/guides/getting-started.md
  • User guide: docs/guides/routing.md
  • User guide: docs/guides/middleware.md
  • User guide: docs/guides/error-handling.md
  • User guide: docs/guides/proxy-trust.md
  • User guide: docs/guides/dependency-injection.md
  • User guide: docs/guides/data-access.md
  • User guide: docs/guides/configuration.md
  • User guide: docs/guides/deployment.md
  • User guide: docs/guides/localization.md
  • User guide: docs/guides/static-files.md
  • User guide: docs/guides/worker.md
  • User guide: docs/guides/websocket.md
  • Architecture decisions: docs/adr/
  • Detailed specs: docs/specs/

Repository Layout (High Level)

  • Root package (github.com/credo-go/credo): App, Context, routing, handler/middleware types
  • config/: config loading; config.Load returns *config.Config (satisfies credo.RawConfig), with typed Get[T] access
  • middleware/, validation/, auth/, store/, ...: feature packages
  • internal/: private implementations (router radix tree, DI internals, etc.)
  • docs/: ADRs (docs/adr/) and detailed specs (docs/specs/)

Contributing

See CONTRIBUTING.md for guidelines on how to contribute.

Security

See SECURITY.md for vulnerability reporting instructions, and SECURITY-UPSTREAMS.md for how Credo tracks the upstream projects its adapted code derives from. Reports are triaged by severity on a best-effort basis — there is no fixed response-time guarantee.

License

MIT -- see LICENSE for details.

Documentation

Overview

Package credo is a batteries-included Go web framework that combines the best patterns from Chi (router), Echo (context), Goyave (architecture & components), and GoFr (enterprise toolkit).

It targets Go 1.27+ and leverages generics for type-safe dependency injection without reflection.

Quick Start

package main

import (
	"log"

	"github.com/credo-go/credo"
)

func main() {
    app, err := credo.New()
    if err != nil {
        panic(err)
    }

    app.GET("/", func(ctx *credo.Context) error {
        return ctx.Response().JSON(200, map[string]string{"message": "Hello, Credo!"})
    })

    if err := app.Run(); err != nil {
        log.Fatal(err)
    }
}

Key Concepts

  • Handler: func(*credo.Context) error — all handlers return errors
  • Context: request-scoped struct with Request/Response accessors
  • Middleware: func(credo.Handler) credo.Handler — wraps Handlers. Three tiers run in order: global → group → route. Group middleware is collected from the group parent chain when the app compiles, so registration order affects execution order only — middleware added to a group after its routes still applies to them. Panic recovery, request IDs, access logging, compression, decompression and locale detection are framework features that wrap the whole chain, not middleware.
  • Route: fluent API with Name(), SetMeta(), Middleware()
  • QUERY: first-class RFC 10008 routes via App.QUERY/Group.QUERY; request content requires Content-Type and is commonly decoded with BindBody
  • ErrorRenderer: receives normalized *ErrorInfo and shapes error response bodies via App.UseErrorRenderer — returns the body (nil = default Credo envelope); classification, localization, logging, status, and writing handled by framework; RFC 9457 is an opt-in renderer
  • SuccessRenderer: opt-in uniform success envelope via App.UseSuccessRenderer, applied only at the Context.Render seam (raw Response helpers stay un-enveloped) — shape-only like ErrorRenderer: returns the body for a RenderInfo, the framework writes it

API Naming

Credo uses a consistent verb convention so a method's name signals when and how it runs:

Panic recovery is on by default; request IDs, access logging, response compression and request decompression are explicit (App.UseRequestID, App.UseAccessLog, App.UseCompress, App.UseDecompress). With access logging installed, silence individual routes or whole groups with the MetaAccessLog route meta, noisy paths with AccessLogConfig.Skipper, or result classes with AccessLogConfig.MinLevel and AccessLogConfig.ResultFilter; health probes are silent by default (HealthConfig.LogRequests re-enables them).

Panics and Errors

Credo separates developer errors from runtime failures:

  • Startup configuration (registering routes, hosts, middleware, names, static files, health checks) panics on misuse — nil handlers, malformed patterns, duplicates, or registration after the handler chain has compiled. The route table is code written by the developer, so a mistake there is a bug best caught at startup, not a condition to handle.
  • Anything that can legitimately fail at runtime — request handling, server lifecycle, or operations touching the outside world (file I/O, network) — returns an error.

This is why App.UseHealth panics on misuse (it only registers in-process state) while App.UseI18n returns an error (it loads locale files). The same split applies to reload: registering App.OnConfigChange on a store that cannot reload panics, while App.Reload itself — which re-reads files and runs user hooks — returns an error.

The split is drawn by cause, not by execution phase: a developer invariant violation panics even when the offending call happens to run during a request. NewHTTPError with an out-of-domain status or a malformed machine code is a bug in a constant, not a runtime condition — it panics on first execution, and built-in recovery renders a generic 500 that never publishes the invalid value. Request-derived text must map onto predeclared codes; it is never passed through as a wire identity.

Stability

Credo is Beta: shipped packages are usable for real development, with breaking changes possible before v1. See the project README's "Maturity by Area" table for per-area status, including which features are experimental or still planned.

Maturity: beta

Index

Constants

View Source
const (
	// DIPanicConstruction: a constructor panicked while building a singleton.
	DIPanicConstruction = di.PhaseConstruction
	// DIPanicShutdown: a Shutdowner panicked during the dependency-ordered
	// shutdown pass.
	DIPanicShutdown = di.PhaseShutdown
	// DIPanicLateCleanup: a Shutdowner panicked during the best-effort cleanup
	// of an instance constructed after the shutdown context ended.
	DIPanicLateCleanup = di.PhaseLateCleanup
)
View Source
const (
	// DIShutdownRetired: no Shutdown method; released after its dependents.
	DIShutdownRetired = di.ShutdownRetired
	// DIShutdownSucceeded: Shutdown returned nil.
	DIShutdownSucceeded = di.ShutdownSucceeded
	// DIShutdownFailed: Shutdown returned an error.
	DIShutdownFailed = di.ShutdownFailed
	// DIShutdownPanicked: Shutdown panicked; Err is a *DIPanicError.
	DIShutdownPanicked = di.ShutdownPanicked
	// DIShutdownRunning: Shutdown was started but had not returned when the
	// shutdown context ended; its dependencies stayed blocked.
	DIShutdownRunning = di.ShutdownRunning
	// DIShutdownConstructing: the constructor was still running at the
	// boundary.
	DIShutdownConstructing = di.ShutdownConstructing
	// DIShutdownBlocked: live dependents never retired.
	DIShutdownBlocked = di.ShutdownBlocked
	// DIShutdownUnattempted: ready, but the context ended before its turn.
	DIShutdownUnattempted = di.ShutdownUnattempted
	// DIShutdownNeverConstructed: the constructor never ran.
	DIShutdownNeverConstructed = di.ShutdownNeverConstructed
	// DIShutdownConstructionFailed: the constructor failed earlier.
	DIShutdownConstructionFailed = di.ShutdownConstructionFailed
	// DIShutdownLateCleanup: constructed after the shutdown context ended and
	// handed to the separate best-effort cleanup attempt.
	DIShutdownLateCleanup = di.ShutdownLateCleanup
)
View Source
const (
	MsgKeyBadRequest          = "bad_request"
	MsgKeyUnauthorized        = "unauthorized"
	MsgKeyForbidden           = "forbidden"
	MsgKeyNotFound            = "not_found"
	MsgKeyMethodNotAllowed    = "method_not_allowed"
	MsgKeyConflict            = "conflict"
	MsgKeyUnprocessableEntity = "unprocessable_entity"
	MsgKeyUnsupportedMedia    = "unsupported_media_type"
	MsgKeyInternalError       = "internal_server_error"
	MsgKeyTooManyRequests     = "too_many_requests"
	MsgKeyServiceUnavailable  = "service_unavailable"
	MsgKeyGatewayTimeout      = "gateway_timeout"
	MsgKeyRequestTimeout      = "request_timeout"
	MsgKeyValidationFailed    = "validation_failed"
	MsgKeyBindFailed          = "bind_failed"
)

MsgKey constants define Credo's bare default message keys for standard HTTP errors. Applications may map them into their own namespaces with I18nConfig.ResolveMessageKey.

View Source
const (
	// CodeUnsupportedContentEncoding is the 415 code for a request body whose
	// Content-Encoding the decompression feature ([App.UseDecompress]) has
	// not unwrapped.
	CodeUnsupportedContentEncoding = "unsupported_content_encoding"

	// CodeInvalidBindTarget is the 500 code for a nil or non-pointer bind
	// target — a developer error, reported without client-facing detail.
	CodeInvalidBindTarget = "invalid_bind_target"
)

Framework error codes carried on the wire in addition to the status-derived defaults (see errorcode.go).

View Source
const DefaultDecompressMaxBytes int64 = 4 << 20

DefaultDecompressMaxBytes bounds the decompressed request body when DecompressConfig.MaxBytes is zero. It equals the server's default max_body_bytes (4 MiB); that server limit only bounds the compressed wire bytes, so the decompressed stream needs its own ceiling.

MetaAccessLog is the route-meta key that toggles built-in access logging for a route — or, via LookupMeta parent-chain inheritance, for a whole group. Set it to false to silence the access-log line for matched requests:

app.Group("/internal").SetMeta(credo.MetaAccessLog, false)
app.GET("/metrics", h).SetMeta(credo.MetaAccessLog, false)

A route-level value overrides a group-level one (LookupMeta reads the route before its parents), so a noisy group can be silenced while one route inside it stays logged. Only a bool false silences; any non-bool value is ignored and the request is logged (fail-open). Keys under the "credo." namespace are reserved by the framework.

Health probes use it internally; see HealthConfig.LogRequests.

View Source
const MetaRawResponse = "credo.rawresponse"

MetaRawResponse is the route-meta key that silences the debug-mode envelope-bypass diagnostic for routes that intentionally write raw JSON outside Context.Render — webhooks, third-party-dictated shapes, and other deliberate raw endpoints:

app.POST("/webhooks/stripe", h).SetMeta(credo.MetaRawResponse, true)
app.Group("/callbacks").SetMeta(credo.MetaRawResponse, true)

Groups pass the value to their routes through the usual meta parent chain; a route-level value overrides its group. Only the bool true silences.

The diagnostic itself is opt-in twice over: it fires only when a SuccessRenderer is installed AND the application runs in debug mode (WithDebug / server.debug). It flags handlers that wrote a body-carrying JSON response through the raw Response.JSON helper, silently skipping the application's envelope — a leak that is legal by design (the raw helpers are the documented escape hatch) but usually unintentional when a house envelope exists. Non-JSON writers (Text, Blob, XML, streaming) are exempt by design: they are never envelope targets.

Variables

View Source
var (
	ErrNotFound             = NewHTTPError(http.StatusNotFound)
	ErrMethodNotAllowed     = NewHTTPError(http.StatusMethodNotAllowed)
	ErrBadRequest           = NewHTTPError(http.StatusBadRequest)
	ErrUnauthorized         = NewHTTPError(http.StatusUnauthorized)
	ErrForbidden            = NewHTTPError(http.StatusForbidden)
	ErrInternalServerError  = NewHTTPError(http.StatusInternalServerError)
	ErrConflict             = NewHTTPError(http.StatusConflict)
	ErrUnprocessableEntity  = NewHTTPError(http.StatusUnprocessableEntity)
	ErrUnsupportedMediaType = NewHTTPError(http.StatusUnsupportedMediaType)
)

Sentinel errors for common HTTP error conditions.

These are shared package-level instances, like io.EOF: compare with errors.Is and treat them as immutable. Mutating a sentinel's fields would silently change the behavior of every handler in the process. To attach context, derive a copy instead — HTTPError.WithInternal for a wrapped cause, or NewHTTPError for a different status or message key.

View Source
var ErrDIClosed = di.ErrClosed

ErrDIClosed is the sentinel wrapped by every App.Resolve rejected because DI teardown has begun or completed. Compare with errors.Is. It applies from the moment the container enters its closing phase (the DI teardown stage of App.Shutdown, after the HTTP and OnDrain phases) and takes precedence over a failed Finalize.

View Source
var ErrUserMissing = errors.New("credo: no user in context (or type mismatch)")

ErrUserMissing is returned by Context.RequireUser when no authenticated user of the requested type is present on the request. RequireUser wraps it inside ErrUnauthorized, so a handler that returns the error renders a 401 while errors.Is(err, ErrUserMissing) still reports the underlying cause.

Functions

func DirFS

func DirFS(dir string) (fs.FS, io.Closer, error)

DirFS returns a traversal-safe fs.FS rooted at dir, together with an io.Closer that releases the underlying directory handle.

Unlike os.DirFS, it is backed by os.Root, so symlinks that resolve outside dir are refused — closing a common path-traversal hole when serving files from disk. Prefer it over os.DirFS for disk-backed static serving.

The FS holds an open directory handle until the closer is called. Register the closer for graceful shutdown so the handle is released cleanly:

fsys, closer, err := credo.DirFS("./public")
if err != nil {
	return err
}
app.Static("/assets", fsys)
app.OnShutdown(func(context.Context) error { return closer.Close() })

It returns an error if dir cannot be opened.

func StaticCacheImmutableAssets

func StaticCacheImmutableAssets(maxAge time.Duration) func(StaticCacheContext) string

StaticCacheImmutableAssets returns a StaticConfig.CacheControl hook for content-hashed builds: non-HTML assets get "public, max-age=N, immutable", while HTML responses (index files, SPA fallbacks, prerendered pages, and directory listings) get "no-cache, must-revalidate" so entry points stay refreshable. Panics if maxAge is negative or floors below 1 second.

func StaticCacheMaxAge

func StaticCacheMaxAge(maxAge time.Duration) func(StaticCacheContext) string

StaticCacheMaxAge returns a StaticConfig.CacheControl hook that serves every successful response with "public, max-age=N". Sub-second durations are floored to whole seconds; if the floored result is 0 the hook writes no header. Panics if maxAge is negative.

func URLParam

func URLParam(r *http.Request, name string) string

URLParam returns the named URL parameter of r: the value in the request's RouteContext when it carries one, else the request's path value (http.Request.PathValue). It is intended for stdlib handlers mounted via App.Mount, which receive the parameters of the mount prefix as path values: under Mount("/t/{tenant}", h), URLParam(r, "tenant") is the tenant. Credo handlers use Request.RouteParam instead. Returns empty string if the parameter doesn't exist.

func Walk

func Walk(r Routes, fn WalkFunc) error

Walk iterates over registered routes, calling fn with the method and pattern of each one. Mounts (Kind == RouteKindMount) are skipped: the method+pattern shape cannot represent a mount, which answers many methods at a prefix. Use WalkRoutes for the full surface, mounts included.

func WalkRoutes

func WalkRoutes(r Routes, fn WalkRoutesFunc) error

WalkRoutes iterates over all registered routes with full RouteInfo, calling fn for each one.

Types

type AccessLogConfig added in v0.19.0

type AccessLogConfig struct {
	// Logger is a dedicated sink for access records. nil logs through the
	// request-scoped logger, which already carries request_id when
	// [App.UseRequestID] is installed and the handler materialized it; a
	// dedicated logger never inherits [Context.AddLogAttrs]/[Context.SetLogger]
	// enrichment, so the framework attaches request_id explicitly.
	Logger *slog.Logger

	// MinLevel is the minimum status-derived level a record must reach to be
	// submitted: 1xx/2xx/3xx are Info, 4xx Warn, 5xx+ Error. nil selects
	// Info. The Leveler may be consulted concurrently and must be
	// concurrency-safe; [slog.LevelVar] supports runtime changes. A typed-nil
	// Leveler is rejected at registration.
	MinLevel slog.Leveler

	// Skipper excludes a request before routing; only request-level data is
	// reliable inside it (method, path, headers). For route-based silencing
	// use [MetaAccessLog]; for post-response decisions use MinLevel or
	// ResultFilter.
	Skipper func(ctx *Context) bool

	// ResultFilter is a post-response predicate: it runs only after
	// MetaAccessLog silencing and the MinLevel check, sees the final entry,
	// and emits it on true. It cannot restore an entry MinLevel rejected.
	ResultFilter AccessLogResultFilter
}

AccessLogConfig configures the access-log feature installed by App.UseAccessLog. The zero value selects every default.

type AccessLogEntry added in v0.3.0

type AccessLogEntry struct {
	Method       string
	Path         string
	OriginalPath string
	Route        string
	Status       int
	Bytes        int64
	Duration     time.Duration
	RemoteAddr   string
	UserAgent    string
	RequestID    string
	RouteName    string
}

AccessLogEntry is an immutable value snapshot captured at the access-log observation boundary, after the final response: error rendering, panic recovery and response finalization (the compressor's trailer included) have completed, so Status, Bytes and Duration are final. Bytes counts the bytes the underlying transport writer accepted — compressed output when response compression applied. Duration is measured from executor entry to response finalization; the result filter and the log emission itself are excluded. If recovery is disabled and a panic escapes, Status uses the 500 fallback while Bytes reflects only what was written before the panic.

Route is the matched route's registered pattern (for example "/v1/jobs/{job_id}"), empty when no route matched (404/405). It is emitted as the "route" attribute, so a deployment that must not persist concrete path values can drop "path"/"path_original" in its slog handler (for example via slog.HandlerOptions.ReplaceAttr) and keep the low-cardinality route instead. RouteName is available to AccessLogResultFilter but is not added to the emitted structured-log attributes. RemoteAddr is the result of Request.RealIP. RequestID is populated independently of whether the target logger already carries the request_id attribute.

type AccessLogResultFilter added in v0.3.0

type AccessLogResultFilter func(ctx *Context, entry AccessLogEntry) bool

AccessLogResultFilter decides whether an observed access-log entry is submitted to its logger. Returning true emits the entry; false skips it. The Context is pooled and must not be retained. The same filter may be called concurrently for multiple requests and must be concurrency-safe.

The filter runs after the final response. A panic inside it is logged as a framework diagnostic and the entry is skipped; the response is unaffected. With WithoutRecover the panic propagates after request cleanup.

type App

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

App is the main Credo application. It holds the router, middleware stack, context pool, error handler, and route registry.

func New

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

New creates a new App with the given options. When no RawConfig is provided, New auto-loads configuration with config.Load and registers the resulting RawConfig in DI. Passing WithRawConfig bypasses auto-load and registers the given RawConfig instead.

New returns an error if configuration loading fails, server settings contain invalid values (negative timeouts, invalid port), or an option contains an invalid typed-nil value such as a non-nil slog.Leveler interface wrapping a nil pointer.

Usage:

// Zero-config (all defaults):
app, err := credo.New()

// With listen address:
app, err := credo.New(credo.WithAddr("127.0.0.1", 8080))

// With explicit RawConfig (server settings read from "server" key):
app, err := credo.New(credo.WithRawConfig(rawCfg))

func (*App) AddLivenessCheck

func (app *App) AddLivenessCheck(name string, checker HealthChecker)

AddLivenessCheck registers a named liveness check. Panics if App.UseHealth has not been called first, checker is nil, or name is empty, padded with whitespace, contains control characters, uses the reserved "credo." prefix, or duplicates another liveness check.

func (*App) AddReadinessCheck

func (app *App) AddReadinessCheck(name string, checker HealthChecker)

AddReadinessCheck registers a named readiness check. Panics if App.UseHealth has not been called first, checker is nil, or name is empty, padded with whitespace, contains control characters, uses the reserved "credo." prefix, or duplicates another readiness check.

func (*App) Addr

func (app *App) Addr() net.Addr

Addr returns the actual network address the server is listening on. This is particularly useful when the server was started with port 0, as the OS assigns an ephemeral port. Returns nil before Run or after the server stops.

func (*App) AdoptValue added in v0.19.0

func (app *App) AdoptValue[T any](validate func(T) error) (T, error)

AdoptValue reads the pre-built value bound to T during the registration phase, validates it, and atomically protects that same binding against App.Replace before returning it. It is the one registration-time read Credo supports: constructors run only after App.Finalize, so a constructor binding for T is rejected with an explanatory error without being invoked.

A nil validate accepts every value. Validation failure leaves the binding unprotected and repairable through Replace; a Replace or Finalize that wins while validation runs makes the adoption fail rather than protecting or returning a stale instance. Framework integrations (store, worker) use it to take ownership of a value the composition root supplied ahead of them. Use App.Has for a plain existence check.

func (*App) Alias

func (app *App) Alias[I, T any]() error

Alias creates a type alias so that resolving interface I via App.Resolve returns the singleton registered for concrete type T. I must be an interface, T must implement I, and T must already be registered.

app.Alias[UserRepo, *PgUserRepo]()

func (*App) BindMany

func (app *App) BindMany[I, T any]() error

BindMany adds concrete type T to the ordered collection for interface I. I must be an interface, T must be a registered concrete type, and T must implement I.

func (*App) CanProvideValue

func (app *App) CanProvideValue[T any]() error

CanProvideValue reports whether App.ProvideValue could currently register type T. It checks only whether the DI container is finalized or T already has a direct registration, and does not mutate or reserve the registration.

The result is a point-in-time preflight. A later ProvideValue call can still fail if another registration or finalization occurs in between.

func (*App) ConfigExists added in v0.19.0

func (app *App) ConfigExists(key string) bool

ConfigExists reports whether key is present in the application's RawConfig, mirroring [RawConfig.Exists]. Like App.GetConfig it is a bootstrap helper that reads configuration directly, so framework modules and composition roots can consult optional sections during registration, before App.Finalize makes App.Resolve available.

func (*App) DELETE

func (app *App) DELETE(pattern string, h Handler) *Route

DELETE registers a DELETE route. Panics under the same conditions as App.GET.

func (*App) File

func (app *App) File(urlPath string, fsys fs.FS, name string, cfgs ...StaticConfig) *Route

File registers a single GET route that serves one named file from fsys. Returns *Route for standard fluent chaining (Name, SetMeta, Middleware).

Only the Download and CacheControl fields of StaticConfig are supported. Setting Browse, SPA, or a non-empty Index panics at registration time.

Panics if called after compile.

func (*App) Finalize

func (app *App) Finalize() error

Finalize freezes the DI container and validates the dependency graph. After Finalize, no more Provide, ProvideValue, ProvideProtectedValue, ProtectBinding, AdoptValue, Replace, Alias, or BindMany calls are allowed, and App.Resolve becomes available. Finalize is DI-only: routes, hooks, renderers and other HTTP registrations stay open until the App prepares to serve, so controllers built from resolved services can still be wired afterwards.

Finalize is idempotent. If not called explicitly, the Run* entry points and the first App.ServeHTTP call it implicitly.

app.Finalize()

func (*App) GET

func (app *App) GET(pattern string, h Handler) *Route

GET registers a GET route. A matching HEAD handler is registered automatically; subsequent calls to Route.Middleware and Route.SetMeta on the returned route apply to HEAD as well, so HEAD requests can never silently bypass auth, rate limiting, or meta-driven middleware.

Panics if h is nil, the pattern is invalid or already registered, or if called after compile (route registration is developer configuration — see the package-level "Panics and Errors" section).

func (*App) GetConfig

func (app *App) GetConfig[T any](key string) (T, error)

GetConfig decodes the configuration value or sub-tree at the given dotted key path into a value of type T and returns it. It is a convenience wrapper over the application's RawConfig (auto-loaded or supplied via WithRawConfig), saving an explicit app.MustResolve[RawConfig]() plus Unmarshal:

db, err := app.GetConfig[DatabaseConfig]("database")

Like config.(*Config).Get, this is a bootstrap/composition-root helper: read config here and inject typed structs into services via DI rather than reading string keys inside business code (a handler cannot reach this method — there is no App accessor on *Context). A missing key or decode failure returns an error; on error the zero value of T is returned.

func (*App) GetRoute

func (app *App) GetRoute(name string) *Route

GetRoute returns a named route by name.

func (*App) GlobalMiddleware

func (app *App) GlobalMiddleware(middlewares ...Middleware)

GlobalMiddleware appends middleware that runs on every request, including 404 and 405 responses. Must be called before the server starts; panics if called after compile.

func (*App) Group

func (app *App) Group(prefix string) *Group

Group creates a new route group with the given prefix.

func (*App) HEAD

func (app *App) HEAD(pattern string, h Handler) *Route

HEAD registers an explicit HEAD route (overrides auto-generated one). Panics under the same conditions as App.GET.

func (*App) Has added in v0.19.0

func (app *App) Has[T any]() bool

Has reports whether type T is registered, directly or through App.Alias. It never constructs, adopts or protects anything and makes no claim that the instance is healthy or usable; the result is a snapshot, not a reservation for a later registration.

func (*App) Host

func (app *App) Host(pattern string) *Group

Host creates a route group scoped to the given host pattern. Pattern supports exact labels ("api.example.com"), named parameters ("{tenant}.example.com", "{org:[a-z]+}.platform.io"), and a leftmost anonymous wildcard label ("*.example.com"). Routes registered on the returned Group only match requests whose Host header matches the pattern. Unmatched hosts fall back to the default mux. Returns *Group for API consistency with App.Group.

Host panics if the pattern is a duplicate, overlaps an existing pattern with identical match semantics, contains an invalid wildcard, an invalid regex constraint, or a port. Registering a route on the returned Group panics if a route parameter name collides with a host parameter name. Must be called before the server starts; panics if called after compile.

func (*App) IsDebug

func (app *App) IsDebug() bool

IsDebug reports whether the application is running in debug mode. Debug mode enables development-time warnings (e.g., bind targets that do not implement Validatable). Activated via WithDebug or the server.debug config key.

func (*App) IsRunning

func (app *App) IsRunning() bool

IsRunning reports whether the server is in the running state.

func (*App) Logger

func (app *App) Logger() *slog.Logger

Logger returns the application-level logger used by framework internals. Worker and other integration packages use this accessor to derive framework-scoped loggers without exposing raw logger registration in DI.

func (*App) Mount

func (app *App) Mount(pattern string, handler http.Handler)

Mount attaches another http.Handler as a sub-router under the given pattern. The sub-router receives the remainder of the URL path.

The pattern may carry parameters ("/t/{tenant}", "/v/{major}.{minor}", "/y/{year:[0-9]{4}}"). The handler then receives the path below the matched prefix, and each parameter of the prefix as a path value: a stdlib handler reads it with r.PathValue("tenant") or URLParam, a mounted Credo app with ctx.Request().PathValue("tenant") — Request.RouteParam returns that app's own route parameters only. Path values the request already carried are kept; a name used again holds the value of the prefix closest to the handler. A catch-all parameter is not a prefix: it consumes the rest of the path, so the handler would always be handed "/".

Method scope: the mounted handler is registered for all standard HTTP methods except CONNECT and TRACE, which are excluded deliberately (CONNECT is a proxy mechanism; TRACE enables cross-site tracing). Requests using them receive 405 Method Not Allowed.

Middleware scope: mounted handlers receive only global middleware (and the framework features that wrap every request). Group-level and route-level middleware do not apply because mounted handlers are plain http.Handler instances dispatched outside the per-route compiled chain. If the mounted sub-application requires authentication or other protections, it must enforce them internally or the protections must be registered as global middleware.

The parent's RouteContext (which may contain internal params like _mount) is stripped before calling the child handler, so the child dispatch creates its own fresh RouteContext. This prevents internal routing state from leaking across mount boundaries. The parameters of a prefix cross the boundary as path values instead, set on a clone of the request, so the request the caller holds keeps the path values it had.

Must be called before the server starts; panics if called after compile.

func (*App) MustAlias

func (app *App) MustAlias[I, T any]()

MustAlias is like App.Alias but panics on error.

func (*App) MustBindMany

func (app *App) MustBindMany[I, T any]()

MustBindMany is like App.BindMany but panics on error.

func (*App) MustGetConfig

func (app *App) MustGetConfig[T any](key string) T

MustGetConfig is like App.GetConfig but panics on error. It suits composition-root code where a missing or invalid required key should abort startup.

func (*App) MustProvide

func (app *App) MustProvide[T any](constructor any)

MustProvide is like App.Provide but panics on error.

func (*App) MustProvideValue

func (app *App) MustProvideValue[T any](value T)

MustProvideValue is like App.ProvideValue but panics on error.

func (*App) MustReplace

func (app *App) MustReplace[T any](value T) (old T, existed bool)

MustReplace is like App.Replace but panics on error. It returns the same previous-instance information.

func (*App) MustResolve

func (app *App) MustResolve[T any]() T

MustResolve is like App.Resolve but panics on error. It is primarily intended for bootstrap/composition-root code. A constructor panic surfaces here as a panic whose value is the DIPanicError, not the original value.

func (*App) MustResolveAll

func (app *App) MustResolveAll[T any]() []T

MustResolveAll is like App.ResolveAll but panics on error.

func (*App) NewInfra

func (app *App) NewInfra(name string) Infra

NewInfra creates a scoped Infra with the given name. The Logger is tagged with "service"=name and falls back to the framework default logger when the application has none configured.

Use NewInfra for components that live outside the DI container (middleware factories, startup helpers, workers created manually). For DI-managed services, Infra is injected automatically.

func (*App) OPTIONS

func (app *App) OPTIONS(pattern string, h Handler) *Route

OPTIONS registers an OPTIONS route. Panics under the same conditions as App.GET.

func (*App) OnConfigChange added in v0.5.0

func (app *App) OnConfigChange[T any](key string, fn func(ctx context.Context, next T) error)

OnConfigChange registers a typed subscriber for one configuration section. When a reload changes any leaf under key (or key itself), T is decoded from the new snapshot and fn receives it; subscribers whose section did not change are not invoked. Several subscriptions may share a key, and nested keys are independent: "databases" and "databases.primary" both fire when databases.primary.dsn changes.

When the App's RawConfig implements config.Stager (as *config.Config does), every affected subscriber is decoded — and validated, if T has a Validate() error method — against the candidate snapshot before it is published; any failure aborts the reload and the previous snapshot stays current. With a store that only implements config.Reloader the snapshot is published first and a decode failure is reported through the Reload error.

The subscriber owns atomic application in its own domain — store the value behind an atomic.Pointer, call slog.LevelVar.Set, swap a limiter. The framework never rebuilds DI singletons (ADR-004): a value already injected through a constructor does not change.

Must be called before Run. Panics for a nil fn, after the App is frozen, or when the App's RawConfig implements neither config.Stager nor config.Reloader — a subscription that can never fire is startup misuse.

func (*App) OnDrain

func (app *App) OnDrain(fn func(ctx context.Context) error)

OnDrain registers a subsystem drain hook that runs after the application lifecycle context is cancelled and before DI infrastructure is shut down. Hooks run concurrently with one another and with HTTP server draining; no ordering between hooks is guaranteed. The ctx carries the same absolute shutdown deadline used by the HTTP drain.

A successful hook must ensure its subsystem can no longer run handlers that depend on application infrastructure. Hooks also run during teardown after an OnStart failure, so they must be idempotent and must not assume their corresponding startup work completed. A hook that ignores ctx may outlive the shutdown budget; Credo reports it as incomplete and proceeds with the expired-context teardown contract rather than claiming graceful success.

Must be called before Run; panics for a nil hook or after the App is frozen.

func (*App) OnPreDrain

func (app *App) OnPreDrain(fn func(ctx context.Context) error)

OnPreDrain registers an early subsystem drain hook that runs after shutdown begins and readiness is withdrawn, but before the application lifecycle context is cancelled. Hooks run concurrently with one another; registration order is identity only, not execution order. The ctx carries the same absolute shutdown deadline used by every later teardown phase.

A successful hook must stop its subsystem's admission and finish work that still depends on live background workers or DI infrastructure. Hooks also run during teardown after an OnStart failure, so they must be idempotent and must tolerate partial startup. If a hook is still running when ctx ends, Credo logs a waiting diagnostic but keeps the lifecycle context and infrastructure live until the hook actually returns. Its completion timestamp determines the final identified incomplete error. Later teardown then continues with the same, possibly expired context rather than racing the pre-drain work.

Most subsystems should use App.OnDrain, which runs after lifecycle cancellation and concurrently with HTTP drain. OnPreDrain is for the narrower case where cancellation itself would tear down a dependency too early.

Must be called before Run; panics for a nil hook or after the App is frozen.

func (*App) OnReload added in v0.5.0

func (app *App) OnReload(fn func(ctx context.Context) error)

OnReload registers a reload hook. Hooks run in FIFO order at the end of every App.Reload — after the new configuration snapshot is visible and the typed App.OnConfigChange subscribers have applied their sections — with the reload context (WithReloadTimeout for the SIGHUP path, the caller's for a programmatic Reload). An error, or a recovered panic, is joined into the Reload result and does not skip later hooks; it never stops the process.

Typical uses: re-open a log file after rotation, refresh an allowlist, drive certificate rotation for a WithTLSConfig source through its own GetCertificate.

Must be called before Run; panics for a nil hook or after the App is frozen.

func (*App) OnShutdown

func (app *App) OnShutdown(fn func(ctx context.Context) error)

OnShutdown registers a function to be called during graceful shutdown. Hooks are called in LIFO order (last registered, first called). The ctx passed to each hook carries the shutdown deadline from Shutdown(ctx).

The hooks are the last teardown step: they run after HTTP and the OnDrain hooks have drained and after the DI container has shut down, so a singleton that implements Shutdowner is already closed when a hook runs. Work that still needs such a singleton — flushing through a database handle, a final publish — belongs in App.OnDrain, which runs before DI teardown.

Hooks run on every teardown, including a failed startup (an OnStart hook erroring after an earlier one ran). OnShutdown is the session teardown point, not an OnStart mirror, so hooks must be idempotent and must not assume any particular OnStart hook completed.

A hook that panics is recovered: the panic is logged with its stack and becomes that hook's error, the remaining hooks still run, and Shutdown returns the joined errors.

Must be called before Run; panics for a nil hook or after the App is frozen.

func (*App) OnStart

func (app *App) OnStart(fn func(ctx context.Context) error)

OnStart registers a function to be called during startup, after the port is bound but before the server starts accepting connections. Hooks are called in FIFO order (first registered, first called). The ctx passed to each hook is the lifecycle context (created at Run time). It is derived independently from any ctx passed to RunContext, so cancelling that ctx during startup does not abort a running hook; the cancellation is observed only after all hooks complete. If any hook returns an error, the server does not start: remaining hooks are skipped, the App runs the full teardown chain (the same as graceful shutdown, including DI shutdown and OnShutdown hooks), and Run returns the error. The App ends terminally stopped — a session that began tears down rather than rolling back, so it cannot be run again (create a new App). A hook that panics fails the same way: the panic is recovered, logged with its stack and reported as that hook's error. Typical uses include cache warm-up. The store/sqldb migration wrapper plugs in directly as app.OnStart(db.Migrate) for development and deliberate single-replica deployments; multi-replica production should use one deadline-bounded pre-deploy migration job instead. Must be called before Run; panics for a nil hook or after the App is frozen.

func (*App) PATCH

func (app *App) PATCH(pattern string, h Handler) *Route

PATCH registers a PATCH route. Panics under the same conditions as App.GET.

func (*App) POST

func (app *App) POST(pattern string, h Handler) *Route

POST registers a POST route. Panics under the same conditions as App.GET.

func (*App) PUT

func (app *App) PUT(pattern string, h Handler) *Route

PUT registers a PUT route. Panics under the same conditions as App.GET.

func (*App) ProtectBinding

func (app *App) ProtectBinding[T any](expected ...T) error

ProtectBinding prevents App.Replace from overwriting the existing direct registration for T. It is idempotent and rejected after Finalize. The method does not resolve or otherwise instantiate T. When one expected value is supplied, protection is a compare-and-protect operation: it succeeds only if the bound prebuilt value is still that same comparable value. Integrations that need to read, validate and protect in one step use App.AdoptValue.

func (*App) Provide

func (app *App) Provide[T any](constructor any) error

Provide registers a constructor for type T in the application's DI container. The constructor can accept any number of parameters that are themselves registered, and must return T or (T, error). It runs at most once, on the first resolution after App.Finalize.

app.Provide[*UserService](NewUserService)

Because Go cannot express "a function with arbitrary parameters returning T" in the type system, constructor is typed any: signature mistakes (wrong return type, not a function) are reported as an error at registration time, not at compile time. The dependency graph itself is validated at App.Finalize. A constructor that captures app and calls App.Resolve inside its body is unsupported: such a dependency is invisible to graph validation, cycle detection and dependency-ordered shutdown.

func (*App) ProvideProtectedValue

func (app *App) ProvideProtectedValue[T any](value T) error

ProvideProtectedValue registers a pre-built singleton whose binding cannot later be overwritten through App.Replace. It is intended for integrations that publish a value together with external lifecycle or health state and therefore cannot safely allow the DI binding to diverge afterward.

func (*App) ProvideValue

func (app *App) ProvideValue[T any](value T) error

ProvideValue registers a pre-built value for type T as a Singleton. The container owns the value from then on: if it implements Shutdowner it is closed during teardown, unless a later successful App.Replace hands it back to the caller.

app.ProvideValue[*Logger](logger)

func (*App) QUERY added in v0.13.0

func (app *App) QUERY(pattern string, h Handler) *Route

QUERY registers an RFC 10008 safe, idempotent query route whose query representation travels in the request body. Request.BindBody provides the standard decode-and-validate path. QUERY requests must include Content-Type. Panics under the same conditions as App.GET.

func (*App) Reload added in v0.5.0

func (app *App) Reload(ctx context.Context) error

Reload performs a trigger-driven partial reload (ADR-020). It succeeds only while the server is running. The sequence is:

  1. If the RawConfig implements config.Stager, re-read every source into a candidate snapshot (a load error aborts with the old snapshot untouched).
  2. Decode — and validate — every App.OnConfigChange subscriber whose section the candidate changes; any failure aborts before anything is published.
  3. Publish the snapshot atomically, run framework participants (file-based TLS rotation), the affected subscribers in registration order, then the App.OnReload hooks FIFO. Errors and recovered panics are collected and the sequence continues; there is no rollback.
  4. Return the joined step-3 errors (nil on full success), log one Info summary, and log a Warn naming every changed key that no subscriber or participant covers — those sections are restart-only.

A RawConfig that implements only config.Reloader skips the pre-publish validation: the snapshot is published first and decode failures become step-3 errors. A RawConfig that implements neither leaves the configuration untouched and runs only the participants and OnReload hooks.

Concurrent calls are serialized: a caller waits for the in-flight reload unless its ctx ends first, and a caller still queued when shutdown begins returns the not-running error instead of reloading a stopping server. Every participant, subscriber, and hook receives a context that is cancelled when either ctx or the application lifecycle ends, so a reload overlapping a shutdown is told to stop; shutdown then waits for it to return before tearing down DI infrastructure (see App.Shutdown).

Under App.Run a SIGHUP (Unix) calls Reload with a context bounded by WithReloadTimeout; App.RunContext and App.ServeContext install no signal handler, so their callers invoke Reload directly. A reload never stops the process, whatever it reports.

func (*App) RemoveMeta

func (app *App) RemoveMeta(key string)

RemoveMeta removes a root-level metadata key. Must be called before the server starts; panics if called after compile.

func (*App) Replace

func (app *App) Replace[T any](value T) (old T, existed bool, err error)

Replace registers a pre-built value for type T, overwriting any existing unprotected registration. Unlike App.ProvideValue, a duplicate T is normally replaced. Bindings published by App.ProvideProtectedValue, locked through App.ProtectBinding or adopted through App.AdoptValue reject replacement because external lifecycle state depends on their identity.

On success the container owns the new value and no longer tracks the superseded instance: Replace returns that instance with existed == true when a previously created instance existed (a pre-built value), and the caller assumes its cleanup responsibility. A superseded constructor binding that never ran yields the zero value and false; Replace never constructs an old provider merely to return it. When the returned instance implements Shutdowner a Warn log names the type, as a reminder that the container will not close it. A rejected replacement changes neither the binding nor ownership.

Replace is intended for composition-root overrides and tests where a real binding is swapped for a stub or fake. Because the replacement is a value, it carries no dependencies and stays valid during App.Finalize. Replace is rejected after the container is finalized or shut down.

In tests, the github.com/credo-go/credo/testutil package builds on Replace through its WithOverride option.

old, existed, err := app.Replace[UserRepo](mockRepo)

func (*App) Resolve

func (app *App) Resolve[T any]() (T, error)

Resolve retrieves an instance of type T from the application's DI container. It is admitted only after App.Finalize (Run and ServeHTTP finalize implicitly): constructors run at first resolution, exactly once, and a constructor panic is returned as a DIPanicError to every caller. Once shutdown has reached DI teardown, Resolve returns an error wrapping ErrDIClosed.

Resolve is primarily intended for bootstrap/composition-root code after Finalize; runtime calls remain available, but Credo's recommended application pattern is constructor injection. The shutdown hooks (App.OnPreDrain, App.OnDrain, App.OnShutdown) must not resolve: take their dependencies at registration time instead. App.OnStart hooks run after Finalize and before traffic, and may resolve.

svc, err := app.Resolve[*UserService]()

func (*App) ResolveAll

func (app *App) ResolveAll[T any]() ([]T, error)

ResolveAll retrieves all singletons bound to interface type T via App.BindMany, preserving bind order. When no bindings exist, it returns an empty slice and nil error. The same phase rules as App.Resolve apply.

func (*App) Routes

func (app *App) Routes() []RouteInfo

Routes returns introspection data for every registered route across the default mux and all host-scoped muxes, plus one entry per App.Mount prefix. See RouteInfo for the per-entry fields, including the route Name, the resolved and shallow-copied Meta, and a mount's forwarded method set.

The result is a deterministic total order — sorted by (Host, Pattern, Method, Kind), independent of registration order and host compile-sort state — so route/permission catalogs and golden-file tests stay stable. The returned slice and each RouteInfo.Meta map are freshly allocated; the caller owns them.

Routes reads live *Route fields (Name, metadata) without locking, so it must not run concurrently with route registration or configuration (Name, SetMeta, Mount). It is a post-wiring (or post-freeze) operation.

func (*App) Run

func (app *App) Run() error

Run starts the HTTP server and blocks until an interrupt (Ctrl+C) or SIGTERM is received, then performs graceful shutdown using the deadline set by WithShutdownTimeout. An App.OnPreDrain hook that ignores that deadline remains a hard teardown barrier and may delay return. A second signal during shutdown force-kills the process. Returns nil on graceful shutdown.

On Unix, Run also handles SIGHUP: each signal triggers App.Reload under the WithReloadTimeout budget (systemctl reload, logrotate postrotate). Reloads run one at a time, signals that arrive during a reload coalesce into at most one follow-up, and a failed reload is logged but never stops the server. There is no SIGHUP on Windows; there, and under App.RunContext on every platform, the programmatic App.Reload is the only trigger.

Run serves HTTPS automatically when TLS is configured via WithTLSFiles, WithTLSConfig, or the server.tls.* config keys; otherwise it serves plaintext. A misconfigured certificate (missing file, mismatched pair, or a WithTLSConfig with no certificate source) fails fast before the server accepts connections, rolling the lifecycle back so the App can run again.

Run is the safe default for a process whose lifetime is the server's. For explicit lifecycle control — tests, embedding, or caller-driven cancellation — use App.RunContext.

func (*App) RunContext

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

RunContext starts the HTTP server and blocks until ctx is cancelled, the server stops, or a programmatic App.Shutdown. Unlike App.Run it installs no signal handler; cancellation is entirely the caller's. On ctx cancellation the drain keeps ctx's values but drops its cancellation and applies the WithShutdownTimeout deadline. An App.OnPreDrain hook that ignores that deadline remains a hard teardown barrier and may delay return. Returns nil on graceful shutdown.

Like App.Run, RunContext serves HTTPS when TLS is configured (via WithTLSFiles, WithTLSConfig, or server.tls.*) and plaintext otherwise, with the same fail-fast certificate validation.

Cancelling ctx during startup does not abort an in-progress App.OnStart hook: hooks receive the lifecycle context, not ctx, so the cancellation takes effect only after all hooks complete.

func (*App) ServeContext

func (app *App) ServeContext(ctx context.Context, l net.Listener) error

ServeContext serves on a caller-provided listener, sharing the same lifecycle as App.RunContext. It is the escape hatch for listeners the framework does not create itself — Unix sockets, a preconfigured test listener, or an externally managed listener. It supplies the listener only; the server itself is still the one the framework builds, so protocol-level settings such as H2C come from WithHTTPServer:

credo.WithHTTPServer(func(s *http.Server) {
	s.Protocols = new(http.Protocols)
	s.Protocols.SetHTTP1(true)
	s.Protocols.SetUnencryptedHTTP2(true)
})

ServeContext takes ownership of l: it is closed when the server stops, matching net/http.Server.Serve semantics. Returns nil on graceful shutdown.

ServeContext serves l exactly as given and is TLS-exempt: TLS configured via WithTLSFiles or WithTLSConfig does not apply here, nor does the WithHTTPRedirect listener. For HTTPS on a custom listener, wrap it yourself — e.g. tls.NewListener(l, cfg).

func (*App) ServeHTTP

func (app *App) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements http.Handler. The first call prepares the App — Finalize, compile, publish — and stores the result; a preparation error is a developer error and panics on every request rather than being retried. Requests are admitted by lifecycle state: a stopped App, or a stopping App that was never prepared, receives the default 503 envelope without touching DI or any configured callback, while an already-prepared handler keeps serving during the managed drain. Direct ServeHTTP never claims the managed server's start slot; an external http.Server stays its owner's job to drain before App.Shutdown.

func (*App) SetMeta

func (app *App) SetMeta(key string, val any)

SetMeta sets a root-level metadata key-value pair. Must be called before the server starts; panics if called after compile.

func (*App) Shutdown

func (app *App) Shutdown(ctx context.Context) error

Shutdown gracefully shuts down the server: it withdraws readiness, runs App.OnPreDrain, cancels the lifecycle context, drains in-flight HTTP requests and App.OnDrain subsystem hooks in parallel, tears down DI singletons in dependency order, then runs OnShutdown hooks (LIFO). The caller's ctx carries the shared absolute deadline; WithShutdownTimeout does not replace it. An OnPreDrain hook that ignores ctx remains a hard teardown barrier and may delay return beyond that deadline. Returns an error if any shutdown step fails or remains incomplete (joined via errors.Join).

Shutdown is also accepted on an App that was never run: bootstrap teardown closes route and DI registration, runs the same drain with no managed server, and tears down every singleton that exists — including values registered by a composition root whose App.Finalize never ran or failed. This is the cleanup path for tests and for Apps served through an external http.Server; that server's admission and drain remain its owner's job and must complete before Shutdown. The App is single-use: the terminal state is stopped even when cleanup was incomplete. Shutdown returns an error when the App is starting, or has already stopped; a managed start that reaches running (or rolls back to building) while Shutdown is deciding is claimed by the same call rather than refused with a stale state.

func (*App) State

func (app *App) State() string

State returns the current lifecycle state as a string.

func (*App) Static

func (app *App) Static(prefix string, fsys fs.FS, cfgs ...StaticConfig) *StaticRoute

Static registers routes that serve files from fsys under the given URL prefix. Returns a *StaticRoute for fluent configuration (Name, SetMeta, Middleware).

Internally registers two routes: a catch-all for file paths and an exact match for the prefix itself (serves the index file). Both share the same handler and receive fluent configuration uniformly via StaticRoute.

Panics if prefix contains { or } (route parameters in a static prefix are not meaningful) or if called after compile. The cache presets (StaticCacheMaxAge, StaticCacheImmutableAssets) panic at their own call site on invalid durations.

Production recommendation: use DirFS (or os.Root.FS()) for symlink-safe disk serving. os.DirFS does not prevent symlink-based path traversal.

func (*App) StatusHandler

func (app *App) StatusHandler(code int, h Handler)

StatusHandler sets an app-level custom handler for the router's own 404 or 405 answer. The handler registered for http.StatusNotFound runs when no route matches the request; the one for http.StatusMethodNotAllowed runs when routes match the path but none of them serves the method, with the Allow header already set. It answers in place of the default error response for that case, inside the global middleware and without a matched route (Context.HasRoute reports false).

Only these two codes are consulted. A handler registered for any other code is accepted and never called. The handlers are not error handlers either: an error that a route handler or a middleware returns — ErrNotFound included — goes through the centralized error handling and does not reach them; use App.UseErrorRenderer to shape error bodies.

Must be called before the server starts; panics if called after compile.

func (*App) UseAccessLog added in v0.19.0

func (app *App) UseAccessLog(cfgs ...AccessLogConfig)

UseAccessLog installs access logging: one "request completed" record per request with method, path, route, status, bytes, duration, remote_addr (from Request.RealIP), user_agent and request_id. The record is observed after the final response — error rendering, panic recovery and response finalization included — so status and bytes are what the client received. Order: Skipper → request → MetaAccessLog → status/level → MinLevel → snapshot → ResultFilter → emit.

The feature is off by default and independent of App.UseRequestID: the request_id attribute is empty when only access logging is installed. UseAccessLog accepts zero configs for the defaults or one config; it panics for more than one config, for a typed-nil MinLevel, when called twice, or after the App was prepared or shut down.

func (*App) UseCompress added in v0.19.0

func (app *App) UseCompress(cfgs ...CompressConfig)

UseCompress installs response compression. For a request whose Accept-Encoding negotiates gzip or deflate, the response writer is wrapped before any user middleware runs and the wrapper stays in place through centralized error rendering, so error envelopes are compressed like handler output. Compression is applied only to responses whose Content-Type is in Types and that carry no Content-Encoding of their own; HEAD and bodiless responses, streaming (Flush), committed responses and hijacked connections keep their behavior. The compressor is finalized at the framework's response-completion boundary, before the access record observes the response, so access-log bytes count the compressed output the transport accepted.

The feature is off by default. UseCompress accepts zero configs for the defaults or one config; it panics for more than one config, for a Level outside 1–9, when called twice, or after the App was prepared or shut down.

func (*App) UseDecompress added in v0.19.0

func (app *App) UseDecompress(cfgs ...DecompressConfig)

UseDecompress installs request-body decompression. Credo does not decompress request bodies by default: a Content-Encoding the application has not opted into is rejected by BindBody with 415 Unsupported Media Type. This feature is that opt-in. It understands gzip (also x-gzip) and deflate (zlib-wrapped per RFC 9110, with raw DEFLATE accepted for clients that omit the zlib header), all from the standard library.

Decompression runs before Global middleware, so body-reading middleware and binders consume the same decoded stream. For a matching request it replaces the body with the decompressed stream bounded by MaxBytes (the server's max_body_bytes still bounds the compressed wire bytes independently), sets ContentLength to -1 (unknown), and removes the Content-Encoding header so downstream binding treats the body as plain. An unsupported coding or a coding list with more than one entry answers 415; a stream whose header is already corrupt answers 400 through the regular bind error pipeline; both are rendered without running any user middleware. Bodies declared empty pass through untouched.

The feature is off by default. UseDecompress accepts zero configs for the defaults or one config; it panics for more than one config, for a negative MaxBytes, when called twice, or after the App was prepared or shut down.

func (*App) UseErrorRenderer added in v0.19.0

func (app *App) UseErrorRenderer(r ErrorRenderer)

UseErrorRenderer installs the renderer that shapes error response bodies. The framework handles error classification, logging, the status code, HEAD handling, and committed-response guards internally; the renderer receives a request-scoped ErrorInfo containing normalized status, code, message key, resolved message, details, and violations, and returns the body to encode — or nil for the default Credo body. It is the error-side mirror of App.UseSuccessRenderer: install both to give every response, success and failure alike, one envelope.

The renderer may be a method of a service resolved from DI after App.Finalize; registration stays open until the App prepares to serve. Omitting the call keeps the default JSON renderer. UseErrorRenderer panics for a nil renderer, when called twice, or after the App was prepared or shut down.

func (*App) UseHealth

func (app *App) UseHealth(cfgs ...HealthConfig)

UseHealth initializes health check endpoints on the application. With no arguments, it registers both /health (liveness) and /ready (readiness).

UseHealth performs no I/O — it only registers in-process state — so misuse panics like every other registration API (contrast App.UseI18n, which reads locale files and therefore returns an error). Panics if called more than once, if called after compile, or if cfg.Group belongs to a different App.

func (*App) UseI18n

func (app *App) UseI18n(cfgs ...I18nConfig) error

UseI18n initializes i18n for the application. It loads locale files and installs the bundle; the request locale is then resolved lazily through I18nConfig.Detect on the first Context.Locale or translation access of each request — there is no locale middleware.

Behavior:

  • No args or zero-value cfg: reads RawConfig "i18n" key; if absent, uses defaults (dir="locales/", default="en").
  • An implicitly discovered locales/ directory may be absent (inactive).
  • An explicit Dir or DirFS must exist and contain at least one message.
  • Messages/Fields provide one programmatic catalog for Default; external files override it key by key.
  • Malformed files: returns error.
  • Valid files: installs the bundle.

Unlike registration-only setup APIs such as App.UseHealth, UseI18n reads locale files from disk or an fs.FS — an external operation that can fail for reasons other than a programming mistake — so failures are returned as errors rather than panicking. It still panics if called after preparation or shutdown, like all configuration APIs, and when called twice: a completed call — an inactive conventional setup included — consumes the slot, while a call that returned an error leaves it free.

func (*App) UseRequestID added in v0.19.0

func (app *App) UseRequestID(cfgs ...RequestIDConfig)

UseRequestID installs request correlation: every request gets an ID — the incoming Header value when it is present, within Limit and made of safe header/log characters, otherwise a freshly generated one — published on the response header, readable through Context.RequestID and attached as the request_id attribute of the request-scoped logger the first time Context.Logger is used.

The feature is off by default; without it no ID is generated or echoed and Context.RequestID returns "". It is independent of App.UseAccessLog: access records carry an empty request_id when only access logging is installed. UseRequestID accepts zero configs for the defaults or one config; it panics for more than one config, when called twice, or after the App was prepared or shut down.

func (*App) UseSuccessRenderer added in v0.19.0

func (app *App) UseSuccessRenderer(r SuccessRenderer)

UseSuccessRenderer installs the renderer that shapes successful responses sent through Context.Render. It is opt-in: with no renderer installed, Render falls back to plain JSON and the framework imposes no response envelope. The renderer receives a RenderInfo (status, data, and any RenderOption side channels) and returns the body to encode — nil writes the data plain; the framework owns the write, mirroring App.UseErrorRenderer's shape-only contract. The raw Response helpers (Response.JSON and friends) are never routed through it, so an enterprise envelope ({code,message,data}, HAL, JSON:API, …) applies only where handlers opt in via Render.

Like UseErrorRenderer, it may be a DI-resolved method registered after Finalize, it is installed at most once, and it panics for a nil renderer, a second call, or a call after the App was prepared or shut down.

type BindError added in v0.4.0

type BindError struct {
	// Reason is the machine-readable failure category.
	Reason BindErrorReason

	// Field is the affected field path (e.g. "age", "user.address.city",
	// or a form/query parameter name). Empty for body-level failures
	// (syntax, empty_body, trailing_data).
	Field string

	// Expected is the human-readable expected type for type_mismatch
	// ("integer", "number", "string", "boolean", "array", "object").
	// Empty for other reasons.
	Expected string

	// Offset is the byte offset in the JSON body where the failure was
	// detected. Zero when unknown or not applicable (XML, form, query).
	Offset int64

	// Internal is the underlying decoder error. It is logged at debug level
	// (credo: client error) and never exposed to the client.
	Internal error
}

BindError is the typed decode error returned by Request.BindBody and Request.BindQuery. The error pipeline classifies it as 400 Bad Request with a default error body whose single violations[] entry mirrors the validation output shape: Field, Code (the Reason), Message, and Params.

Handlers normally return it unchanged. To branch on it, use errors.AsType[*credo.BindError](err).

A request body exceeding the configured size limit is not a BindError: it keeps its dedicated 413 Request Entity Too Large classification.

func (*BindError) Error added in v0.4.0

func (e *BindError) Error() string

Error implements the error interface.

func (*BindError) HTTPStatus added in v0.4.0

func (e *BindError) HTTPStatus() int

HTTPStatus returns 400 Bad Request. The error pipeline classifies BindError directly; this method keeps the status visible to custom renderers and middleware that only understand the HTTPStatus interface.

func (*BindError) Unwrap added in v0.4.0

func (e *BindError) Unwrap() error

Unwrap returns the underlying decoder error, supporting errors.Is/As.

type BindErrorReason added in v0.4.0

type BindErrorReason string

BindErrorReason identifies why Request.BindBody or Request.BindQuery failed to decode the request payload into the target struct.

Reason values are stable machine-readable identifiers: each appears as the Code of the violations[] entry in the default response and as the scoped i18n lookup reason.

const (
	// BindReasonSyntax reports a malformed payload: invalid JSON, XML, or
	// form encoding, including a truncated body.
	BindReasonSyntax BindErrorReason = "syntax"

	// BindReasonTypeMismatch reports a value whose type does not match the
	// target field — a JSON string where a number is expected, or a
	// non-numeric form/query value for an integer field.
	BindReasonTypeMismatch BindErrorReason = "type_mismatch"

	// BindReasonInvalidValue reports a value of the right shape that failed
	// semantic conversion: rejected by the target field's
	// [encoding.TextUnmarshaler] or a semantic unmarshal step (an
	// unparseable time.Time, netip.Addr, custom type, or numeric overflow).
	BindReasonInvalidValue BindErrorReason = "invalid_value"

	// BindReasonEmptyBody reports a request without a body where one is
	// required.
	BindReasonEmptyBody BindErrorReason = "empty_body"

	// BindReasonTrailingData reports extra content after the first JSON
	// value in the request body. BindBody accepts exactly one JSON value.
	BindReasonTrailingData BindErrorReason = "trailing_data"

	// BindReasonDuplicateField reports a JSON object member that appears
	// more than once (including case-variant repeats of the same field).
	BindReasonDuplicateField BindErrorReason = "duplicate_field"

	// BindReasonUnknownField reports a JSON object member that does not
	// correspond to any field of the target. Only produced under strict
	// bodies ([WithStrictBodies] or server.strict_bodies); by default
	// unknown members are ignored.
	BindReasonUnknownField BindErrorReason = "unknown_field"
)

type CompressConfig added in v0.19.0

type CompressConfig struct {
	// Skipper excludes a request from compression. It is evaluated once, on
	// the original request as received (method, path and headers), before
	// routing and before any user middleware; route data and the response
	// are not available to it. A rewrite does not re-evaluate it. nil
	// compresses every eligible request.
	Skipper func(ctx *Context) bool

	// Level is the gzip/deflate compression level, 1–9. Zero selects 5.
	// Level 0 (no compression) cannot be requested: leave the feature out or
	// use Skipper.
	Level int

	// Types limits compression to specific response content types. Exact
	// values ("application/json") and wildcards ("text/*") are supported.
	// Default: common textual MIME types.
	Types []string
}

CompressConfig configures the response compression feature installed by App.UseCompress. The zero value selects every default.

type Context

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

Context is the request-scoped struct that holds the Request, Response, matched Route, logger, and a key-value store.

Context is pooled via sync.Pool for zero-allocation request handling. Access fields only through methods (not direct field access) to ensure pool safety. Because it is pooled, Context deliberately does not implement context.Context; call Context.Context to obtain the request's context.Context for context-taking APIs.

Context is Credo's HTTP request context. Lifecycle hooks such as App.OnStart and App.OnShutdown receive a standard context.Context, not *Context.

func NewContext

func NewContext(w http.ResponseWriter, r *http.Request) *Context

NewContext creates a new Context wrapping the given ResponseWriter and Request. This is primarily useful for testing error handlers and middleware.

func (*Context) AddLogAttrs

func (c *Context) AddLogAttrs(args ...any)

AddLogAttrs adds attributes to the request-scoped logger for the remainder of this request. The new logger is derived from Context.Logger, so enrichment added earlier — such as the request_id attribute — is preserved by construction. args are key-value pairs as accepted by slog.Logger.With:

ctx.AddLogAttrs("tenant_id", tenantID)

Prefer this over Context.SetLogger when the goal is to add attributes rather than replace the logger. Calling it with no arguments is a no-op.

func (*Context) Context

func (c *Context) Context() context.Context

Context returns the underlying request's context.Context. Use it for APIs that take a context.Context — database queries, downstream requests, or transaction propagation through a data-store API:

err := db.InTx(ctx.Context(), func(txCtx context.Context) error {
	return service.Update(txCtx)
})

The returned context is canceled when the request completes. For background work that must outlive the request, detach it with context.WithoutCancel:

bg := context.WithoutCancel(ctx.Context())
go process(bg)

Context deliberately does NOT implement context.Context itself: it is pooled (sync.Pool) and reused across requests, so retaining a *Context as a long-lived context.Context would observe a later request's state. Context hands back the real, non-pooled request context instead.

func (*Context) Get

func (c *Context) Get(key string) any

Get retrieves a value from the request-scoped store.

func (*Context) GetUser

func (c *Context) GetUser[T any]() (T, bool)

GetUser returns the authenticated user previously stored under type T and reports whether one was present. The type argument is required because it cannot be inferred from a return value: ctx.GetUser[*User](). Retrieve with the same T that was stored — a value set under a concrete type is not visible through an interface type parameter.

func (*Context) HasRequestLogger

func (c *Context) HasRequestLogger() bool

HasRequestLogger reports whether Context.Logger returns (or, for the request ID tier's deferred enrichment, will return on first use) a request-scoped logger — one set by the request ID feature (App.UseRequestID), Context.SetLogger, or Context.AddLogAttrs. It does not inspect the logger's attributes.

The framework's log emitters (access log, panic recovery) use it as a convention-based signal: under the derivation contract documented on Context.SetLogger, a request-scoped logger is assumed to already carry request_id, so the emitters skip adding the attribute explicitly.

func (*Context) HasRoute

func (c *Context) HasRoute() bool

HasRoute reports whether a route matched for this request. Returns false inside custom 404/405 status handlers where no route exists. Use this to guard Context.Route calls in middleware that may run on unmatched-request paths:

if ctx.HasRoute() {
    val, _ := ctx.Route().LookupMeta("permission")
}

func (*Context) IsRewriting

func (c *Context) IsRewriting() bool

IsRewriting reports whether this context has a pending internal rewrite. This can be useful in middleware to avoid side-effects (e.g., response writing) when the handler signaled a re-dispatch.

func (*Context) Locale

func (c *Context) Locale() string

Locale returns the request's locale (e.g., "en", "tr"). It is resolved on first use — by Locale itself, Context.T, Context.TPlural or the error pipeline's message translation — through I18nConfig.Detect and memoized for the request: later header changes, authentication or rewrites do not change it. An empty or unresolvable detection selects the configured default language. Returns an empty string, without invoking the detector, when i18n is not configured.

func (*Context) Logger

func (c *Context) Logger() *slog.Logger

Logger returns the request-scoped logger. Falls back through the chain: request logger → app logger → nop logger.

func (*Context) OriginalPath

func (c *Context) OriginalPath() string

OriginalPath returns the request path as received from the client in its wire form (percent-encoding preserved), before any rewriting (middleware.Rewrite or ctx.Rewrite). Useful for access logging, analytics, and debugging.

func (*Context) Render

func (c *Context) Render(status int, data any, opts ...RenderOption) error

Render sends a successful response through the app's SuccessRenderer when one is installed via App.UseSuccessRenderer, letting an application apply a uniform response envelope at a single seam. With no renderer installed (the default), it writes data as plain JSON via Response.JSON, imposes no envelope, and any RenderOption side channels are dropped.

With a renderer installed, the renderer returns the body shape and the framework writes it with status and the application JSON profile; a nil return writes data plain, and a renderer that committed the response itself keeps full control (see SuccessRenderer for the contract). Body-forbidding statuses (1xx, 204, 304) always render status-only.

Render is the only success path that consults the renderer: the raw helpers (Response.JSON, Response.XML, Response.Text, Response.Blob, and the streaming writers) stay un-intercepted, so handlers serving webhooks, health probes, or third-party-dictated shapes can always bypass the envelope by calling them directly.

func (*Context) Request

func (c *Context) Request() *Request

Request returns the Request for this context.

func (*Context) RequestID

func (c *Context) RequestID() string

RequestID returns the current request ID. It returns an empty string when request ID middleware is not active.

func (*Context) RequireUser

func (c *Context) RequireUser[T any]() (T, error)

RequireUser is like Context.GetUser but returns a handler-ready error when the user is absent: ErrUnauthorized wrapping ErrUserMissing. The framework renders it as 401, and errors.Is(err, ErrUserMissing) still reports the cause. The type argument is required: ctx.RequireUser[*User]().

func (*Context) Response

func (c *Context) Response() *Response

Response returns the Response for this context.

func (*Context) Rewrite

func (c *Context) Rewrite(path string) error

Rewrite triggers an internal re-dispatch to the given path. The client is unaware of the rewrite (no HTTP redirect is sent). The original request path is preserved in OriginalPath(). The matched host scope does not change.

Rewrite must be the last call in a handler — the return value must be returned directly:

return ctx.Rewrite("/new-path")

A maximum of 10 rewrites per request is enforced to prevent loops. If exceeded, an error is returned and the request fails with 500.

func (*Context) Route

func (c *Context) Route() *Route

Route returns the matched Route (for accessing Meta, Name, BuildURI). Returns nil when no route matched (e.g., inside custom 404/405 handlers). Use Context.HasRoute to guard against nil before calling Route methods.

func (*Context) Set

func (c *Context) Set(key string, val any)

Set stores a key-value pair in the request-scoped store.

func (*Context) SetLogger

func (c *Context) SetLogger(l *slog.Logger)

SetLogger replaces the request-scoped logger for the remainder of this request. It is the wholesale-replacement API: reach for it when the logger itself must change (different handler, level, or destination). To add request-bound attributes, prefer Context.AddLogAttrs.

When replacing, derive the new logger from Context.Logger so existing enrichment is preserved:

ctx.SetLogger(ctx.Logger().With("tenant_id", tenantID))

A logger built from scratch silently drops attributes added earlier — including the request_id added by the request ID tier — from all subsequent log output (handler logs and the access log). The framework cannot detect this; if you must start from a fresh logger, re-attach the ID via Context.RequestID.

The logger is cleared automatically when the request completes.

func (*Context) SetUser

func (c *Context) SetUser[T any](user T)

SetUser stores the authenticated user on the request, keyed by its type T. It is the framework's blessed way to attach a principal: T is inferred from the argument, so call sites read ctx.SetUser(user) with no explicit type argument. Storing a different type adds a separate slot; storing the same type again replaces the previous value.

github.com/credo-go/credo/auth.Middleware calls this after a successful Authenticate; custom middleware may call it directly.

func (*Context) T

func (c *Context) T(key string, data ...map[string]any) string

T translates a message key using the detected locale. If i18n is not configured or the key is not found, the key itself is returned. Optional data map provides template variables for the message.

T always renders the message's Other plural form; for count-based plural selection use Context.TPlural.

func (*Context) TPlural

func (c *Context) TPlural(key string, count any, data ...map[string]any) string

TPlural translates a message key using the detected locale, rendering the CLDR cardinal plural form selected for count. count may be any integer kind, an integral float, or a decimal string ("1.5") when visible fraction digits matter. The count value is exposed to the template as {{.count}}.

// messages.json: "items": {"one": "{{.count}} item", "other": "{{.count}} items"}
ctx.TPlural("items", 1) // "1 item"
ctx.TPlural("items", 5) // "5 items"

If i18n is not configured or the key is not found, the key itself is returned. When count cannot be interpreted as a number, the Other form is rendered.

type DIPanicError added in v0.19.0

type DIPanicError = di.PanicError

DIPanicError is the recovered panic of a DI constructor or of a Shutdowner invoked during teardown. Its fields are the failing registered Type, the Phase (construction, normal shutdown, or late cleanup), the original panic Value and the Stack captured on the panicking goroutine. When Value is an error it is also reachable through errors.Is/As. Obtain it with errors.AsType[*credo.DIPanicError], including through a DIShutdownError or a joined App shutdown error.

A constructor panic is terminal: the constructor is never retried, and the first, concurrent and later resolvers of that type all receive the same DIPanicError. App.MustResolve panics with the error as its value.

type DIPanicPhase added in v0.19.0

type DIPanicPhase = di.PanicPhase

DIPanicPhase identifies where a DIPanicError was recovered.

type DIShutdownEntry added in v0.19.0

type DIShutdownEntry = di.ShutdownEntry

DIShutdownEntry is one registration's record inside a DIShutdownError: its Type, State, the Err of a failed or panicked attempt, the Blockers that kept a blocked entry from retiring, and the Duration of a completed attempt or the elapsed time of an incomplete one.

type DIShutdownError added in v0.19.0

type DIShutdownError = di.ShutdownError

DIShutdownError reports a failed or incomplete DI teardown. It is returned by App.Shutdown (joined with other teardown errors) whenever a singleton's Shutdown failed, panicked, or could not be attempted or completed within the shutdown budget. Obtain it with errors.AsType[*credo.DIShutdownError].

Entries holds one DIShutdownEntry per registration in registration order, including the successful and diagnostic ones, and Cause is the shutdown context error when the budget ran out. The report is an immutable snapshot: a Shutdown call returning after the boundary, or a late-cleanup result, is logged and never written back. Unwrap exposes the callback failures and the context cause so errors.Is and errors.As traverse the report.

type DIShutdownState added in v0.19.0

type DIShutdownState = di.ShutdownState

DIShutdownState is the per-registration outcome recorded in a DIShutdownEntry.

type DecompressConfig added in v0.19.0

type DecompressConfig struct {
	// Skipper excludes a request from decompression, leaving its body and
	// Content-Encoding untouched — the way to keep raw bodies for routes
	// such as signed webhooks. It is evaluated once, on the original request
	// as received (method, path and headers), before routing and before any
	// user middleware; route and authentication data are not available to
	// it, and a rewrite does not re-evaluate it. nil decompresses every
	// encoded request. A skipped encoded body is still rejected by BindBody
	// with 415.
	Skipper func(ctx *Context) bool

	// MaxBytes bounds the decompressed body in bytes. Reading past it fails
	// with the framework's 413 Request Entity Too Large classification, the
	// same way the server-wide max_body_bytes limit surfaces. Zero selects
	// [DefaultDecompressMaxBytes]; a negative value is a configuration error
	// and panics at registration.
	MaxBytes int64
}

DecompressConfig configures the request-body decompression feature installed by App.UseDecompress. The zero value selects every default.

type ErrorBody added in v0.14.0

type ErrorBody struct {
	// Code is the stable machine-readable error identity.
	Code string `json:"code"`

	// Message is the resolved human-readable message.
	Message string `json:"message"`

	// Details carries optional structured, client-safe detail.
	Details any `json:"details,omitempty"`

	// Violations lists rule violations behind the error: field-scoped
	// validation failures and document-scoped bind (body-contract) failures.
	// A bind entry's Field may be empty when the violation concerns the whole
	// body (for example a JSON syntax error).
	Violations []validation.ValidationError `json:"violations,omitempty"`
}

ErrorBody is the error object nested inside ErrorResponse.

type ErrorInfo

type ErrorInfo struct {
	// Err is the original error returned by the handler.
	// Use [errors.As] / [errors.Is] for type-specific behavior
	// (e.g., Sentry reporting, extracting metadata for custom headers).
	Err error

	// Status is the HTTP status the framework writes. A renderer may change it
	// before returning; invalid values fail closed to a generic 500 response.
	Status int

	// Code is the stable machine-readable error identity.
	Code string

	// MessageKey is the exact effective i18n key before resolution. It is the
	// explicit key carried by the error, the configured resolver result, or the
	// bare Code when neither exists.
	MessageKey string

	// Message is the resolved human-readable message, including safe fallback.
	Message string

	// Details is optional structured, client-safe application detail.
	Details any

	// Violations contains validation or binding rule violations. Validation
	// entries are field-scoped; a bind entry's Field may be empty when the
	// violation concerns the whole body (for example a JSON syntax error).
	Violations []validation.ValidationError
}

ErrorInfo carries the original error and framework-normalized presentation data to the ErrorRenderer. It is request-scoped and must not be retained after the renderer returns.

type ErrorRenderer

type ErrorRenderer func(ctx *Context, info *ErrorInfo) any

ErrorRenderer shapes the body of an error response given a classified ErrorInfo. The framework owns everything around that shape: error classification, logging, the status code (info.Status — mutate it before returning to change it), the Content-Type, HEAD handling, and committed-response guards.

The return value is the response body. A non-nil value is encoded as JSON with the application's JSON profile and written with info.Status; returning nil renders the default Credo error envelope instead. Either way the renderer never writes the response itself in the common case — it only decides the shape.

The renderer is called for all HTTP methods including HEAD, so it can set response headers (e.g., Retry-After, WWW-Authenticate) on the Context before returning; for HEAD the framework then sends a status-only response and the returned body is discarded. Setting headers and returning nil is the way to decorate the default error body.

For the rare response that is not JSON at all, the renderer may commit the response itself through the Context (as any handler could); once Response.Committed reports true the return value is ignored.

Register a custom renderer with App.UseErrorRenderer.

func RFC9457ErrorRenderer added in v0.12.0

func RFC9457ErrorRenderer(cfgs ...RFC9457Config) ErrorRenderer

RFC9457ErrorRenderer returns an ErrorRenderer that projects Credo's normalized error model into RFC 9457 Problem Details. The response uses application/problem+json; Code, Details, and Violations are extension members.

type ErrorResponse added in v0.12.0

type ErrorResponse struct {
	Success bool      `json:"success"`
	Error   ErrorBody `json:"error"`
}

ErrorResponse is Credo's default JSON error envelope. The top level carries only the success discriminator; everything about the error itself lives in the nested ErrorBody object, mirroring how a success envelope pairs "success" with a data payload.

type Group

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

Group is the user-facing route group for configuring routes with a shared prefix, middleware, and metadata. It is also the node of the group parent chain: route metadata (LookupMeta) and group middleware are both resolved by walking this chain — metadata dynamically at request time, middleware once at compile time.

func (*Group) DELETE

func (g *Group) DELETE(pattern string, h Handler) *Route

DELETE registers a DELETE route in this group. Panics under the same conditions as App.GET.

func (*Group) File

func (g *Group) File(urlPath string, fsys fs.FS, name string, cfgs ...StaticConfig) *Route

File registers a single GET route that serves one named file from fsys within this group. See App.File for full documentation.

func (*Group) GET

func (g *Group) GET(pattern string, h Handler) *Route

GET registers a GET route in this group. A matching HEAD handler is registered automatically; subsequent calls to Route.Middleware and Route.SetMeta on the returned route apply to HEAD as well, so HEAD requests can never silently bypass auth, rate limiting, or meta-driven middleware. Panics under the same conditions as App.GET.

func (*Group) Group

func (g *Group) Group(prefix string) *Group

Group creates a nested sub-group with the given prefix. The sub-group inherits this group's metadata and middleware through the parent chain.

func (*Group) HEAD

func (g *Group) HEAD(pattern string, h Handler) *Route

HEAD registers a HEAD route in this group. Panics under the same conditions as App.GET.

func (*Group) Middleware

func (g *Group) Middleware(middlewares ...Middleware) *Group

Middleware appends group-level middlewares. They apply to every route of this group and its sub-groups, regardless of whether the route was registered before or after this call: per-route chains are assembled from the group parent chain when the app compiles (first request or Run), mirroring how route metadata is resolved via Route.LookupMeta. Must be called before the server starts; panics if called after compile. Returns *Group for chaining.

func (*Group) OPTIONS

func (g *Group) OPTIONS(pattern string, h Handler) *Route

OPTIONS registers an OPTIONS route in this group. Panics under the same conditions as App.GET.

func (*Group) PATCH

func (g *Group) PATCH(pattern string, h Handler) *Route

PATCH registers a PATCH route in this group. Panics under the same conditions as App.GET.

func (*Group) POST

func (g *Group) POST(pattern string, h Handler) *Route

POST registers a POST route in this group. Panics under the same conditions as App.GET.

func (*Group) PUT

func (g *Group) PUT(pattern string, h Handler) *Route

PUT registers a PUT route in this group. Panics under the same conditions as App.GET.

func (*Group) QUERY added in v0.13.0

func (g *Group) QUERY(pattern string, h Handler) *Route

QUERY registers an RFC 10008 safe, idempotent query route whose query representation travels in the request body. Request.BindBody provides the standard decode-and-validate path. QUERY requests must include Content-Type. Panics under the same conditions as App.GET.

func (*Group) RemoveMeta

func (g *Group) RemoveMeta(key string)

RemoveMeta removes a metadata key from this group. Must be called before the server starts; panics if called after compile.

func (*Group) SetMeta

func (g *Group) SetMeta(key string, val any)

SetMeta sets a metadata key-value pair for this group. All routes within the group inherit this metadata. Must be called before the server starts; panics if called after compile.

func (*Group) Static

func (g *Group) Static(prefix string, fsys fs.FS, cfgs ...StaticConfig) *StaticRoute

Static registers routes that serve files from fsys under the given URL prefix within this group. See App.Static for full documentation.

type HTTPError

type HTTPError struct {
	// Status is the HTTP status code.
	Status int `json:"status"`

	// Code is the stable machine-readable error code, rendered as the RFC
	// 7807 "code" extension member. [NewHTTPError] always materializes it:
	// either the explicit code argument or the frozen default for the status
	// (for example 404 → "not_found", unknown 499 → "http_499"). It must
	// satisfy the machine-code grammar ^[a-z0-9]+(_[a-z0-9]+)*$.
	Code string `json:"code,omitempty"`

	// MessageKey is an optional i18n message key or literal fallback message
	// used only for title presentation; it never contributes to Code. Attach
	// one with [HTTPError.WithMessageKey].
	MessageKey string `json:"message_key,omitempty"`

	// Details carries optional structured, client-safe detail rendered as the
	// default error response's "details" member. It is encoded with the
	// application's JSON profile; never place secrets or internal state here.
	Details any `json:"-"`

	// Internal is the underlying error. It is never exposed to the client;
	// the error pipeline logs it, at Error for a 5xx status and at Debug below.
	Internal error `json:"-"`
}

HTTPError represents an HTTP error carrying a status and a stable machine-readable code, with an optional presentation message key.

Code is the primary wire identity; MessageKey only affects the human-readable message. When MessageKey is empty, the message resolves through the configured scoped resolver or bare Code lookup, then the safe built-in/status fallback. When MessageKey is set, the existing three-level chain applies:

  1. i18n bundle lookup — if a translation exists for MessageKey, use it
  2. builtInMessages lookup — if MessageKey matches a built-in key, use it
  3. MessageKey itself — used as-is (works for literal messages)

func NewHTTPError

func NewHTTPError(status int, code ...string) *HTTPError

NewHTTPError creates a new HTTPError with the given status and optional stable machine-readable code. With no code argument, the frozen default code for the status is used (404 → "not_found"; a status outside the frozen table yields "http_<status>"). MessageKey starts empty; attach a presentation key with HTTPError.WithMessageKey.

The status domain is the full valid range 100..999, not just the error classes: NewHTTPError(200) is accepted and defaults to code "ok". Restricting construction to 4xx/5xx semantics is the caller's concern.

Misuse panics — this is a developer invariant violation, not a runtime condition: a status outside 100..999, more than one code argument, or a code that fails the machine-code grammar ^[a-z0-9]+(_[a-z0-9]+)*$ (which includes an explicitly empty code). During a request, built-in recovery converts the panic into a generic 500 without publishing the invalid value.

func (*HTTPError) Error

func (e *HTTPError) Error() string

Error implements the error interface. The diagnostic order is status, code, key, internal; empty segments are omitted.

func (*HTTPError) HTTPStatus

func (e *HTTPError) HTTPStatus() int

HTTPStatus returns the HTTP status code carried by the error.

func (*HTTPError) Unwrap

func (e *HTTPError) Unwrap() error

Unwrap returns the internal error, supporting errors.Is/As.

func (*HTTPError) WithDetails added in v0.10.0

func (e *HTTPError) WithDetails(v any) *HTTPError

WithDetails returns a copy of the error with structured client-safe detail attached; it is rendered as the default response's "details" member.

func (*HTTPError) WithInternal

func (e *HTTPError) WithInternal(err error) *HTTPError

WithInternal returns a copy of the error with the internal error set.

func (*HTTPError) WithMessageKey added in v0.11.0

func (e *HTTPError) WithMessageKey(key string) *HTTPError

WithMessageKey returns a copy of the error with the presentation message key set. The key affects only the human-readable title (resolved through the i18n bundle → builtInMessages → literal chain); the machine-readable Code is untouched.

type Handler

type Handler func(ctx *Context) error

Handler is the Credo handler signature. Handlers return an error for centralized error handling via the App's error handling pipeline.

type HealthCheckFunc

type HealthCheckFunc func(ctx context.Context) error

HealthCheckFunc adapts a plain function to HealthChecker.

func (HealthCheckFunc) Check

func (f HealthCheckFunc) Check(ctx context.Context) error

Check implements HealthChecker.

type HealthChecker

type HealthChecker interface {
	Check(ctx context.Context) error // nil = healthy
}

HealthChecker checks the health of a component.

type HealthConfig

type HealthConfig struct {
	// Enabled controls whether health endpoints are registered.
	// nil (default) = true.
	Enabled *bool

	// Liveness controls whether the liveness endpoint is registered.
	// nil (default) = true.
	Liveness *bool

	// Readiness controls whether the readiness endpoint is registered.
	// nil (default) = true.
	Readiness *bool

	// LivenessPath is the path for the liveness endpoint. Default: "/health".
	LivenessPath string

	// ReadinessPath is the path for the readiness endpoint. Default: "/ready".
	ReadinessPath string

	// CheckTimeout is the enforced per-check timeout. Default: 5s. A callback
	// that ignores cancellation cannot delay the response beyond this budget;
	// overlapping requests share its still-running execution until it exits.
	CheckTimeout time.Duration

	// ExposeErrors includes check error strings in the readiness response
	// body. Default false: failing checks report only "down" and the error
	// is written to the application log instead — error strings often
	// carry internal details (hostnames, connection targets) that should
	// not reach unauthenticated probe endpoints.
	ExposeErrors bool

	// Group registers health routes on a specific route group instead of the
	// app root. Routes inherit the group's prefix and middleware chain.
	// nil (default) = routes are registered on the app root.
	Group *Group

	// LogRequests includes health and readiness probe requests in the access
	// log. Default false: probe traffic (such as Kubernetes liveness and
	// readiness checks) is silenced via the MetaAccessLog route meta to keep
	// logs clean. The endpoints remain registered and responsive either way.
	//
	// The meta is set at the route level, so LogRequests:true re-enables
	// logging even when the health routes sit under a group that silenced
	// access logging (a route-level value overrides its group's).
	LogRequests bool
}

HealthConfig configures the health check endpoints.

type I18nConfig

type I18nConfig struct {
	// Dir is the filesystem path to the locale directory (e.g., "locales/").
	// Mutually exclusive with DirFS.
	Dir string

	// DirFS is an embed.FS or any fs.FS providing locale files.
	// Mutually exclusive with Dir.
	DirFS fs.FS

	// Default is the default language tag string (e.g., "en").
	// Falls back to "en" if empty.
	Default string

	// Detect returns the request's preferred language. It runs lazily, on the
	// first [Context.Locale] or translation access of a request (the error
	// pipeline's message translation included), and its result is memoized
	// for that request; requests that never touch locale or translation do
	// not invoke it. It sees the request state at that moment — headers, the
	// route when already matched, the user when authentication already ran —
	// and later changes do not re-run it. An empty or unresolvable result
	// selects Default. Calling Locale or a translation from inside Detect is
	// programming misuse and panics; a panic in Detect caches Default for the
	// request and is handled like any request panic. nil reads the
	// Accept-Language header.
	Detect func(ctx *Context) string

	// Messages provides exact message keys for the effective Default language.
	// It may be the only message source or a base overridden by Dir/DirFS.
	Messages I18nMessages

	// Fields provides display names for exact technical field paths in the
	// effective Default language. A message source is still required.
	Fields I18nFields

	// ResolveMessageKey optionally maps framework error, validation, and bind
	// codes to application-owned exact message keys. Credo never adds a prefix.
	ResolveMessageKey MessageKeyResolver
}

I18nConfig configures internationalization for the application.

type I18nFields added in v0.12.0

type I18nFields map[string]string

I18nFields maps exact technical field paths to display names for the effective default language. UseI18n copies the map during setup.

type I18nMessages added in v0.12.0

type I18nMessages map[string]string

I18nMessages maps exact message keys to string templates for the effective default language. UseI18n compiles and copies the map during setup.

type Infra

type Infra struct {

	// Logger is a structured logger, scoped to the service.
	Logger *slog.Logger
	// contains filtered or unexported fields
}

Infra carries framework infrastructure to services. The container produces it automatically when detected as a constructor parameter (Model 1).

Logger is scoped per service: each service receives a logger with a "service" attribute set to the service type name.

When no logger is configured via WithLogger, Infra falls back to a default stderr logger. Future infrastructure (metrics, tracing) will be added as new fields by the observability release.

For testing, construct Infra directly:

infra := credo.Infra{Logger: slog.New(slog.NewTextHandler(os.Stderr, nil))}

type MessageKeyResolver added in v0.12.0

type MessageKeyResolver func(MessageRef) string

MessageKeyResolver maps a message scope and machine code to an exact i18n key. Returning an empty key is a programming error and fails closed through the error pipeline. With no resolver Credo uses the bare code as the key.

type MessageRef added in v0.12.0

type MessageRef struct {
	Scope MessageScope
	Code  string
}

MessageRef is passed to a MessageKeyResolver when a value carries no explicit MessageKey.

type MessageScope added in v0.12.0

type MessageScope uint8

MessageScope identifies the presentation context of a machine code. It lets applications choose their own i18n namespaces without Credo adding hidden prefixes to codes.

const (
	MessageScopeError MessageScope = iota
	MessageScopeValidation
	MessageScopeBind
)

type Middleware

type Middleware func(next Handler) Handler

Middleware is the single middleware type used throughout Credo. All middleware — global, group, and route level — uses this signature.

func WrapStdMiddleware

func WrapStdMiddleware(m StdMiddleware) Middleware

WrapStdMiddleware converts stdlib middleware (func(http.Handler) http.Handler) into a Credo Middleware (func(Handler) Handler). This allows using any existing Go community middleware with Credo's unified middleware stack.

app.GlobalMiddleware(credo.WrapStdMiddleware(corsMiddleware))

A response the middleware writes by itself, without calling next, is the request's response. Its body is the middleware's own — it passes neither the error pipeline nor a SuccessRenderer — but it is recorded: once the middleware returns, Response.Status, Response.Size and Response.Committed report it, the access record observes it, and an error that surfaces afterwards is logged instead of being written after it. A connection the middleware hijacks is reported by Response.Hijacked.

type Option

type Option func(*appOptions)

Option configures the App during construction.

func WithAddr

func WithAddr(host string, port int) Option

WithAddr sets the listen address directly (for testing or programmatic use).

func WithDebug

func WithDebug() Option

WithDebug enables development-mode warnings. When active, the framework logs warnings for common mistakes such as binding a struct that does not implement validation.Validatable. Can also be enabled via the server.debug config key.

func WithHTTPRedirect

func WithHTTPRedirect(addr string) Option

WithHTTPRedirect runs a second, plaintext listener on addr (for example ":80") whose only job is to permanently redirect every request to its HTTPS equivalent. GET and HEAD receive 301; other methods receive 308 so the method (and body) are preserved — matching the framework's trailing-slash redirect convention. The redirect target reuses the request host with the TLS server's port (omitted when it is 443).

TLS must be configured (via WithTLSFiles, WithTLSConfig, or server.tls.*); otherwise startup fails fast at preflight, since redirecting to an HTTPS server that does not exist makes no sense. The redirect listener starts and drains with the main server, and a runtime failure of the redirect listener tears the whole app down — the same as a failure of the main listener — so a requested redirect can never silently die while the app reports healthy. It does not apply to ServeContext, which serves the caller's listener as-is.

func WithHTTPServer added in v0.8.0

func WithHTTPServer(fn func(*http.Server)) Option

WithHTTPServer registers a callback that receives the http.Server the framework built, so the whole standard-library surface stays reachable without Credo growing an option per field. It runs once, at construction time, after every framework-set field — timeouts, MaxHeaderBytes, MaxHeaderValueCount, and the ErrorLog bridge — so the callback has the last word on all of them, config keys included:

credo.WithHTTPServer(func(s *http.Server) {
	s.Protocols = new(http.Protocols)
	s.Protocols.SetHTTP1(true)
	s.Protocols.SetUnencryptedHTTP2(true) // H2C
	s.ConnState = metrics.TrackConnState
})

Three fields are framework-owned and re-imposed after the callback returns, because the lifecycle depends on them: Handler (always the App), Addr (the listener is bound from it), and TLSConfig. TLS is configured through WithTLSConfig or WithTLSFiles, which resolve later at startup; a TLSConfig set here is either overwritten by those or, with no Credo TLS source configured, ignored — it never silently upgrades a plaintext server.

The server's lifecycle methods (Serve, ServeTLS, Shutdown, Close, RegisterOnShutdown) belong to the framework: the callback must not call them or retain the pointer past its return. The WithHTTPRedirect listener is a separate, fixed-function server and is deliberately not passed to the callback. A nil callback is a no-op.

func WithJSONOptions added in v0.7.0

func WithJSONOptions(opts ...jsonv2.Options) Option

WithJSONOptions overrides Credo's JSON response encoding profile. The given options are applied after the framework defaults, so each one overrides that axis and leaves the rest intact:

// keep encoding/json v1's null for nil slices
credo.WithJSONOptions(jsonv2.FormatNilSliceAsNull(true))

// re-enable HTML escaping of < > &
credo.WithJSONOptions(jsontext.EscapeForHTML(true))

// full legacy mode, byte-identical to encoding/json v1 except for the
// trailing newline, which v1's Encoder added and json/v2 never writes
credo.WithJSONOptions(jsonv1.DefaultOptionsV1())

The profile applies to Response.JSON (and therefore to Context.Render's fallback) and to framework-owned default error bodies, except that error bodies always sort map keys — they are a framework contract. Decoding is not affected: request-body policy is WithStrictBodies.

Repeated calls accumulate in order. Construction-time only; there is no config-file key, since options are Go values.

func WithLogger

func WithLogger(l *slog.Logger) Option

WithLogger sets the application-level logger. Each service receives a scoped copy with a "service" attribute. If not set, the framework default logger (a text handler writing to stderr) is used, so access and request logging are on by default without any configuration.

func WithMaxBodyBytes

func WithMaxBodyBytes(n int64) Option

WithMaxBodyBytes sets the maximum number of bytes read from any request body. Requests whose body exceeds the limit receive 413 Request Entity Too Large. A negative value disables the limit; zero (the default) applies a 4 MiB cap.

func WithRawConfig

func WithRawConfig(rc RawConfig) Option

WithRawConfig sets the RawConfig for the application. When provided, New does not auto-load configuration from files, .env, or environment variables; the given RawConfig is registered in DI as-is. The framework still reads its internal server settings from the "server" key when present.

Use this option when config has already been loaded explicitly, for example via config.Load(config.WithFiles(...)) or config.LoadBytes(...).

func WithRecoverConfig added in v0.19.0

func WithRecoverConfig(cfg RecoverConfig) Option

WithRecoverConfig customizes the built-in panic recovery: its logger, whether a stack trace is captured, and the stack size. It does not enable recovery — recovery is on by default — and it never re-enables it: WithoutRecover disables recovery regardless of the order the two options are given in.

func WithRedirectTrailingSlash

func WithRedirectTrailingSlash(enabled bool) Option

WithRedirectTrailingSlash controls whether the router automatically redirects requests whose trailing slash variant matches a registered route. GET/HEAD requests receive 301; other methods receive 308 (preserving the method). Defaults to true when not set.

func WithReloadTimeout added in v0.5.0

func WithReloadTimeout(d time.Duration) Option

WithReloadTimeout sets the context budget for reloads triggered by SIGHUP under Run: re-reading configuration, notifying App.OnConfigChange subscribers, and running App.OnReload hooks must complete within it. Zero (the default) applies a 30s budget. A programmatic App.Reload call ignores this and honours the caller's context instead. Can also be set via the server.reload_timeout config key.

func WithShutdownTimeout

func WithShutdownTimeout(d time.Duration) Option

WithShutdownTimeout sets the graceful-shutdown drain budget used by the signal-aware Run and by context-cancellation-triggered RunContext. The parallel HTTP/OnDrain phase, DI singleton cleanup, and OnShutdown hooks must complete within this single absolute budget. Zero (the default) applies a 30s budget. An explicit Shutdown(ctx) call ignores this and honours the caller's context deadline instead. Can also be set via the server.shutdown_timeout config key.

func WithStrictBodies added in v0.6.0

func WithStrictBodies() Option

WithStrictBodies makes Request.BindBody reject JSON payloads that carry object members not mapping to any field of the target, returning a 400 BindError with reason BindReasonUnknownField. The default is lenient: unknown members are ignored, which is the right posture for public APIs whose clients must tolerate server-side additions. Enable strict bodies when client and server ship together and a misspelled member should surface as an error rather than silently drop. Can also be enabled via the server.strict_bodies config key; the option wins over the key.

Only JSON decoding is affected; XML and form binding are unchanged.

func WithTLSConfig

func WithTLSConfig(cfg *tls.Config) Option

WithTLSConfig configures HTTPS from a fully-formed *tls.Config, exposing the complete crypto/tls surface: mutual TLS, SNI via GetCertificate, custom minimum version and cipher suites, ALPN, and hot certificate reload. It has the highest TLS precedence — when set, WithTLSFiles and the server.tls.* keys are ignored.

The config must carry a certificate source (Certificates, GetCertificate, or GetConfigForClient), validated at startup. It is cloned before use, so the framework never mutates the caller's value and later caller mutations do not affect the running server. Passing a nil config is a configuration error caught at startup: an explicit WithTLSConfig(nil) does not silently fall back to WithTLSFiles, the config keys, or plaintext.

func WithTLSFiles

func WithTLSFiles(certFile, keyFile string) Option

WithTLSFiles configures HTTPS by loading the certificate and private key from the given PEM file paths. When set, Run and RunContext serve TLS; the key pair is loaded and validated at startup (before the server accepts connections), so a missing file or mismatched pair fails fast. The same paths may instead come from the server.tls.cert_file / server.tls.key_file config keys — WithTLSFiles takes precedence over those. It is in turn shadowed by WithTLSConfig.

Calling it with an empty cert or key path is a configuration error caught at startup: an explicit but empty WithTLSFiles does not silently fall back to the config keys or to plaintext. For conditional TLS, omit the option entirely rather than passing empty strings.

The pair is served through GetCertificate backed by an atomic pointer, so every App.Reload (SIGHUP under Run) re-reads the same two paths and swaps the pair in for new handshakes; a failed re-read keeps the current pair and is reported through the reload error. Open connections are never affected.

This option performs no I/O; the files are read when the server starts.

func WithTrustedProxies

func WithTrustedProxies(cidrs ...string) Option

WithTrustedProxies configures the CIDR ranges from which forwarded headers such as X-Forwarded-For, X-Forwarded-Proto, and X-Real-IP are trusted. Requests whose immediate peer is outside this list ignore forwarded headers.

Pass no entries (the default) to disable proxy-header trust entirely. Invalid CIDR entries cause New to return an error.

func WithoutRecover

func WithoutRecover() Option

WithoutRecover disables the built-in panic recovery that covers the whole request execution. By default, Credo recovers from panics in feature selectors, middleware, handlers, renderers and access-log filters, logs the stack trace, and returns 500 Internal Server Error. It wins over WithRecoverConfig regardless of option order.

Disable this if you provide your own recovery mechanism or need panics to propagate (e.g., in tests). Request cleanup — compressor finalization, access-log observation and Context release — still runs while the panic propagates.

func WithoutReloadSignals added in v0.15.0

func WithoutReloadSignals() Option

WithoutReloadSignals disables signal-triggered reloads under App.Run: SIGHUP no longer triggers App.Reload. The signal is still captured — and ignored with an Info log line — so a stray SIGHUP (logrotate postrotate, a forgotten systemd reload directive, a closing terminal) can never terminate the process; raw Unix signal disposition, where an unhandled SIGHUP kills the process, remains available via App.RunContext or App.ServeContext, which install no signal handlers at all. Programmatic App.Reload calls are unaffected. On platforms without reload signals (Windows) this option is a no-op. SIGINT/SIGTERM shutdown handling under Run is unchanged.

type ProblemDetails

type ProblemDetails struct {
	// Type is a URI reference that identifies the problem type.
	// Defaults to "about:blank" per RFC 9457.
	Type string `json:"type"`

	// Title is a short, human-readable summary of the problem type.
	Title string `json:"title"`

	// Status is the HTTP status code.
	Status int `json:"status"`

	// Detail is a human-readable explanation specific to this occurrence.
	Detail string `json:"detail,omitempty"`

	// Instance is a URI reference that identifies the specific occurrence.
	Instance string `json:"instance,omitempty"`

	// Code is a machine-readable error-code extension member.
	// Populated from [HTTPError.Code]; the classification default comes from
	// the frozen statusToCode table. Never derived from the message key.
	Code string `json:"code,omitempty"`

	// Details carries structured, client-safe detail about this occurrence as
	// an extension member. Populated from [HTTPError.Details].
	Details any `json:"details,omitempty"`

	// Violations holds validation or binding rule violations (if any) as an
	// extension member, matching the default envelope's vocabulary.
	Violations []validation.ValidationError `json:"violations,omitempty"`
}

ProblemDetails represents an RFC 9457 Problem Details response. It is used by the opt-in RFC9457ErrorRenderer; Credo's default envelope is ErrorResponse.

func NewProblemDetails

func NewProblemDetails(status int, title string) *ProblemDetails

NewProblemDetails creates a new ProblemDetails with the given status and title. Type defaults to "about:blank" per RFC 9457.

type RFC9457Config added in v0.12.0

type RFC9457Config struct {
	// ResolveType optionally returns the problem type URI for a normalized error.
	// Empty means "about:blank". The callback is request-scoped and must not
	// retain info.
	ResolveType func(info *ErrorInfo) string
}

RFC9457Config configures RFC9457ErrorRenderer.

type RawConfig

type RawConfig = config.RawConfig

RawConfig is an alias for config.RawConfig. The interface is defined in the config package to avoid circular imports between the root package and the config package. This alias ensures that credo.RawConfig continues to work seamlessly throughout the framework.

RawConfig provides low-level access to the merged configuration. This is a bootstrap mechanism — application code should use typed config structs injected via DI instead of calling RawConfig directly.

Unmarshal decodes both struct sections and primitive values:

var port int
rawCfg.Unmarshal("server.port", &port)

var dbCfg DatabaseConfig
rawCfg.Unmarshal("databases.default", &dbCfg)

type RecoverConfig added in v0.19.0

type RecoverConfig struct {
	// Logger receives the "panic recovered" record. nil logs through the
	// request-scoped logger (ctx.Logger()), which already carries the request
	// ID when that feature is installed; a dedicated logger gets the request
	// ID as an explicit attribute instead.
	Logger *slog.Logger

	// DisableStackTrace omits the stack trace from the panic record.
	DisableStackTrace bool

	// StackSize is the maximum number of bytes of stack trace captured.
	// Zero (or negative) selects 8192.
	StackSize int
}

RecoverConfig customizes the built-in panic recovery. Recovery is on by default and covers the whole request execution — feature selectors, user middleware, handlers, renderers and access-log filters. Configure it with WithRecoverConfig; disable it with WithoutRecover, which wins regardless of option order. The zero value selects every default.

type RenderInfo added in v0.10.0

type RenderInfo struct {
	// Status is the HTTP status code the framework writes.
	Status int

	// Data is the payload the handler passed to [Context.Render].
	Data any

	// MessageKey is an optional i18n message key attached via
	// [RenderMessageKey]; empty when none was given. A renderer whose
	// envelope carries a human-readable message resolves it, typically
	// through [Context.T].
	MessageKey string

	// Meta is optional structured metadata attached via [RenderMeta]
	// (pagination, request echo, …); nil when none was given.
	Meta any
}

RenderInfo carries a successful response's status, payload, and optional envelope side channels to the SuccessRenderer.

type RenderOption added in v0.10.0

type RenderOption func(*RenderInfo)

RenderOption attaches an optional envelope side channel — a message key or metadata — to a Context.Render call; see RenderMessageKey and RenderMeta. (Named Render*, not With*: the With prefix is reserved for construction-time App options.)

func RenderMessageKey added in v0.10.0

func RenderMessageKey(key string) RenderOption

RenderMessageKey attaches an i18n message key to the RenderInfo a SuccessRenderer receives. With no renderer installed it has no effect — the side channel only exists for an envelope to consume.

func RenderMeta added in v0.10.0

func RenderMeta(v any) RenderOption

RenderMeta attaches structured metadata (pagination, request echo, …) to the RenderInfo a SuccessRenderer receives. With no renderer installed it has no effect — the side channel only exists for an envelope to consume.

type Request

type Request struct {
	*http.Request
	// contains filtered or unexported fields
}

Request wraps *http.Request and provides request-side helpers: route parameters, query parameter shortcuts, and body/query binding.

func NewRequest

func NewRequest(r *http.Request) *Request

NewRequest creates a new Request wrapping the given *http.Request.

func (*Request) BindBody

func (r *Request) BindBody(target any) error

BindBody decodes the request body into target based on the Content-Type header. Supported content types:

  • application/json (default when Content-Type is absent)
  • application/xml, text/xml
  • application/x-www-form-urlencoded (uses "form" struct tags)
  • multipart/form-data (uses "form" struct tags, including file fields)

JSON bodies are decoded with encoding/json/v2 under strict semantics: exactly one JSON value is accepted — any content after it (a second document, or trailing garbage) fails the bind with BindReasonTrailingData (trailing whitespace is allowed) — and object members must be unique: a repeated member (including a case-variant repeat) fails with BindReasonDuplicateField. Member names keep v1's case-insensitive matching against struct fields.

If target implements validation.Validatable, Validate() is called automatically after successful decoding ("parse, don't validate").

Decode failures return a *BindError carrying a typed reason (400 Bad Request via the error pipeline). Exceeding the body-size limit returns 413 Request Entity Too Large; an unrecognized content type returns 415 Unsupported Media Type.

func (*Request) BindQuery

func (r *Request) BindQuery(target any) error

BindQuery decodes URL query parameters into target using `query:"name"` struct tags. If target implements validation.Validatable, Validate() is called automatically after successful decoding ("parse, don't validate").

In debug mode, a warning is logged when the target does not implement Validatable.

func (*Request) PathValue

func (r *Request) PathValue(name string) string

PathValue returns the route parameter for name, falling back to the embedded request's http.Request.PathValue. Prefer Request.RouteParam in new code.

This shadow exists for stdlib muscle memory: Credo's dispatcher does not populate the embedded *http.Request's path values with a route's parameters (doing so would cost an allocation per request for data Request.RouteParam already serves), so without it ctx.Request().PathValue("id") would silently return "". The raw embedded request — as seen by middleware via WrapStdMiddleware — still carries none of them.

The fallback is also how an app mounted with App.Mount reads the parameters of its mount prefix: Mount("/t/{tenant}", child) hands the child a request whose path values hold the tenant, so in the child PathValue("tenant") returns it, while Request.RouteParam knows the child's own route parameters only.

func (*Request) QueryParam

func (r *Request) QueryParam(name string) string

QueryParam returns a query string parameter value by name. Returns "" if not present.

func (*Request) RealIP

func (r *Request) RealIP() string

RealIP returns the address of the original client.

When the immediate peer RemoteAddr is trusted, RealIP walks the proxy chain — the RFC 7239 Forwarded header's for= parameters first, then X-Forwarded-For — from right to left, skipping trusted proxy hops and returning the first untrusted address. If neither yields a usable value, X-Real-IP is used. If the peer is untrusted, all forwarded headers are ignored.

The returned value is an IP address only for parseable addresses. If RemoteAddr itself is unparseable, RealIP falls back to RemoteAddr verbatim.

func (*Request) RouteParam

func (r *Request) RouteParam(name string) string

RouteParam returns the URL parameter value for name — a path parameter such as {id}, or, for host-scoped routes, a host parameter. It returns "" when the parameter is not present.

RouteParam is the preferred accessor for single values; it never allocates:

id := ctx.Request().RouteParam("id")

The value is percent-decoded exactly once by the router ("a%2Fb" arrives as "a/b" inside one segment); do not unescape it again.

In an app mounted with App.Mount, RouteParam returns that app's own route parameters. The parameters of the mount prefix are path values of the request: read them with Request.PathValue.

Unlike the map returned by Request.RouteParams, the returned string is safe to retain after the request completes.

func (*Request) RouteParams

func (r *Request) RouteParams() map[string]string

RouteParams returns all URL parameter key-value pairs. For host-scoped routes, host params and path params share the same namespace.

The map is a read-only view, materialized lazily on first call: writes to it are not seen by Request.RouteParam. It is owned by the framework and recycled after the request completes — do not retain it or read it from another goroutine after the handler returns. For single values, prefer Request.RouteParam.

func (*Request) Scheme

func (r *Request) Scheme() string

Scheme reports the scheme the original client used: "http" or "https".

If the request arrived over TLS directly, Scheme returns "https". Otherwise, forwarded scheme headers are considered only when the immediate peer RemoteAddr is configured as a trusted proxy on the App. Untrusted peers cannot influence the result.

Only "http" and "https" are returned. Invalid forwarded header values fall back to the underlying transport.

type RequestIDConfig added in v0.19.0

type RequestIDConfig struct {
	// Header is the HTTP header the request ID is read from and written to.
	// Default: "X-Request-Id". Credential headers (Authorization,
	// Proxy-Authorization, Cookie) are rejected at registration because the
	// value is echoed on the response and attached to log records.
	Header string

	// Generator creates a request ID when the client did not send a valid
	// one. Default: crypto/rand.Text (a 128-bit base32 string).
	Generator func() string

	// Limit is the maximum accepted length of an incoming request ID; longer
	// values are discarded and a new ID is generated, so a client cannot
	// inject arbitrarily large values. Default: 64.
	Limit int
}

RequestIDConfig configures the request ID feature installed by App.UseRequestID. The zero value selects every default.

type Response

type Response struct {
	http.ResponseWriter
	// contains filtered or unexported fields
}

Response wraps http.ResponseWriter to track the response status code, byte count, and whether headers have been committed.

The embedded ResponseWriter may be swapped by middleware that wraps the writer (e.g., compression); the tracking state is framework-owned and exposed read-only via Response.Status, Response.Size, and Response.Committed, and Response.Hijacked. A response written by a stdlib middleware adapted with WrapStdMiddleware never passes the Response; the state takes it over when that middleware returns.

func NewResponse

func NewResponse(w http.ResponseWriter) *Response

NewResponse creates a new Response wrapping the given http.ResponseWriter.

func (*Response) Blob

func (r *Response) Blob(code int, contentType string, b []byte) error

Blob sends a binary response with the given content type. Body-forbidding status codes (1xx, 204, 304) write the status only; see Response.JSON.

func (*Response) Committed

func (r *Response) Committed() bool

Committed reports whether the response header has been written. Once committed, the status code and headers can no longer change.

func (*Response) Flush

func (r *Response) Flush()

Flush sends any buffered data to the client.

func (*Response) HTML

func (r *Response) HTML(code int, html string) error

HTML sends an HTML response with the given status code. Body-forbidding status codes (1xx, 204, 304) write the status only; see Response.JSON.

func (*Response) Hijack

func (r *Response) Hijack() (net.Conn, *bufio.ReadWriter, error)

Hijack implements the http.Hijacker interface. It resolves nested Unwrap chains and marks the response only after the effective Hijack call succeeds.

func (*Response) Hijacked

func (r *Response) Hijacked() bool

Hijacked reports whether the underlying HTTP connection was successfully taken over: through Response.Hijack, or by a stdlib middleware adapted with WrapStdMiddleware, whose hijack is recorded when the middleware returns. Writing status or Upgrade headers alone does not mark the response as hijacked. Code that reaches a raw underlying writer some other way — through Response.Unwrap, for example — and hijacks it cannot be observed by this state.

func (*Response) JSON

func (r *Response) JSON(code int, v any) error

JSON sends a JSON response with the given status code, encoded with the application's JSON profile (see WithJSONOptions): deterministic map ordering, nanosecond durations, v2 defaults for everything else — nil slices and maps as [] and {}, no HTML escaping, no trailing newline.

For status codes that forbid a response body (1xx, 204, 304), JSON — like every body-writing helper — skips both the body and the Content-Type header and writes the status line only, exactly as Response.NoContent would. Writing a body to such a status would otherwise fail inside net/http ("http: request method or response status code does not allow body") after the header is already committed, surfacing as a spurious error the pipeline can no longer render.

func (*Response) NoContent

func (r *Response) NoContent(code int) error

NoContent sends a response with no body.

func (*Response) ReadFrom added in v0.19.0

func (r *Response) ReadFrom(src io.Reader) (int64, error)

ReadFrom copies src into the response body until EOF, implementing io.ReaderFrom for io.Copy and Response.Stream. When the underlying writer implements io.ReaderFrom (net/http's HTTP/1.1 writer does, copying through a pooled buffer and using sendfile or splice on a plaintext TCP connection when src is a regular file or a socket) the copy is delegated to it. Otherwise — a compressing or other wrapping writer, HTTP/2 — the copy runs through a pooled 32 KiB buffer, so a Reader-only source never costs a buffer allocation per response.

The bytes the writer accepted count toward Response.Size; a hijacked response returns http.ErrHijacked. The commit follows Response.Write: nothing is committed before the first byte, so a source that fails before producing any output leaves the response uncommitted and the handler's error still renders as an error response; the first byte commits 200 when no status was written. On an uncommitted response the first buffer's worth of src therefore always goes through Response.Write before the copy is delegated (as net/http itself does before switching to sendfile): the commit is recorded here, ahead of any later failure in src, so a source that panics after its first bytes leaves a committed response whose status and access record are the 200 already on the wire. The delegated part is counted the same way: the bytes the writer read from src before a panic it also wrote, so Response.Size still reports what the client received.

func (*Response) Redirect

func (r *Response) Redirect(code int, url string) error

Redirect sends an HTTP redirect response.

func (*Response) Reset

func (r *Response) Reset(w http.ResponseWriter)

Reset resets the response for reuse from the pool.

func (*Response) SetCookie

func (r *Response) SetCookie(cookie *http.Cookie)

SetCookie adds a Set-Cookie header to the response.

func (*Response) Size

func (r *Response) Size() int64

Size returns the number of bytes written to the response body.

func (*Response) Status

func (r *Response) Status() int

Status returns the HTTP status code written, or 0 when the response has not been committed yet.

func (*Response) Stream

func (r *Response) Stream(code int, contentType string, rd io.Reader) error

Stream sends a streaming response from the given reader. A reader that implements io.WriterTo writes itself; any other reader is copied through Response.ReadFrom, which copies through a pooled buffer and delegates the remainder of a large source to the underlying writer instead of allocating a buffer per call. Body-forbidding status codes (1xx, 204, 304) write the status only and never read from rd; see Response.JSON.

func (*Response) String

func (r *Response) String() string

String implements fmt.Stringer for debugging.

func (*Response) Text

func (r *Response) Text(code int, s string) error

Text sends a plain text response with the given status code. Named Text (not String) to avoid conflict with the fmt.Stringer interface. Body-forbidding status codes (1xx, 204, 304) write the status only; see Response.JSON.

func (*Response) Unwrap

func (r *Response) Unwrap() http.ResponseWriter

Unwrap returns the underlying http.ResponseWriter.

func (*Response) Write

func (r *Response) Write(b []byte) (int, error)

Write writes the data to the connection as part of an HTTP reply. If WriteHeader has not been called, it calls WriteHeader(200).

func (*Response) WriteHeader

func (r *Response) WriteHeader(code int)

WriteHeader sends an HTTP response header with the given status code. It can only be called once per response.

func (*Response) WriteString added in v0.10.0

func (r *Response) WriteString(s string) (int, error)

WriteString writes the string to the connection as part of an HTTP reply, implementing io.StringWriter. When the underlying ResponseWriter also implements it (net/http's does), the string is written without the []byte(s) copy that io.WriteString would otherwise allocate per call. If WriteHeader has not been called, it calls WriteHeader(200).

func (*Response) XML

func (r *Response) XML(code int, v any) error

XML sends an XML response with the given status code. Body-forbidding status codes (1xx, 204, 304) write the status only; see Response.JSON.

type Route

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

Route represents a registered route with its handler, metadata, and fluent configuration methods.

func (*Route) BuildURI

func (r *Route) BuildURI(params ...string) (string, error)

BuildURI generates a URI from the route pattern by replacing named parameters with the provided values in order. Values are decoded parameter values, exactly what Request.RouteParam reports for the generated URI: each is checked against its regex constraint and percent-encoded for one path segment with url.PathEscape, so "a/b" for a single-segment parameter yields "a%2Fb" while a catch-all value keeps its slashes as separators and escapes each segment. Static text of the pattern is written verbatim.

It returns an error when a value is missing or empty, fails its constraint, when too many values are provided, or when the route pattern is malformed.

uri, err := route.BuildURI("42") // "/users/42"

func (*Route) BuildURL

func (r *Route) BuildURL(params ...string) (string, error)

BuildURL generates a full URL by combining the route's host pattern and path pattern, replacing parameters with the provided values in order. Host pattern parameters are consumed first, then path parameters. A host value fills exactly one label: it must be non-empty, consist of letters, digits, hyphens and underscores, and satisfy the label's regex constraint; host labels are never percent-encoded. Path values follow Route.BuildURI. It returns an error when a value is missing or invalid, when too many values are provided, or when either pattern is malformed. Wildcard host patterns cannot generate concrete URLs and return an error.

For host-scoped routes:

// Host: {tenant}.myapp.com, Path: /users/{id}
url, err := route.BuildURL("acme", "42") // "acme.myapp.com/users/42"

For default (non-host-scoped) routes, BuildURL is equivalent to Route.BuildURI:

url, err := route.BuildURL("42") // "/users/42"

func (*Route) GetHost

func (r *Route) GetHost() string

GetHost returns the host pattern for host-scoped routes. Returns an empty string for routes on the default mux.

func (*Route) GetMethod

func (r *Route) GetMethod() string

GetMethod returns the HTTP method.

func (*Route) GetName

func (r *Route) GetName() string

GetName returns the route name.

func (*Route) GetPattern

func (r *Route) GetPattern() string

GetPattern returns the URL pattern.

func (*Route) LookupMeta

func (r *Route) LookupMeta(key string) (any, bool)

LookupMeta searches for a metadata value by key, traversing the parent chain (route → group → parent group → ...) until found.

func (*Route) Middleware

func (r *Route) Middleware(m ...Middleware) *Route

Middleware appends one or more per-route middlewares. Must be called before the server starts; panics if called after compile. Returns the Route for fluent chaining.

For GET routes with an auto-generated HEAD twin, middleware is also appended to the twin so that HEAD requests run the same chain as GET — otherwise auth, rate limiting, and other middleware could be silently bypassed via HEAD.

func (*Route) Name

func (r *Route) Name(name string) *Route

Name sets the route name for URL generation. Route names must be unique within the App. Duplicate names panic. Must be called before the server starts; panics if called after compile. Returns the Route for fluent chaining.

func (*Route) SetMeta

func (r *Route) SetMeta(key string, val any) *Route

SetMeta attaches a key-value metadata pair to this route. Must be called before the server starts; panics if called after compile. Returns the Route for fluent chaining.

For GET routes with an auto-generated HEAD twin, the value is also set on the twin so middleware reading meta sees identical values regardless of which method was used.

type RouteContext

type RouteContext = radix.RouteContext

RouteContext is the routing context type used by the radix tree. Re-exported from internal/radix so consumers can reference this type without importing internal packages.

type RouteInfo

type RouteInfo struct {
	// Method is the HTTP method of a normal route; empty for a mount (see Methods).
	Method string

	// Methods is the sorted set of forwarded HTTP methods for a mount
	// (CONNECT and TRACE excluded); nil for a normal route.
	Methods []string

	// Pattern is the user-facing URL pattern; for a mount it is the cleaned
	// mount prefix.
	Pattern string

	// Host is the host pattern, or empty for the default mux.
	Host string

	// Name is the route name, or empty if unnamed.
	Name string

	// Meta is the resolved, shallow-copied route metadata; nil if none.
	Meta map[string]any

	// Kind reports whether this entry describes a normal route or a mount.
	Kind RouteKind

	// AutoHead reports whether this is an auto-generated HEAD twin of a GET route.
	AutoHead bool

	// RegisteredAt is the user call site ("file:line") that registered this
	// route or mount, or "" when the framework could not capture it. Intended
	// for startup route dumps and /debug/routes diagnostics.
	RegisteredAt string
}

RouteInfo holds introspection data about a registered route or mount.

A normal route (Kind == RouteKindRoute) carries a single Method and a nil Methods. A mount (Kind == RouteKindMount) leaves Method empty and lists its sorted forwarded method set in Methods, because one mount answers every forwarded method at its prefix.

Meta is the fully resolved route metadata (route ← group ← app) as a shallow copy: callers may read it and add or delete keys without affecting framework state, but the values are read-only by convention — mutating a slice, map, or pointer stored in Meta mutates the live route metadata. Meta is nil when neither the route nor any ancestor group defines metadata.

type RouteKind

type RouteKind string

RouteKind distinguishes a normal registered route from a mounted handler prefix in introspection output.

const (
	// RouteKindRoute is a normal route registered via GET/POST/Static and friends.
	RouteKindRoute RouteKind = "route"

	// RouteKindMount is a handler subtree attached via [App.Mount]. Only its
	// prefix and forwarded method set are exposed in introspection, never its
	// internal routes.
	RouteKindMount RouteKind = "mount"
)

type Routes

type Routes interface {
	// Routes returns a slice of RouteInfo for all registered routes.
	Routes() []RouteInfo
}

Routes describes the interface for route introspection.

type Shutdowner

type Shutdowner interface {
	Shutdown(ctx context.Context) error
}

Shutdowner is implemented by services that need cleanup on shutdown. The context carries a deadline from the application's graceful shutdown timeout; implementations should respect ctx.Done() for timely cleanup.

type StaticCacheContext

type StaticCacheContext struct {
	// RequestPath is the path received from the client before internal rewrites.
	RequestPath string

	// FilePath is the resolved slash-separated path inside the fs.FS.
	// Directory listings use the resolved directory path.
	FilePath string

	// FileName is the base name of the served file, or the generated listing name.
	FileName string

	// IsHTML reports whether the response is an HTML entry point or listing.
	IsHTML bool
}

StaticCacheContext describes a successfully resolved static response for cache policy decisions.

type StaticConfig

type StaticConfig struct {
	// Index is the file served for directory requests.
	// Default: "index.html".
	Index string

	// Browse enables directory listing when a directory has no index file.
	// SPA takes precedence: if SPA is also true and the request qualifies
	// as an SPA candidate, the sibling-or-root fallback runs instead of
	// the directory listing.
	// Default: false (returns 404 for directories without index).
	Browse bool

	// SPA enables single-page application mode for routes that target a
	// page rather than an asset (GET or HEAD with no dot in the last path
	// segment). For these requests, the resolver prefers, in order:
	//
	//   File branch (path does not exist):
	//     1. <path>.html sibling (e.g. /admin/users → admin/users.html)
	//     2. root index
	//
	//   Directory branch (path is an existing directory):
	//     1. <dir>/<Index> (the directory's own index file)
	//     2. <dir>.html sibling (e.g. /reports/ → reports.html)
	//     3. root index
	//
	// Requests with a dot in the last segment (app.js, style.css) skip
	// the fallback entirely and return 404 when missing.
	// Default: false.
	SPA bool

	// Download sets Content-Disposition to "attachment" on all responses,
	// prompting the browser to download instead of display inline.
	// Default: false.
	Download bool

	// CacheControl decides the Cache-Control header for each successfully
	// served response (status below 400). It receives the resolved cache
	// context and returns the full header value; returning "" writes no
	// header. Nil disables Cache-Control entirely.
	//
	// The hook runs once per response — including 206 partial-content
	// responses — and never for error statuses. It should be pure and
	// deterministic.
	//
	// Presets cover the common policies:
	//
	//	credo.StaticConfig{CacheControl: credo.StaticCacheMaxAge(24 * time.Hour)}
	//	credo.StaticConfig{CacheControl: credo.StaticCacheImmutableAssets(365 * 24 * time.Hour)}
	//
	// Anything else is a few lines of code — e.g. SvelteKit-style builds
	// where only one directory holds content-hashed assets:
	//
	//	CacheControl: func(c credo.StaticCacheContext) string {
	//		if strings.HasPrefix(c.FilePath, "_app/immutable/") {
	//			return "public, max-age=31536000, immutable"
	//		}
	//		return "no-cache, must-revalidate"
	//	}
	CacheControl func(StaticCacheContext) string
}

StaticConfig configures static file serving for App.Static, Group.Static, App.File, and Group.File.

For App.File and Group.File, only Download and CacheControl apply. Setting Browse, SPA, or a non-empty Index panics at registration time.

Credo can only guard headers written before its Response.WriteHeader call. Reverse proxies or CDNs that add Cache-Control after Credo must be configured separately.

type StaticRoute

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

StaticRoute represents a static file serving endpoint. It wraps the two internal GET routes created by App.Static (catch-all + exact prefix match) and proxies fluent configuration to both. HEAD requests automatically observe the same middleware and route metadata as GET, so calling StaticRoute.Middleware or StaticRoute.SetMeta keeps the two methods in sync without any extra bookkeeping.

func (*StaticRoute) BuildURI

func (sr *StaticRoute) BuildURI(filePath ...string) string

BuildURI returns the URL path for a file within this static endpoint.

sr.BuildURI("css/app.css")  → "/static/css/app.css"
sr.BuildURI("")             → "/static/"
sr.BuildURI()               → "/static/"

func (*StaticRoute) Middleware

func (sr *StaticRoute) Middleware(m ...Middleware) *StaticRoute

Middleware appends middleware to both the catch-all and exact-match GET routes. HEAD requests automatically run the same chain as GET, so auth, rate limiting, and other header-mutating middleware can never be silently bypassed via a HEAD request.

Must be called before the server starts; panics if called after compile.

func (*StaticRoute) Name

func (sr *StaticRoute) Name(name string) *StaticRoute

Name sets the route name on the primary (catch-all) route only. Route names must be unique; the exact-match route remains unnamed. Use StaticRoute.BuildURI for URL generation instead of Route.BuildURI, which requires the catch-all parameter explicitly.

Must be called before the server starts; panics if called after compile.

func (*StaticRoute) SetMeta

func (sr *StaticRoute) SetMeta(key string, val any) *StaticRoute

SetMeta sets metadata on both the catch-all and exact-match GET routes. HEAD requests automatically see the same metadata as GET, so middleware reading route meta returns consistent values for both methods and both registration patterns.

Must be called before the server starts; panics if called after compile.

type StdMiddleware

type StdMiddleware = func(http.Handler) http.Handler

StdMiddleware is a stdlib-compatible middleware signature. Use WrapStdMiddleware to convert stdlib middleware into Middleware.

type SuccessRenderer

type SuccessRenderer func(ctx *Context, info RenderInfo) any

SuccessRenderer shapes the body of a successful response sent through Context.Render. It is the success-side mirror of ErrorRenderer and follows the same shape-only contract: the renderer returns the body, and the framework owns the write — status (info.Status), the application JSON profile, and the body-forbidding status rule (1xx/204/304 render status-only) all apply centrally.

The return value is the response body. A non-nil value is encoded as JSON with the application's JSON profile and written with info.Status; returning nil writes info.Data plain — the escape for a renderer that envelopes selectively. For the rare response that is not JSON at all, the renderer may commit the response itself through the Context (as any handler could); once Response.Committed reports true the return value is ignored.

It is opt-in, never installed by default, and consulted only through Context.Render — the raw Response helpers (Response.JSON, Response.XML, Response.Text, Response.Blob, and the streaming writers) stay un-intercepted so webhooks, health probes, and third-party response shapes always bypass any house envelope. A renderer that panics is treated like a handler panic and caught by the built-in recovery layer.

Register a custom renderer with App.UseSuccessRenderer. The single RenderInfo seam is also the integration point a future typed-endpoint layer would route its typed result through, so one envelope policy covers both.

type WalkFunc

type WalkFunc func(method, pattern string) error

WalkFunc is the callback for Walk. It receives the method and pattern of each registered route. Return a non-nil error to stop walking.

type WalkRoutesFunc

type WalkRoutesFunc func(ri RouteInfo) error

WalkRoutesFunc is the callback for WalkRoutes. It receives the full RouteInfo including the host pattern. Return a non-nil error to stop walking.

Directories

Path Synopsis
Package auth provides authentication infrastructure for Credo applications.
Package auth provides authentication infrastructure for Credo applications.
Package config provides struct-centric configuration loading with deterministic merge order.
Package config provides struct-centric configuration loading with deterministic merge order.
Package fault defines transport-neutral semantic error kinds.
Package fault defines transport-neutral semantic error kinds.
Package httpclient provides outbound HTTP for Credo applications: timeout, retry with backoff, structured logging, and W3C trace context propagation — composed as an http.RoundTripper chain on a plain *http.Client.
Package httpclient provides outbound HTTP for Credo applications: timeout, retry with backoff, structured logging, and W3C trace context propagation — composed as an http.RoundTripper chain on a plain *http.Client.
internal
di
Adapted from github.com/samber/do (MIT License).
Adapted from github.com/samber/do (MIT License).
faultstatus
Package faultstatus contains Credo's default HTTP transport policy for transport-neutral semantic faults.
Package faultstatus contains Credo's default HTTP transport policy for transport-neutral semantic faults.
health
Package health defines stable, bounded health probes and the module-internal seam through which integration packages contribute store checks to the root health engine.
Package health defines stable, bounded health probes and the module-internal seam through which integration packages contribute store checks to the root health engine.
httpheader
Package httpheader provides comma-separated header token helpers shared by the root package's HTTP features and the middleware package.
Package httpheader provides comma-separated header token helpers shared by the root package's HTTP features and the middleware package.
httpwriter
Package httpwriter resolves optional net/http response-writer capabilities through bounded Unwrap chains.
Package httpwriter resolves optional net/http response-writer capabilities through bounded Unwrap chains.
i18n
Package i18n is the internal message lookup engine for the Credo framework.
Package i18n is the internal message lookup engine for the Credo framework.
observe
Package observe provides shared helpers for request observation code such as access logging and panic recovery.
Package observe provides shared helpers for request observation code such as access logging and panic recovery.
origin
Package origin parses and matches web origins (scheme://host[:port]) with one strict grammar shared by every Credo surface that accepts an allow-list of origins (the WebSocket adapter, CORS).
Package origin parses and matches web origins (scheme://host[:port]) with one strict grammar shared by every Credo surface that accepts an allow-list of origins (the WebSocket adapter, CORS).
pattern
Package pattern owns Credo's route-pattern grammar: {name} matches one path segment, {name:regex} constrains it, and {name...} captures the rest of the path.
Package pattern owns Credo's route-pattern grammar: {name} matches one path segment, {name:regex} constrains it, and {name...} captures the rest of the path.
radix
Package radix implements a compressed radix tree (Patricia trie) for HTTP request routing.
Package radix implements a compressed radix tree (Patricia trie) for HTTP request routing.
requestid
Package requestid provides shared request ID helpers used by Credo's built-in and configurable middleware implementations.
Package requestid provides shared request ID helpers used by Credo's built-in and configurable middleware implementations.
resourceid
Package resourceid canonicalizes stable resource identity tokens shared by lifecycle-aware framework integrations.
Package resourceid canonicalizes stable resource identity tokens shared by lifecycle-aware framework integrations.
static
Package static implements Credo's static file serving: sanitization of the router-decoded path, index and SPA fallbacks, directory listings, Range-aware file delivery, and status-aware Cache-Control.
Package static implements Credo's static file serving: sanitization of the router-decoded path, index and SPA fallbacks, directory listings, Range-aware file delivery, and status-aware Cache-Control.
wirepath
Package wirepath defines the canonical form in which the router compares a request path with registered patterns.
Package wirepath defines the canonical form in which the router compares a request path with registered patterns.
Package middleware provides built-in HTTP middleware for the Credo framework.
Package middleware provides built-in HTTP middleware for the Credo framework.
Package pagination provides generic, ORM-agnostic types and utilities for paginated API responses.
Package pagination provides generic, ORM-agnostic types and utilities for paginated API responses.
scripts
releasegate command
Command releasegate verifies Credo's lockstep multi-module release contract.
Command releasegate verifies Credo's lockstep multi-module release contract.
Package store provides universal data access contracts for the Credo framework.
Package store provides universal data access contracts for the Credo framework.
sqldb module
Package testutil provides helpers for testing Credo applications: building a hermetic test App, overriding dependencies with fakes, injecting config, and asserting on structured log output.
Package testutil provides helpers for testing Credo applications: building a hermetic test App, overriding dependencies with fakes, injecting config, and asserting on structured log output.
Package validation provides a programmatic, type-safe validation engine using Go generics.
Package validation provides a programmatic, type-safe validation engine using Go generics.
Package websocket provides Credo's server-side WebSocket adapter over the exact-pinned github.com/coder/websocket protocol engine.
Package websocket provides Credo's server-side WebSocket adapter over the exact-pinned github.com/coder/websocket protocol engine.
Package worker provides background task management for Credo applications.
Package worker provides background task management for Credo applications.

Jump to

Keyboard shortcuts

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