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 with no reflection on the request path.
The package is large because the App's subsystems live in it: routing, dependency injection, components and their lifecycle, health, i18n, the HTTP features and the workers. The sections below group the overview by subject; the symbol index stays alphabetical, so ContinuousConfig, RestartPolicy, Schedule and ScheduledConfig stand apart from Worker, WorkerInfo and Workers.
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:
- With<X> / Without<X> — construction-time Option values passed to New. They only set configuration and perform no I/O, so their order does not matter (e.g. WithLogger, WithRecoverConfig, WithoutRecover).
- Use<X> — post-construction setup that installs a subsystem or an HTTP feature once: it registers routes, an engine or a feature configuration and performs no I/O; what reads the outside world, such as locale files, runs in the start phase. It panics on developer misuse — duplicate or late registration, invalid config (e.g. App.UseHealth, App.UseI18n, App.UseAccessLog, App.UseErrorRenderer).
- Set<X> / Remove<X> — imperative mutators for a single request-state or route value (e.g. Context.SetUser, Route.SetMeta).
- On<X> — registers a lifecycle hook (e.g. App.OnStart, App.OnStop, App.OnReload).
- Add<X> — adds one of several registrations of a kind (e.g. App.AddLivenessCheck, App.AddReadinessCheck).
- A noun accessor returns the App's one registry of a subsystem that takes many registrations (e.g. App.Workers).
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).
Dependency Injection ¶
The container binds one singleton per type. App.Provide registers a constructor, whose first result type is the binding's type and whose parameters are resolved from the container — Infra first by convention, produced by the container for the binding it builds; App.ProvideValue binds a value built by the application, such as an opened database; App.Alias binds an interface to a bound type, and App.BindMany adds a type to the collection App.ResolveAll returns. Nothing is built at registration. The first App.Resolve, App.ResolveAll, App.MustResolve or App.MustResolveAll finalizes the container — validating the whole graph — and then resolves; App.Finalize is an optional early check that returns the same report as an error. App.Has probes a binding without building or finalizing anything. Framework components are never bound automatically: the one framework-made binding is RawConfig.
RegistrationOption values shape a registration: Override replaces an earlier binding or alias of the type, Borrowed binds a value whose start and teardown its owner keeps, CloseOnShutdown makes a value with Close a component, ComponentName names a component in logs, /ready and lifecycle errors — it is not a DI key — Ingress places a component in the ingress tier, and OptionalReadiness reports its readiness entry without letting it gate readiness. Each call checks the options it accepts and panics on the others.
Components ¶
A Component is a value whose teardown the App owns: a binding whose type shows Shutdown, or a value or constructor handed to App.Manage, which adds a component that is not a binding. The binding's type, not its value, plans the rest: a component whose type shows Starter is started before its dependants, one that shows Readier enters /ready, and one that implements IngressComponent is placed in the ingress tier. A type that hides its value's Start, Ready or ingress tier is refused. The App starts components in dependency order before it accepts requests and shuts them down after their consumers in two tiers (Tier): the ingress tier with the HTTP drain, then the internal tier. Holders that share a resource (ResourceIdentifier) start it once and tear it down once, through its holder of record. Every call the App makes on a component carries its scoped Infra, read with InfraFrom, whose logger writes component=<name>. Start and drain failures are reported as a *LifecycleError.
Workers ¶
App.Workers returns the App's one worker registry. Workers.Continuous registers a worker that runs until the App stops, restarted under its RestartPolicy; Workers.Scheduled registers one that runs on a Schedule. Each takes a worker — a Worker or a func(context.Context) error — a run function whose other parameters the container supplies, or a constructor of a worker that the start walk builds. Each worker is a component named "worker:<name>", started and stopped in its tier; Workers.Snapshot and Workers.Lookup report every worker's WorkerInfo.
Panics and Errors ¶
Credo separates developer errors from runtime failures:
- Startup configuration (registering dependencies, 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 and the dependency graph are 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.
Bootstrap is sequential: registration calls — dependency bindings, feature mounts, satellite registrations, routes and hooks — come from the goroutine that builds the App, before it runs, and are not safe for concurrent use. The documented order is:
- configuration — New;
- the application's bindings — App.Provide, App.ProvideValue, a database it opened among them, App.Alias and App.BindMany;
- feature mounts and component registrations, in any order among themselves — App.UseI18n, App.UseHealth, workers and App.Manage;
- App.Resolve, routes and anything built from a resolved value, a readiness check included: the first resolving call finalizes the container, and App.Finalize, called before it, is an optional early check of the graph that returns its report as an error;
- App.Run.
A mistake surfaces in one of three phases:
- Registration panics on misuse known at the call site, with a message naming the call and the remedy: a constructor of the wrong shape, a duplicate binding, an App.Alias or App.BindMany whose types do not fit, and a dependency registration after shutdown began or after the container was finalized, naming what finalized it — App.Finalize, the first resolving call, or the App's start or first request — where, and the calls that led there.
- Finalizing returns what only the whole dependency graph reveals — every missing dependency with its whole path from the registration that needs it, every cycle — joined in registration order, with the same text on every run: App.Finalize returns it, and so does the first resolving call when it is the one that finalizes.
- Starting and serving return errors for what touches the outside world.
This is why App.UseI18n panics on misuse at the call while a missing or malformed locale file fails the start: the files are read in the start phase. 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
Example (BootstrapOrder) ¶
Example_bootstrapOrder follows the documented bootstrap order, every satellite included: configuration, Provide, feature mounts and satellite registrations, then Resolve and routes, then Run. It calls the optional Finalize before its first Resolve, which would finalize the container otherwise. Registration is sequential — every call comes from this goroutine, before the App runs.
package main
import (
"context"
"fmt"
"io"
"log"
"log/slog"
"net/http"
"github.com/credo-go/credo"
)
// exampleDB stands in for a database handle such as *sqldb.DB: Start pings
// it, Ready reports it in /ready, and Shutdown closes it.
type exampleDB struct{}
func (*exampleDB) Start(context.Context) error { return nil }
func (*exampleDB) Ready(context.Context) error { return nil }
func (*exampleDB) Shutdown(context.Context) error { return nil }
type examplePayments struct{}
func (*examplePayments) Ping(context.Context) error { return nil }
type exampleOrders struct {
db *exampleDB
payments *examplePayments
}
func newExampleOrders(db *exampleDB, payments *examplePayments) *exampleOrders {
return &exampleOrders{db: db, payments: payments}
}
func (o *exampleOrders) List(ctx *credo.Context) error {
return ctx.Response().Text(http.StatusOK, "3 orders")
}
// exampleRelay is a continuous worker built by the container.
type exampleRelay struct{ db *exampleDB }
func newExampleRelay(db *exampleDB) *exampleRelay { return &exampleRelay{db: db} }
func (*exampleRelay) Run(ctx context.Context) error {
<-ctx.Done()
return nil
}
// Example_bootstrapOrder follows the documented bootstrap order, every
// satellite included: configuration, Provide, feature mounts and satellite
// registrations, then Resolve and routes, then Run. It calls the optional
// Finalize before its first Resolve, which would finalize the container
// otherwise. Registration is sequential — every call comes from this
// goroutine, before the App runs.
func main() {
// 1. Configuration.
app, err := credo.New(
credo.WithAddr("127.0.0.1", 0),
credo.WithLogger(slog.New(slog.DiscardHandler)),
)
if err != nil {
log.Fatal(err)
}
// 2. Provide. A misused registration panics here, at its line.
app.ProvideValue(&exampleDB{}, credo.ComponentName("orders-db"))
app.Provide(func() *examplePayments { return &examplePayments{} })
app.Provide(newExampleOrders)
// 3. Feature mounts and satellite registrations, in any order.
app.UseI18n(credo.I18nConfig{
Default: "en",
Messages: credo.I18nMessages{"orders.empty": "No orders yet"},
})
app.UseHealth()
app.Workers().Continuous("outbox-relay", newExampleRelay)
// Optional: Finalize reports every missing dependency and cycle at once,
// before anything is built; without it, the first Resolve finalizes.
if err := app.Finalize(); err != nil {
log.Fatal(err)
}
// 4. Resolve, routes and what is built from resolved values.
orders := app.MustResolve[*exampleOrders]()
app.GET("/orders", orders.List)
payments := app.MustResolve[*examplePayments]()
app.AddReadinessCheck("payments", credo.HealthCheckFunc(payments.Ping))
// 5. Run. Here a start hook asks the running App for its routes and then
// stops it, so the example ends.
ctx, stop := context.WithCancel(context.Background())
defer stop()
app.OnStart(func(context.Context) error {
go func() {
defer stop()
for _, path := range []string{"/orders", "/ready"} {
resp, err := http.Get("http://" + app.Addr().String() + path)
if err != nil {
fmt.Println(err)
return
}
body, _ := io.ReadAll(resp.Body)
resp.Body.Close()
if path == "/ready" {
// The readiness body carries check latencies.
fmt.Println("GET", path, resp.StatusCode)
continue
}
fmt.Println("GET", path, resp.StatusCode, string(body))
}
}()
return nil
})
if err := app.RunContext(ctx); err != nil {
log.Fatal(err)
}
fmt.Println(app.State())
}
Output: GET /orders 200 3 orders GET /ready 200 stopped
Index ¶
- Constants
- Variables
- func DirFS(dir string) (fs.FS, io.Closer, error)
- func StaticCacheImmutableAssets(maxAge time.Duration) func(StaticCacheContext) string
- func StaticCacheMaxAge(maxAge time.Duration) func(StaticCacheContext) string
- func URLParam(r *http.Request, name string) string
- func Walk(r Routes, fn WalkFunc) error
- func WalkRoutes(r Routes, fn WalkRoutesFunc) error
- type AccessLogConfig
- type AccessLogEntry
- type AccessLogResultFilter
- type App
- func (app *App) AddLivenessCheck(name string, checker HealthChecker)
- func (app *App) AddReadinessCheck(name string, checker HealthChecker, opts ...RegistrationOption)
- func (app *App) Addr() net.Addr
- func (app *App) Alias[I, T any](opts ...RegistrationOption)
- func (app *App) BindMany[I, T any]()
- func (app *App) ConfigExists(key string) bool
- func (app *App) DELETE(pattern string, h Handler) *Route
- func (app *App) File(urlPath string, fsys fs.FS, name string, cfgs ...StaticConfig) *Route
- func (app *App) Finalize() error
- func (app *App) GET(pattern string, h Handler) *Route
- func (app *App) GetConfig[T any](key string) (T, error)
- func (app *App) GetRoute(name string) *Route
- func (app *App) GlobalMiddleware(middlewares ...Middleware)
- func (app *App) Group(prefix string) *Group
- func (app *App) HEAD(pattern string, h Handler) *Route
- func (app *App) Has[T any]() bool
- func (app *App) Host(pattern string) *Group
- func (app *App) IsDebug() bool
- func (app *App) IsRunning() bool
- func (app *App) Logger() *slog.Logger
- func (app *App) Manage(v any, opts ...RegistrationOption)
- func (app *App) Mount(pattern string, handler http.Handler)
- func (app *App) MustGetConfig[T any](key string) T
- func (app *App) MustResolve[T any]() T
- func (app *App) MustResolveAll[T any]() []T
- func (app *App) NewInfra(name string) Infra
- func (app *App) OPTIONS(pattern string, h Handler) *Route
- func (app *App) OnConfigChange[T any](key string, fn func(ctx context.Context, next T) error)
- func (app *App) OnReload(fn func(ctx context.Context) error)
- func (app *App) OnStart(fn func(ctx context.Context) error, opts ...RegistrationOption)
- func (app *App) OnStop(fn func(ctx context.Context) error, opts ...RegistrationOption)
- func (app *App) PATCH(pattern string, h Handler) *Route
- func (app *App) POST(pattern string, h Handler) *Route
- func (app *App) PUT(pattern string, h Handler) *Route
- func (app *App) Provide(constructor any, opts ...RegistrationOption)
- func (app *App) ProvideValue[T any](value T, opts ...RegistrationOption)
- func (app *App) QUERY(pattern string, h Handler) *Route
- func (app *App) Reload(ctx context.Context) error
- func (app *App) RemoveMeta(key string)
- func (app *App) Resolve[T any]() (T, error)
- func (app *App) ResolveAll[T any]() ([]T, error)
- func (app *App) Routes() []RouteInfo
- func (app *App) Run() error
- func (app *App) RunContext(ctx context.Context) error
- func (app *App) ServeContext(ctx context.Context, l net.Listener) error
- func (app *App) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (app *App) SetMeta(key string, val any)
- func (app *App) Shutdown(ctx context.Context) error
- func (app *App) Start(ctx context.Context) error
- func (app *App) State() string
- func (app *App) Static(prefix string, fsys fs.FS, cfgs ...StaticConfig) *StaticRoute
- func (app *App) StatusHandler(code int, h Handler)
- func (app *App) UseAccessLog(cfgs ...AccessLogConfig)
- func (app *App) UseCompress(cfgs ...CompressConfig)
- func (app *App) UseDecompress(cfgs ...DecompressConfig)
- func (app *App) UseErrorRenderer(r ErrorRenderer)
- func (app *App) UseHealth(cfgs ...HealthConfig)
- func (app *App) UseI18n(cfgs ...I18nConfig)
- func (app *App) UseRequestID(cfgs ...RequestIDConfig)
- func (app *App) UseSuccessRenderer(r SuccessRenderer)
- func (app *App) Workers() *Workers
- type BindError
- type BindErrorReason
- type Component
- type CompressConfig
- type Context
- func (c *Context) AddLogAttrs(args ...any)
- func (c *Context) Context() context.Context
- func (c *Context) Get(key string) any
- func (c *Context) GetUser[T any]() (T, bool)
- func (c *Context) HasRequestLogger() bool
- func (c *Context) HasRoute() bool
- func (c *Context) IsRewriting() bool
- func (c *Context) Locale() string
- func (c *Context) Logger() *slog.Logger
- func (c *Context) OriginalPath() string
- func (c *Context) Render(status int, data any, opts ...RenderOption) error
- func (c *Context) Request() *Request
- func (c *Context) RequestID() string
- func (c *Context) RequireUser[T any]() (T, error)
- func (c *Context) Response() *Response
- func (c *Context) Rewrite(path string) error
- func (c *Context) Route() *Route
- func (c *Context) Set(key string, val any)
- func (c *Context) SetLogger(l *slog.Logger)
- func (c *Context) SetUser[T any](user T)
- func (c *Context) T(key string, data ...map[string]any) string
- func (c *Context) TPlural(key string, count any, data ...map[string]any) string
- type ContinuousConfig
- type DIPanicError
- type DIPanicPhase
- type DecompressConfig
- type ErrorBody
- type ErrorInfo
- type ErrorRenderer
- type ErrorResponse
- type Group
- func (g *Group) DELETE(pattern string, h Handler) *Route
- func (g *Group) File(urlPath string, fsys fs.FS, name string, cfgs ...StaticConfig) *Route
- func (g *Group) GET(pattern string, h Handler) *Route
- func (g *Group) Group(prefix string) *Group
- func (g *Group) HEAD(pattern string, h Handler) *Route
- func (g *Group) Middleware(middlewares ...Middleware) *Group
- func (g *Group) OPTIONS(pattern string, h Handler) *Route
- func (g *Group) PATCH(pattern string, h Handler) *Route
- func (g *Group) POST(pattern string, h Handler) *Route
- func (g *Group) PUT(pattern string, h Handler) *Route
- func (g *Group) QUERY(pattern string, h Handler) *Route
- func (g *Group) RemoveMeta(key string)
- func (g *Group) SetMeta(key string, val any)
- func (g *Group) Static(prefix string, fsys fs.FS, cfgs ...StaticConfig) *StaticRoute
- type HTTPError
- type Handler
- type HealthCheckFunc
- type HealthChecker
- type HealthConfig
- type I18nConfig
- type I18nFields
- type I18nMessages
- type Infra
- type IngressComponent
- type LifecycleEntry
- type LifecycleError
- type LifecycleOutcome
- type LifecyclePhase
- type MessageKeyResolver
- type MessageRef
- type MessageScope
- type Middleware
- type Option
- func WithAddr(host string, port int) Option
- func WithDebug() Option
- func WithHTTPRedirect(addr string) Option
- func WithHTTPServer(fn func(*http.Server)) Option
- func WithJSONOptions(opts ...jsonv2.Options) Option
- func WithLogger(l *slog.Logger) Option
- func WithMaxBodyBytes(n int64) Option
- func WithRawConfig(rc RawConfig) Option
- func WithRecoverConfig(cfg RecoverConfig) Option
- func WithRedirectTrailingSlash(enabled bool) Option
- func WithReloadTimeout(d time.Duration) Option
- func WithShutdownTimeout(d time.Duration) Option
- func WithStrictBodies() Option
- func WithTLSConfig(cfg *tls.Config) Option
- func WithTLSFiles(certFile, keyFile string) Option
- func WithTrustedProxies(cidrs ...string) Option
- func WithoutRecover() Option
- func WithoutReloadSignals() Option
- type ProblemDetails
- type RFC9457Config
- type RawConfig
- type Readier
- type RecoverConfig
- type RegistrationOption
- type RenderInfo
- type RenderOption
- type Request
- func (r *Request) BindBody(target any) error
- func (r *Request) BindQuery(target any) error
- func (r *Request) PathValue(name string) string
- func (r *Request) QueryParam(name string) string
- func (r *Request) RealIP() string
- func (r *Request) RouteParam(name string) string
- func (r *Request) RouteParams() map[string]string
- func (r *Request) Scheme() string
- type RequestIDConfig
- type ResourceIdentifier
- type Response
- func (r *Response) Blob(code int, contentType string, b []byte) error
- func (r *Response) Committed() bool
- func (r *Response) Flush()
- func (r *Response) FlushError() error
- func (r *Response) HTML(code int, html string) error
- func (r *Response) Hijack() (net.Conn, *bufio.ReadWriter, error)
- func (r *Response) Hijacked() bool
- func (r *Response) JSON(code int, v any) error
- func (r *Response) NoContent(code int) error
- func (r *Response) ReadFrom(src io.Reader) (int64, error)
- func (r *Response) Redirect(code int, url string) error
- func (r *Response) Reset(w http.ResponseWriter)
- func (r *Response) SetCookie(cookie *http.Cookie)
- func (r *Response) Size() int64
- func (r *Response) Status() int
- func (r *Response) Stream(code int, contentType string, rd io.Reader) error
- func (r *Response) String() string
- func (r *Response) Text(code int, s string) error
- func (r *Response) Unwrap() http.ResponseWriter
- func (r *Response) Write(b []byte) (int, error)
- func (r *Response) WriteHeader(code int)
- func (r *Response) WriteString(s string) (int, error)
- func (r *Response) XML(code int, v any) error
- type RestartPolicy
- type Route
- func (r *Route) BuildURI(params ...string) (string, error)
- func (r *Route) BuildURL(params ...string) (string, error)
- func (r *Route) GetHost() string
- func (r *Route) GetMethod() string
- func (r *Route) GetName() string
- func (r *Route) GetPattern() string
- func (r *Route) LookupMeta(key string) (any, bool)
- func (r *Route) Middleware(m ...Middleware) *Route
- func (r *Route) Name(name string) *Route
- func (r *Route) SetMeta(key string, val any) *Route
- type RouteContext
- type RouteInfo
- type RouteKind
- type Routes
- type Schedule
- type ScheduledConfig
- type Starter
- type StaticCacheContext
- type StaticConfig
- type StaticRoute
- type StdMiddleware
- type SuccessRenderer
- type Tier
- type WalkFunc
- type WalkRoutesFunc
- type Worker
- type WorkerInfo
- type WorkerKind
- type WorkerRun
- type WorkerStatus
- type Workers
Examples ¶
Constants ¶
const ( // DIPanicConstruction: a constructor panicked while building a singleton. DIPanicConstruction = di.PhaseConstruction // DIPanicStart: a component's Start panicked during the start walk. DIPanicStart = di.PhaseStart // DIPanicShutdown: a component's Shutdown or Close panicked during the // drain. DIPanicShutdown = di.PhaseShutdown // DIPanicLateCleanup: a teardown panicked during the best-effort cleanup // of an instance constructed after the drain deadline. DIPanicLateCleanup = di.PhaseLateCleanup )
const ( MsgKeyBadRequest = "bad_request" 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" 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.
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).
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.
const DefaultMaxRestartDelay = time.Minute
DefaultMaxRestartDelay is the default cap on the restart delay of a continuous worker (RestartPolicy.MaxDelay).
const DefaultMinRestartDelay = 3 * time.Second
DefaultMinRestartDelay is the default first and shortest wait before a continuous worker restarts (RestartPolicy.MinDelay).
const MetaAccessLog = internalobserve.MetaAccessLogKey
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.
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 ¶
var ( ErrNotFound = NewHTTPError(http.StatusNotFound) ErrMethodNotAllowed = NewHTTPError(http.StatusMethodNotAllowed) ErrBadRequest = NewHTTPError(http.StatusBadRequest) 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.
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 — when App.Shutdown begins the internal tier, after the HTTP drain and the ingress tier — and takes precedence over a failed Finalize.
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.
var ErrWorkerRunTimeout = internalworker.ErrRunTimeout
ErrWorkerRunTimeout is the cancellation cause of a run that exceeded its ScheduledConfig.RunTimeout budget. Inside Run,
errors.Is(context.Cause(ctx), credo.ErrWorkerRunTimeout)
tells the budget running out from the worker being stopped. A run cut short by the timeout is recorded as a failure wrapping ErrWorkerRunTimeout, even when Run returns nil.
Functions ¶
func DirFS ¶
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. Close it in a stop hook, which runs after the HTTP drain, so the handle is released cleanly:
fsys, closer, err := credo.DirFS("./public")
if err != nil {
return err
}
app.Static("/assets", fsys)
app.OnStop(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 ¶
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 ¶
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 ¶
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 or the server settings contain invalid values (negative timeouts, an invalid port). An option only records configuration and cannot fail by itself.
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, opts ...RegistrationOption)
AddReadinessCheck registers a named readiness check. OptionalReadiness, its one option, reports the check in /ready without letting it gate readiness: a check of a cache or of a third-party API. Panics if App.UseHealth has not been called first, checker is nil, an option other than OptionalReadiness is given, or name is empty, padded with whitespace, contains control characters, uses the reserved "credo." prefix, or duplicates another readiness check.
func (*App) 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) Alias ¶
func (app *App) Alias[I, T any](opts ...RegistrationOption)
Alias creates a type alias so that resolving interface I via App.Resolve returns the singleton registered for concrete type T. An alias is a binding of I: a later direct binding of I panics unless it carries Override, which replaces the alias. I must be an interface, T must implement I and be registered already, and I must have neither a binding nor an alias; otherwise Alias panics, as it does after App.Finalize or after shutdown began. Override, its one option, points I at T in place of its earlier binding or alias.
The type an overridden alias pointed at stays registered until App.Finalize, which drops it when no other alias, App.BindMany entry or constructor parameter reaches it: it is never built or started, and resolving it reports the override.
app.Provide(NewPgUserRepo) // binds *PgUserRepo app.Alias[UserRepo, *PgUserRepo]()
func (*App) BindMany ¶
BindMany adds concrete type T to the ordered collection for interface I. I must be an interface, T must be a registered concrete type that implements I, and the pair must be new; otherwise BindMany panics, as it does after App.Finalize or after shutdown began.
func (*App) ConfigExists ¶ added in v0.19.0
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: unlike App.Resolve, it never finalizes the container.
func (*App) File ¶
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 ¶
Finalize freezes the DI container and validates the dependency graph. After Finalize, a Provide, ProvideValue, Alias, BindMany or Manage call and a worker registration panic, naming what finalized the container, where, and the calls that led there. 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 returns what only the whole graph reveals, joined in registration order with the same text on every run: each missing dependency with its whole path from the registration that needs it, for example
di: missing dependency: *app.OrderService → *app.PaymentClient → *http.Client (not registered); ...
each circular dependency, constructors that take a context.Context, and each internal component that depends on an ingress one, with the path and both remedies.
Finalize is idempotent and optional: an early check of the graph. If not called explicitly, the first resolving call (App.Resolve and its siblings), App.Run, App.Start and the first App.ServeHTTP call make it implicitly, whichever comes first.
if err := app.Finalize(); err != nil {
log.Fatal(err)
}
func (*App) GET ¶
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 ¶
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) 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) HEAD ¶
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
Has reports whether type T is registered, directly or through App.Alias. It is the one non-resolving presence probe: it never runs a constructor and makes no claim that the instance is healthy or usable, and the result is a snapshot of the registrations made so far, not a reservation for a later one. Use it in a composition root to ask whether an optional module was wired.
func (*App) Host ¶
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, a parameter without a name, a parameter name used twice, an empty or 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 ¶
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) 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) Manage ¶ added in v0.24.0
func (app *App) Manage(v any, opts ...RegistrationOption)
Manage adds a component that is not a DI binding: a value that has Shutdown, or a constructor over DI parameters — func(deps...) C or func(deps...) (C, error) — that the start walk builds and that never becomes a binding. A function whose own type has Shutdown is a value, not a constructor. ComponentName names it (default: its type name); Ingress places it in the ingress tier; OptionalReadiness keeps its readiness entry from gating. A value has no edges and stops in reverse registration order within its tier; a constructor has its parameters' edges. A mounted child App is handed to Manage so that its start phase runs in the parent's.
Only a value claims the resource it holds. The value a constructor builds claims nothing: when it holds a resource a registration holds too, such as a wrapper that embeds a bound handle, it defers to that registration, which gives the resource's one readiness entry and runs its one teardown. Such a constructor with ComponentName, Ingress or OptionalReadiness fails the start once its value is built, since the value has no entry and no teardown of its own for them to shape.
Manage panics on a value without Shutdown, on a duplicate name, on a resource a ProvideValue binding already holds, on a resource handed to Manage twice, on a resource whose registrations are placed in different tiers, and after Finalize or shutdown.
func (*App) Mount ¶
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 "/". The name _mount is reserved: the mount captures the rest of the path under it.
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.
Mount panics if handler is nil, if the pattern is malformed, names a parameter _mount or uses a name twice, if a route already occupies the prefix, or if called after compile; nothing is registered then.
func (*App) MustGetConfig ¶
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) MustResolve ¶
MustResolve is like App.Resolve but panics on error: the whole Finalize report when the implicit Finalize fails, or a constructor's failure. 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 ¶
MustResolveAll is like App.ResolveAll but panics on error.
func (*App) NewInfra ¶
NewInfra creates a scoped Infra with the given name, for code that runs outside a call the App makes on a component (middleware factories, startup helpers). The Logger is tagged with component=name and falls back to the framework default logger when the application has none configured. A constructor receives its Infra automatically, and a component's Start, Ready and Shutdown read theirs with InfraFrom.
func (*App) OPTIONS ¶
OPTIONS registers an OPTIONS route. Panics under the same conditions as App.GET.
func (*App) OnConfigChange ¶ added in v0.5.0
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) OnReload ¶ added in v0.5.0
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) OnStart ¶
func (app *App) OnStart(fn func(ctx context.Context) error, opts ...RegistrationOption)
OnStart registers a start hook: an anonymous component of a tier, internal unless Ingress is passed. Start hooks run FIFO after their tier's components have started — so a hook can use what they provide — and before the App accepts requests. Under managed serving the listener is already bound, so App.Addr is available.
The ctx ends when the hook returns, or earlier when a shutdown is requested during the start phase; work that outlives the hook belongs to a component with Start and Shutdown. A hook that returns an error or panics fails the start: nothing further starts, what was built is rolled back, and the entry point returns a *LifecycleError. A hook is a leaf action: a resource with its own teardown is a component — handed to App.Manage, or bound with CloseOnShutdown.
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 the App is prepared; panics for a nil hook, an option other than Ingress, or after the App is frozen.
func (*App) OnStop ¶ added in v0.24.0
func (app *App) OnStop(fn func(ctx context.Context) error, opts ...RegistrationOption)
OnStop registers a stop hook: an anonymous component of a tier, internal unless Ingress is passed. Stop hooks run LIFO before their tier's components stop, so a hook can still use them: the ingress tier's hooks beside the HTTP drain, the internal tier's after it. The ctx carries the drain deadline; a hook that has not returned by then is abandoned and reported, and an error or a panic is reported without stopping the drain.
Stop hooks run on every teardown — the drain, bootstrap teardown, and the rollback of a failed or interrupted start — so a hook must tolerate a start that never reached its counterpart. Process-level cleanup that must outlive every component belongs after Run returns.
Must be called before the App is prepared; panics for a nil hook, an option other than Ingress, or after the App is frozen.
func (*App) Provide ¶
func (app *App) Provide(constructor any, opts ...RegistrationOption)
Provide registers a constructor in the application's DI container. The binding's type is the constructor's first result type: func(deps...) T or func(deps...) (T, error) binds T. Its parameters are themselves resolved from the container. It runs at most once, on its first resolution; the first resolving call finalizes the container (App.Finalize) when nothing has.
app.Provide(NewUserService) // binds *UserService
A constructor declared to return a concrete type binds that type; the interfaces it serves are bound with App.Alias. One declared to return an interface binds the interface.
Because Go cannot express "a function with arbitrary parameters" in the type system, constructor is typed any: a signature mistake (not a function, no result, a second result that is not an error) panics here, at the call, not at compile time. So do a nil constructor, a second binding of T — a direct one, or an alias of T — without Override, and a call after the container was finalized or after shutdown began; each is misuse known at the call site (see "Panics and Errors" in the package documentation). The dependency graph itself is validated when the container is finalized (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.
A binding whose type shows Shutdown is a component: the App shuts its value down after its consumers, and starts it and asks it for readiness when the type also shows Start or Ready (Component). A value whose Shutdown only the built value shows is shut down too, in the internal tier. A component whose built value has a Start, a Ready or an IngressComponent tier the binding's type hides fails the start once it is built: declare the constructor to return the concrete type, and bind the interface with App.Alias. The options are Ingress, CloseOnShutdown, Override, ComponentName and OptionalReadiness; each panics on misuse at the call.
Registration is sequential: call Provide from the goroutine that builds the App, before it runs.
func (*App) ProvideValue ¶
func (app *App) ProvideValue[T any](value T, opts ...RegistrationOption)
ProvideValue registers a pre-built value for type T as a Singleton. The App owns the value from then on: if it is a Component it is shut down during the drain, unless Borrowed leaves it to the caller. The options are Ingress, Borrowed, CloseOnShutdown, Override, ComponentName and OptionalReadiness; Override is how a composition root or a test swaps an earlier binding — a direct one, or an alias of T — for a stub, and the value it replaces never becomes the App's. A second binding of T without Override, a call after App.Finalize or after shutdown began, a value whose resource another holder owns differently, and a component whose Start, Ready or IngressComponent tier the type T hides panic, like App.Provide; a hidden capability's remedies are binding the concrete type with an App.Alias of T, or Borrowed when the caller starts and stops the value.
app.ProvideValue[*Logger](logger)
func (*App) QUERY ¶ added in v0.13.0
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
Reload performs a trigger-driven partial reload (ADR-020). It succeeds only while the server is running. The sequence is:
- If the RawConfig implements config.Stager, re-read every source into a candidate snapshot (a load error aborts with the old snapshot untouched).
- Decode — and validate — every App.OnConfigChange subscriber whose section the candidate changes; any failure aborts before anything is published.
- 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.
- 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 ¶
RemoveMeta removes a root-level metadata key. Must be called before the server starts; panics if called after compile.
func (*App) Resolve ¶
Resolve retrieves an instance of type T from the application's DI container. The first resolving call — Resolve, App.ResolveAll, App.MustResolve or App.MustResolveAll — finalizes the container when nothing has (App.Finalize) and records itself, with its site, as what finalized it; a failed Finalize is that call's error, and every later Resolve returns it. Constructors run at first resolution, exactly once, and a constructor panic is returned as a DIPanicError to every caller. Once shutdown has begun, Resolve returns an error wrapping ErrDIClosed. Resolve is safe for concurrent use; concurrent first calls finalize once.
Resolve is primarily intended for bootstrap/composition-root code; runtime calls remain available, but Credo's recommended application pattern is constructor injection. Stop hooks (App.OnStop) 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 ¶
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 ¶
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 ¶
Run binds the listener, runs the start phase — each component's Start in dependency order, then the start hooks — serves, and blocks until an interrupt (Ctrl+C) or SIGTERM is received, then drains in tiers under the deadline set by WithShutdownTimeout. A signal during the start phase interrupts it: nothing further starts, what was built is rolled back, and Run returns nil after a clean rollback. A second signal force-kills the process. Returns nil on graceful shutdown, and a *LifecycleError when the start fails or a drain or rollback does not complete.
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 ¶
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. 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 the start phase interrupts it: the running Start's or start hook's context is cancelled, nothing further starts, what was built is rolled back, the listener never accepts, and RunContext returns nil after a clean rollback.
func (*App) ServeContext ¶
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.
An App with something to start — a component with Start or Ready, a start hook, a constructor handed to App.Manage, a bound database, a worker or App.UseI18n catalogs — refuses to serve until the start phase has succeeded: before App.Start (or while it runs) every request panics with a message naming App.Start and testutil.Start, and after a failed or interrupted App.Start the stopped App answers with the 503 envelope. Under Run, RunContext and ServeContext the listener accepts only after the start phase, so the gate never fires; a child App mounted into a parent is handed to the parent with Manage for the same reason.
func (*App) SetMeta ¶
SetMeta sets a root-level metadata key-value pair. Must be called before the server starts; panics if called after compile.
func (*App) Shutdown ¶
Shutdown gracefully shuts down the App: it withdraws readiness; drains in-flight HTTP requests concurrently with the ingress tier (ingress stop hooks LIFO, then ingress components); waits for an in-flight reload; then stops the internal tier — internal stop hooks LIFO, then internal components in reverse dependency order. The caller's ctx carries the one deadline the steps share; WithShutdownTimeout does not replace it. A component or hook that has not returned at the deadline is abandoned and the components it depends on stay open. Returns the HTTP drain's error, the reload's and a *LifecycleError, joined, when a step fails or remains incomplete.
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 on a starting App interrupts the start phase and waits, within ctx, for the rollback; it returns the rollback's lifecycle error, nil when the rollback was clean. Shutdown returns an error when the App is already stopping or stopped; a 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) Start ¶ added in v0.24.0
Start runs the start phase without a listener; Run, RunContext and ServeContext serve. It claims the App, prepares it (Finalize and compile), runs the start walk — each component's Start in dependency order, then the start hooks, internal tier first — and enters running, for an App served through ServeHTTP by an external http.Server or in a test. Shutdown stops what it started.
Whoever serves the App through ServeHTTP owns that server's admission and drain and completes them before Shutdown: the internal tier stops after the HTTP drain only if that drain has happened.
Start is accepted only once, in building; a second call, or a serve entry point after it, returns an error. A failed start rolls back what was built, leaves the App stopped, and returns a *LifecycleError. ctx interrupts the start phase: nothing further starts, what was built is rolled back under the shutdown timeout, and Start returns ctx's error — or, when Shutdown interrupted it, an error saying so — joined with the lifecycle error when the rollback was not clean. In tests, testutil.Start starts an App and shuts it down when the test ends.
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), if the group's prefix names a parameter _static (the name the file path is captured under) or uses a name twice, 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 ¶
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, and StatusHandler panics for any other code, so a registration that would never run fails at startup instead of being silently ignored. No other code is supported: a 5xx handler would re-enter application code inside error rendering. 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, committed responses and hijacked connections keep their behavior. A Flush streams the compressed output; a flush before the first write makes the compression decision then, from the headers set so far, so the flushed header carries Content-Encoding. 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 — and misuse panics like every other registration API. 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)
UseI18n installs internationalization for the application. The request locale is resolved lazily through I18nConfig.Detect on the first Context.Locale or translation access of each request — there is no locale middleware.
Registration validates the configuration and compiles the programmatic catalog; it does no I/O. The locale files are read in the start phase, before any component starts, and a read failure is a start failure.
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; otherwise the start fails.
- Messages/Fields provide one programmatic catalog for Default; external files override it key by key.
- A malformed locale file fails the start.
UseI18n panics, like every Use* registration, on misuse: more than one config, Dir together with DirFS, an "i18n" config section that does not decode, an invalid Default, a programmatic message that does not compile, Fields with no message source, a second call, and a call after preparation or shutdown.
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.
func (*App) Workers ¶ added in v0.25.0
Workers returns the App's one worker registry, created on first use; every call returns the same value. It registers nothing, so an App that calls it and registers no worker has no start work. It is not bound in DI: a module that registers workers takes the *App it already receives.
The registry logs through the App's logger with module=worker, and each worker's records carry component=worker:<name>.
Example ¶
package main
import (
"context"
"fmt"
"log/slog"
"time"
"github.com/credo-go/credo"
)
// heartbeat is a continuous worker: Run stays active until the application
// shuts down.
type heartbeat struct{}
func (heartbeat) Run(ctx context.Context) error {
ticker := time.NewTicker(30 * time.Second)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return nil
case <-ticker.C:
run, _ := credo.CurrentWorkerRun(ctx)
slog.InfoContext(ctx, "heartbeat", "worker", run.Worker)
}
}
}
// metricsReport is a scheduled worker: one run per activation, never
// overlapping.
type metricsReport struct{}
func (metricsReport) Run(context.Context) error { return nil }
func main() {
app, err := credo.New()
if err != nil {
panic(err)
}
workers := app.Workers()
workers.Continuous("heartbeat", heartbeat{},
credo.ContinuousConfig{Restart: credo.RestartPolicy{MinDelay: 5 * time.Second}})
workers.Scheduled("metrics-report", "@every 1m", metricsReport{})
for _, info := range workers.Snapshot() {
var tier credo.Tier
if info.Continuous != nil {
tier = info.Continuous.Tier
} else {
tier = info.Scheduled.Tier
}
fmt.Println(info.Name, info.Kind, tier, info.Status)
}
}
Output: heartbeat continuous internal pending metrics-report scheduled ingress pending
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) HTTPStatus ¶ added in v0.4.0
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.
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 Component ¶ added in v0.24.0
Component is a value whose teardown the App owns. A DI singleton is a component when it has Shutdown — its binding's type shows the method at registration, or its built value has it — and so is a value or constructor handed to App.Manage. The App shuts components down after their consumers, in two tiers (Tier), and starts and asks for readiness those whose binding's type shows the optional capabilities Starter and Readier.
The context carries the drain deadline. A Shutdown that has not returned at the deadline is abandoned: the components it depends on stay open, and the App reports it in a *LifecycleError.
Component never gains a method; it grows through optional capabilities.
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.OnStop 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 ¶
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 ¶
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) GetUser ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
Logger returns the request-scoped logger. Falls back through the chain: request logger → app logger → nop logger.
func (*Context) OriginalPath ¶
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) RequestID ¶
RequestID returns the current request ID. It returns an empty string when request ID middleware is not active.
func (*Context) RequireUser ¶
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) Rewrite ¶
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 ¶
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) SetLogger ¶
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 ¶
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 ¶
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 ¶
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 ContinuousConfig ¶ added in v0.25.0
type ContinuousConfig struct {
// Tier is the drain tier of the worker's component; zero is
// TierInternal: the worker stops after the HTTP drain, before the
// components it depends on. A worker that consumes an external queue
// declares TierIngress, so it stops taking work with the listener.
Tier Tier `json:"tier"`
// Restart is the restart policy after a failed run.
Restart RestartPolicy `json:"restart"`
// UnreadyWhenFailed reports the instance unready once the worker is
// failed.
UnreadyWhenFailed bool `json:"unready_when_failed"`
}
ContinuousConfig configures a continuous worker. Zero means the default in every field.
type DIPanicError ¶ added in v0.19.0
type DIPanicError = di.PanicError
DIPanicError is the recovered panic of a DI constructor, or of a component's Start, Shutdown or Close. Its fields are the failing Type, the Phase (construction, start, 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 *LifecycleError.
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 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 ¶
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
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 ¶
DELETE registers a DELETE route in this group. Panics under the same conditions as App.GET.
func (*Group) File ¶
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 ¶
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 ¶
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 ¶
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 ¶
OPTIONS registers an OPTIONS route in this group. Panics under the same conditions as App.GET.
func (*Group) PATCH ¶
PATCH registers a PATCH route in this group. Panics under the same conditions as App.GET.
func (*Group) POST ¶
POST registers a POST route in this group. Panics under the same conditions as App.GET.
func (*Group) PUT ¶
PUT registers a PUT route in this group. Panics under the same conditions as App.GET.
func (*Group) QUERY ¶ added in v0.13.0
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 ¶
RemoveMeta removes a metadata key from this group. Must be called before the server starts; panics if called after compile.
func (*Group) SetMeta ¶
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:
- i18n bundle lookup — if a translation exists for MessageKey, use it
- builtInMessages lookup — if MessageKey matches a built-in key, use it
- MessageKey itself — used as-is (works for literal messages)
func NewHTTPError ¶
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 ¶
Error implements the error interface. The diagnostic order is status, code, key, internal; empty segments are omitted.
func (*HTTPError) HTTPStatus ¶
HTTPStatus returns the HTTP status code carried by the error.
func (*HTTPError) WithDetails ¶ added in v0.10.0
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 ¶
WithInternal returns a copy of the error with the internal error set.
func (*HTTPError) WithMessageKey ¶ added in v0.11.0
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 ¶
Handler is the Credo handler signature. Handlers return an error for centralized error handling via the App's error handling pipeline.
type HealthCheckFunc ¶
HealthCheckFunc adapts a plain function to HealthChecker.
type HealthChecker ¶
HealthChecker checks the health of a dependency or subsystem.
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
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
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 component it serves.
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 to the application part it serves: a constructor's logger carries component=<name>, the name of the binding it builds — its type as the lifecycle prints it, such as *users.Service, or its ComponentName name — the key and value the lifecycle's own records about that component use. Framework packages add module=<name> to the records they write.
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))}
func InfraFrom ¶ added in v0.25.0
InfraFrom returns the scoped Infra the App puts in the context of every call it makes on a component — Start, Ready, Shutdown — and on an OnStart or OnStop hook. Its Logger is the App's logger with component=<name>, the component's name as its readiness entry, a LifecycleError and the lifecycle's own records show it. context.WithoutCancel keeps the value, so work derived from the Start context sees the same Infra.
It is the path for a framework module whose value is built outside the App and started by it: the module logs to its own configured logger when one is given, otherwise to InfraFrom(ctx).Logger, otherwise to the framework default. Only framework infrastructure travels in the context, never application services.
Outside such a call InfraFrom returns the zero Infra, whose nil Logger means the framework default. Request code logs through the request's Context.Logger, and a constructor takes Infra as a parameter.
type IngressComponent ¶ added in v0.25.0
type IngressComponent interface {
Component
IngressTier()
}
IngressComponent is the capability of a component type whose tier follows from its nature: a server or a consumer, where work enters the process. A registration whose type implements it is planned in the ingress tier without Ingress, which stays accepted and redundant. IngressTier is never called; the check needs no value, so Finalize validates the tiers before anything is built. A type declares the tier only when no registration could rightly place it internal: there is no way down. A binding whose type hides the method of its value, such as an interface view, is refused, as a hidden Start is.
type LifecycleEntry ¶ added in v0.24.0
type LifecycleEntry struct {
// Name is the component's credo.ComponentName name, its type name,
// worker:<name> for a worker, or OnStart[i]/OnStop[i] for a hook.
Name string
// Tier is the component's tier.
Tier Tier
// Phase is the phase the outcome belongs to.
Phase LifecyclePhase
// Outcome is what happened.
Outcome LifecycleOutcome
// Err is the failure for OutcomeFailed and OutcomePanicked; nil otherwise.
Err error
// KeptOpenBy names the abandoned consumers of an OutcomeKeptOpen entry.
KeptOpenBy []string
// Duration is how long an abandoned call had run at the boundary, or how
// long a completed one took; zero when unknown.
Duration time.Duration
}
LifecycleEntry is one component's record in a LifecycleError.
func (LifecycleEntry) String ¶ added in v0.24.0
func (e LifecycleEntry) String() string
String renders the entry as it appears in the error text.
type LifecycleError ¶ added in v0.24.0
type LifecycleError struct {
// Entries holds the records, start entries first, then the drain's in
// the order the components were registered. Callers must not modify it.
Entries []LifecycleEntry
// Cause is the context error when the deadline or a cancellation ended
// the phase before it completed; nil otherwise.
Cause error
// contains filtered or unexported fields
}
LifecycleError reports a failed start, or a start or drain that did not complete. It names each component that failed, panicked, was abandoned at the deadline or was kept open by an abandoned consumer, with its tier and phase. It is an immutable snapshot taken at the boundary: a call returning later, or the late cleanup of a construction that completed after the deadline, is logged and never written back. Obtain it with errors.AsType[*credo.LifecycleError]; Unwrap exposes each failure and the context cause, so errors.Is and errors.As traverse it.
func (*LifecycleError) Error ¶ added in v0.24.0
func (e *LifecycleError) Error() string
Error summarizes the entries.
func (*LifecycleError) Unwrap ¶ added in v0.24.0
func (e *LifecycleError) Unwrap() []error
Unwrap returns the entries' errors and the context cause.
type LifecycleOutcome ¶ added in v0.24.0
type LifecycleOutcome string
LifecycleOutcome is what happened to a component in a LifecycleEntry.
const ( // OutcomeFailed: the call returned an error (in Err). OutcomeFailed LifecycleOutcome = "failed" // OutcomePanicked: the call panicked; Err is a *DIPanicError for a // component. OutcomePanicked LifecycleOutcome = "panicked" // OutcomeAbandoned: the call had not returned at the deadline, or the // deadline ended before its turn. A component still running keeps the // components it depends on open. OutcomeAbandoned LifecycleOutcome = "abandoned" // OutcomeKeptOpen: the component was not stopped because a consumer that // was abandoned may still use it (KeptOpenBy). OutcomeKeptOpen LifecycleOutcome = "kept_open" )
type LifecyclePhase ¶ added in v0.24.0
type LifecyclePhase string
LifecyclePhase is the phase a LifecycleEntry belongs to.
const ( // PhaseStart is the start walk: a component's construction or Start, or // a start hook. PhaseStart LifecyclePhase = "start" // PhaseShutdown is the drain, or the rollback of a failed or interrupted // start: a component's Shutdown or Close, or a stop hook. PhaseShutdown LifecyclePhase = "shutdown" )
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 ¶
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 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 ¶
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
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
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 ¶
WithLogger sets the application-level logger. Each component receives a scoped copy with a "component" 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 ¶
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 ¶
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 ¶
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
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 ¶
WithShutdownTimeout sets the graceful-shutdown drain budget used by the signal-aware Run and by context-cancellation-triggered RunContext, and for the rollback of a failed or interrupted start. The HTTP drain, the ingress tier and the internal tier share this one absolute budget, spent in order; a component or hook that has not returned by its end is abandoned. 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 ¶
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 ¶
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 ¶
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 ¶
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 Readier ¶ added in v0.24.0
Readier is the capability of a component that answers readiness. The readiness endpoint aggregates the Ready of every component whose binding's type shows it, under the component's name, with the request's context. A borrowed value's Ready contributes too.
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 RegistrationOption ¶ added in v0.24.0
type RegistrationOption struct {
// contains filtered or unexported fields
}
RegistrationOption is an option of a component registration: Ingress, Borrowed, CloseOnShutdown, Override, ComponentName or OptionalReadiness. Each call accepts the options that apply to it and panics on any other.
func Borrowed ¶ added in v0.24.0
func Borrowed() RegistrationOption
Borrowed, on ProvideValue only, keeps the binding and the value's readiness contribution and leaves starting and shutting the value down to the caller, through every holder of the resource: a pool two Apps in one process share, or a fixture a test suite reuses. A holder of the same resource that claims its teardown panics.
func CloseOnShutdown ¶ added in v0.25.0
func CloseOnShutdown() RegistrationOption
CloseOnShutdown makes a binding whose type has a Close method — Close() error, Close(), or Close(ctx) error, which receives the drain deadline — a component the App closes on shutdown, after its consumers. It panics on a type with none of the three, on a type that is already a component, and beside Borrowed. Close is never discovered without it: a handle that embeds another and closes it, such as bun's over its *sql.DB, would close the pool while a sibling component still uses it.
func ComponentName ¶ added in v0.25.0
func ComponentName(name string) RegistrationOption
ComponentName names a component — a binding made with App.Provide or App.ProvideValue, or a value handed to App.Manage — in logs, readiness and lifecycle errors; the default is its type as the lifecycle prints it, such as *sqldb.DB. The name follows the rules of a health check name. Each component has its own name, except the registrations of one resource, a raw handle and a wrapper that embeds it, which give it one name: the name given on either, which its readiness entry and its teardown carry. The name labels the component and is not a DI key: a second value of one type is bound under a wrapper type of its own. On a binding it panics when the binding is not a component at registration, since the name is planned before the value exists.
func Ingress ¶ added in v0.24.0
func Ingress() RegistrationOption
Ingress places a component — or a start or stop hook — in the ingress tier; a type that implements IngressComponent is there without it. On Provide and ProvideValue it panics on a binding that is not a component at registration: its type shows no Shutdown and it carries no CloseOnShutdown, and the tier is planned before the value exists.
func OptionalReadiness ¶ added in v0.25.0
func OptionalReadiness() RegistrationOption
OptionalReadiness reports a component in /ready without letting it gate readiness: its Ready is asked under the same deadline, its entry shows its own status and latency, and a failure is logged like any failing check, while /ready answers 200 with the status "degraded" when every gating entry is up. Start and Shutdown are unchanged, so a component whose Start fails still fails the start. It applies to App.Provide, App.ProvideValue and App.Manage wherever the registration plans a readiness entry — its type shows Ready, and it is a component or borrowed — and panics elsewhere at registration; App.AddReadinessCheck takes it too. The registrations of one resource all give it or none does.
func Override ¶ added in v0.24.0
func Override() RegistrationOption
Override, on Provide, ProvideValue and Alias, replaces an earlier binding of the same type before Finalize — a direct binding, or an alias of an interface — and panics when there is none, so an override that no longer matches the wiring fails instead of adding a binding nothing resolves. The replaced value never becomes the App's: whoever built it releases it, and the type a replaced alias pointed at is dropped at Finalize when nothing else uses it.
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 ¶
Request wraps *http.Request and provides request-side helpers: route parameters, query parameter shortcuts, and body/query binding.
func NewRequest ¶
NewRequest creates a new Request wrapping the given *http.Request.
func (*Request) BindBody ¶
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 ¶
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 ¶
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 ¶
QueryParam returns a query string parameter value by name. Returns "" if not present.
func (*Request) RealIP ¶
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 ¶
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 ¶
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 ¶
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 ResourceIdentifier ¶ added in v0.24.0
type ResourceIdentifier interface {
ResourceIdentity() any
}
ResourceIdentifier names the resource a value holds. Values that share an identity are one resource, started once and torn down once: the teardown runs when the last holder retires, through its holder of record: the first registration that holds it — a binding, or a value handed to App.Manage, one that is a component by its type preferred — else its first holder. A value a constructor builds without becoming a binding, a worker's or one from a constructor handed to Manage, defers to a registration: it adds no readiness entry and never runs the teardown. The registrations of one resource agree on its tier. Without the method a comparable value — a pointer, or a struct over one — is its own identity. A value that releases state of its own must not share an identity: a wrapper that does holds the handle in a named field instead of embedding it.
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 ¶
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 ¶
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 implements http.Flusher; see Response.FlushError.
func (*Response) FlushError ¶ added in v0.23.0
FlushError sends any buffered data to the client and reports whether it could; http.ResponseController prefers it to Flush. A flush commits the response, as net/http's does: status 200 is written first when no status was. The commit is recorded, so an error the handler returns afterwards is logged instead of being appended to the flushed response. When no writer in the chain can flush, the result is http.ErrNotSupported and nothing is committed; after a hijack it is http.ErrHijacked.
func (*Response) HTML ¶
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 ¶
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 ¶
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 ¶
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) ReadFrom ¶ added in v0.19.0
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) Reset ¶
func (r *Response) Reset(w http.ResponseWriter)
Reset resets the response for reuse from the pool.
func (*Response) Status ¶
Status returns the HTTP status code written, or 0 when the response has not been committed yet.
func (*Response) Stream ¶
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) Text ¶
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 ¶
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 ¶
WriteHeader sends an HTTP response header with the given status code. The final status is written once per response; later calls are ignored.
An informational status other than 101 (103 Early Hints, for example) is sent at once with the current headers and commits nothing: the final status follows, as with net/http. A code outside 100–999 panics, as net/http does, before anything is recorded, so the response stays uncommitted and the recovered panic is still answered with a 500.
func (*Response) WriteString ¶ added in v0.10.0
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).
type RestartPolicy ¶ added in v0.25.0
type RestartPolicy struct {
// Disabled makes the first failed run terminal. It cannot be combined
// with any other field.
Disabled bool `json:"disabled"`
// Limit allows the first run plus at most Limit restarts; zero means
// unlimited.
Limit int `json:"limit"`
// MinDelay is the first and shortest wait; zero is
// [DefaultMinRestartDelay].
MinDelay time.Duration `json:"min_delay"`
// MaxDelay is the longest wait; zero is the larger of
// [DefaultMaxRestartDelay] and MinDelay. A positive MaxDelay below
// MinDelay is rejected.
MaxDelay time.Duration `json:"max_delay"`
}
RestartPolicy is the restart policy of a continuous worker. After a failed run the worker waits and runs again; the wait starts at MinDelay and backs off, with jitter, up to MaxDelay while failures repeat:
ceiling = min(MinDelay × 2^(k−1), MaxDelay) delay = uniform in [max(MinDelay, ceiling/2), ceiling]
where k counts the failures of the current sequence, so the first delay is exactly MinDelay. A run that lasted at least MaxDelay starts a new sequence. Equal delays give a fixed delay.
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 ¶
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, empty for a single-segment parameter, fails its constraint, when too many values are provided, or when the route pattern is malformed. An empty catch-all value is valid: the catch-all matches an empty rest, so "/files/{path...}" with "" builds "/files/".
uri, err := route.BuildURI("42") // "/users/42"
func (*Route) BuildURL ¶
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 ¶
GetHost returns the host pattern for host-scoped routes. Returns an empty string for routes on the default mux.
func (*Route) LookupMeta ¶
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 ¶
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 ¶
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 Schedule ¶ added in v0.25.0
type Schedule struct {
// contains filtered or unexported fields
}
Schedule is a compiled cron schedule.
func ParseSchedule ¶ added in v0.25.0
ParseSchedule parses a cron expression into a compiled schedule.
The supported syntax is standard 5-field Vixie cron — minute, hour, day-of-month, month, day-of-week — with lists ("1,15"), ranges ("1-5"), steps ("*/10", "8-18/2"), month and weekday names ("jan", "sat"), "?" as an alias for "*", and 7 accepted as Sunday. The descriptors @hourly, @daily (alias @midnight), @weekly, @monthly, and "@every <duration>" are also accepted. Schedules are evaluated in the server's local time zone and fire at second 0 of the matching minute; for sub-minute periods use "@every <duration>", whose duration must be a positive whole number of seconds ("@every 90s", "@every 1h30m"; "@every 1500ms" is rejected).
As in crontab(5), when both the day-of-month and day-of-week fields are restricted (neither is "*"), the schedule fires when EITHER matches: "0 0 13 * fri" runs on the 13th of the month AND on every Friday. Note that a step applied to "*" (e.g. "*/2" in day-of-month) counts as restricted for this rule.
type ScheduledConfig ¶ added in v0.25.0
type ScheduledConfig struct {
// Tier is the drain tier of the worker's component; zero is TierIngress:
// the worker stops with the listener, so no run starts during the drain.
Tier Tier `json:"tier"`
// RunOnStart adds one run as soon as the worker starts, before the first
// computed activation.
RunOnStart bool `json:"run_on_start"`
// RunTimeout bounds every run, the RunOnStart run included: the run
// context is cancelled with the cause [ErrWorkerRunTimeout], and the run
// is a failure whatever Run returns. The timeout is cooperative; it never
// abandons the goroutine. Zero means no timeout.
RunTimeout time.Duration `json:"run_timeout"`
// MaxConsecutiveFailures makes the worker failed after that many failed
// runs in a row; zero means unlimited.
MaxConsecutiveFailures int `json:"max_consecutive_failures"`
// UnreadyWhenFailed reports the instance unready once the worker is
// failed.
UnreadyWhenFailed bool `json:"unready_when_failed"`
// UnreadyUntilFirstSuccess keeps the instance unready until the worker's
// first run succeeds; once met it stays met. Pair it with RunOnStart
// unless waiting for the first activation is intended.
UnreadyUntilFirstSuccess bool `json:"unready_until_first_success"`
// UnreadyAfterSuccessAge reports the instance unready when the last
// success is older than this; zero turns the check off. It is not applied
// before the first success.
UnreadyAfterSuccessAge time.Duration `json:"unready_after_success_age"`
}
ScheduledConfig configures a scheduled worker. Zero means the default in every field.
type Starter ¶ added in v0.24.0
Starter is the capability of a component the App starts. The start walk calls Start once, after the Start of every component it depends on and before the App accepts requests. Start returns once the component is usable; work that outlives it runs on a goroutine whose context derives from context.WithoutCancel(ctx), stopped by the component's Shutdown. The context ends when Start returns, or earlier when a shutdown is requested during the start phase.
Start is planned from the binding's type, and a component whose binding's type hides its value's Start or Ready is refused — a ProvideValue at the call, a built value at the start — unless another holder of the same resource plans it or the binding is Borrowed; bind the concrete type and the interface with App.Alias. A type with Start but no Shutdown is not a component and is never started. Holders that share a resource identity start it once, and a borrowed resource is not started through any holder. A Start that returns an error has released what it opened; the App does not shut it down.
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 ¶
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 Tier ¶ added in v0.24.0
type Tier uint8
Tier is the drain tier of a component. The ingress tier — where work enters the process: servers, consumers, scheduled workers — stops first, concurrently with the HTTP drain; the internal tier stops after it, in reverse dependency order. The zero Tier is unset and means the registration's default. TierIngress and TierInternal encode as the text "ingress" and "internal".
const ( // TierIngress is the tier that stops first, with the HTTP drain. TierIngress Tier = Tier(di.TierIngress) // TierInternal is the default tier, stopped after the HTTP drain. TierInternal Tier = Tier(di.TierInternal) )
func (Tier) MarshalText ¶ added in v0.24.0
MarshalText encodes the Tier as "ingress", "internal", or "" when unset.
func (Tier) String ¶ added in v0.24.0
String returns "ingress", "internal", or "" for the unset Tier.
func (*Tier) UnmarshalText ¶ added in v0.24.0
UnmarshalText decodes "ingress", "internal", or "" (unset).
type WalkFunc ¶
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 ¶
WalkRoutesFunc is the callback for WalkRoutes. It receives the full RouteInfo including the host pattern. Return a non-nil error to stop walking.
type Worker ¶ added in v0.25.0
Worker is a background task run by the App. The name that identifies it is given at registration (Workers.Continuous, Workers.Scheduled), not by the worker itself. A func(context.Context) error is registered as it is, and a function whose other parameters the container supplies, or a constructor of a worker, is registered in its own form.
A continuous worker's Run must stay active until ctx is cancelled; a scheduled worker's Run performs one activation and returns.
type WorkerInfo ¶ added in v0.25.0
type WorkerInfo struct {
Name string `json:"name"`
Kind WorkerKind `json:"kind"`
// Schedule is the expression of a scheduled worker, as registered; empty
// for a continuous worker.
Schedule string `json:"schedule,omitzero"`
// Continuous is the resolved configuration of a continuous worker; nil
// for a scheduled one. Each snapshot holds its own copy.
Continuous *ContinuousConfig `json:"continuous,omitzero"`
// Scheduled is the resolved configuration of a scheduled worker; nil for
// a continuous one. Each snapshot holds its own copy.
Scheduled *ScheduledConfig `json:"scheduled,omitzero"`
Status WorkerStatus `json:"status"`
// Restarts counts the restarts of a continuous worker that started.
Restarts int64 `json:"restarts"`
// ConsecutiveFailures counts the failed runs of a scheduled worker since
// its last success.
ConsecutiveFailures int64 `json:"consecutive_failures"`
// LastStartedAt is the start time of the most recently admitted run.
LastStartedAt time.Time `json:"last_started_at,omitzero"`
// LastSucceededAt is the completion time of the last successful run of a
// scheduled worker; always zero for a continuous worker.
LastSucceededAt time.Time `json:"last_succeeded_at,omitzero"`
// LastError is the error of the most recent failed run, without any stack
// trace; a successful scheduled run clears it, a graceful stop does not.
LastError string `json:"last_error,omitzero"`
}
WorkerInfo is a point-in-time snapshot of a worker: its identity, its resolved configuration and its live state.
WorkerInfo is shaped for direct JSON encoding, for example from an admin endpoint: field names are snake_case, durations encode as integer nanoseconds under Credo's response profile, and schedule, continuous, scheduled, last_started_at, last_succeeded_at and last_error are omitted while zero.
type WorkerKind ¶ added in v0.25.0
type WorkerKind string
WorkerKind reports whether a worker runs continuously or on a schedule.
const ( // WorkerKindContinuous is a worker whose Run lives until its component // stops. WorkerKindContinuous WorkerKind = "continuous" // WorkerKindScheduled is a worker that runs once per cron activation. WorkerKindScheduled WorkerKind = "scheduled" )
type WorkerRun ¶ added in v0.25.0
type WorkerRun struct {
// Worker is the registration name.
Worker string
// ID is the run's identifier, equal to the run_id of the App's log lines
// for that run.
ID string
// ScheduledAt is the intended activation of a scheduled run; zero for
// continuous runs and for the RunOnStart run.
ScheduledAt time.Time
}
WorkerRun is the execution metadata of one run, carried by the context passed to Run.
func CurrentWorkerRun ¶ added in v0.25.0
CurrentWorkerRun returns the metadata of the run that ctx belongs to, and false with a zero WorkerRun for a context that is not a run context.
Example ¶
package main
import (
"context"
"fmt"
"log/slog"
"github.com/credo-go/credo"
)
// reportOnce is a scheduled worker that prints its run metadata and closes
// done.
type reportOnce struct{ done chan struct{} }
func (w reportOnce) Run(ctx context.Context) error {
defer close(w.done)
run, ok := credo.CurrentWorkerRun(ctx)
fmt.Println("run context:", ok)
fmt.Println("worker:", run.Worker)
fmt.Println("run id set:", run.ID != "")
fmt.Println("run on start, so no activation time:", run.ScheduledAt.IsZero())
return nil
}
func main() {
app, err := credo.New(credo.WithLogger(slog.New(slog.DiscardHandler)))
if err != nil {
panic(err)
}
done := make(chan struct{})
app.Workers().Scheduled("report", "@every 1h", reportOnce{done: done}, credo.ScheduledConfig{RunOnStart: true})
_, ok := credo.CurrentWorkerRun(context.Background())
fmt.Println("outside a run:", ok)
if err = app.Start(context.Background()); err != nil {
panic(err)
}
<-done
if err = app.Shutdown(context.Background()); err != nil {
panic(err)
}
}
Output: outside a run: false run context: true worker: report run id set: true run on start, so no activation time: true
type WorkerStatus ¶ added in v0.25.0
type WorkerStatus string
WorkerStatus is a worker's lifecycle state.
const ( // WorkerStatusPending means the worker's component has not started, or a // continuous worker has not yet been admitted to its first run. WorkerStatusPending WorkerStatus = "pending" // WorkerStatusRunning means a run has been admitted and is executing. WorkerStatusRunning WorkerStatus = "running" // WorkerStatusBackoff means a continuous worker is waiting to restart // after a failure: unhealthy, recovering. WorkerStatusBackoff WorkerStatus = "backoff" // WorkerStatusWaiting means a scheduled worker is waiting for its next // activation, whatever its last run did. WorkerStatusWaiting WorkerStatus = "waiting" // WorkerStatusStopped means the loop ended because the worker's component // was shut down; the worker will not run again. WorkerStatusStopped WorkerStatus = "stopped" // WorkerStatusFailed means a positive failure limit was exhausted, // restarts are disabled and a run failed, or the schedule has no future // activation. It is permanent until the application restarts. WorkerStatusFailed WorkerStatus = "failed" )
type Workers ¶ added in v0.25.0
type Workers struct {
// contains filtered or unexported fields
}
Workers is the App's worker registry, which App.Workers returns. It is a registry, not a lifecycle: each registration adds the worker to the App as a component named "worker:<name>", which the App starts and stops in its tier like every other component. Workers has no Start, no Shutdown and no DI binding.
func (*Workers) Continuous ¶ added in v0.25.0
func (s *Workers) Continuous(name string, w any, cfg ...ContinuousConfig)
Continuous registers w under name as a continuous worker: its Run is called once when the worker starts and must stay active until its context is cancelled; a failed run — an error, a panic, or a nil return before shutdown — is restarted under cfg's RestartPolicy. A restart runs the same worker again, so a run must be re-enterable.
w takes one of three forms:
- a worker: a value whose type implements Worker, or a func(context.Context) error, named function types of that signature included. It has no edges the dependency graph can see and takes its place in its tier by registration order.
- a run function: a function that takes exactly one context.Context, in any position, and returns only an error, such as func(ctx context.Context, db *sqldb.DB) error or the method expression (*OutboxRelay).Run of a bound worker. Its other parameters are resolved from the container once, after their components have started, and each run calls the function with that run's context and those values.
- a constructor of a worker: func(deps...) W or func(deps...) (W, error), where W is a worker in either form. The start walk builds it after its dependencies have started, and the value it builds, the component "worker-value:<name>", is not a binding: nothing resolves it, each registration calls its constructor separately, and it is torn down, in the internal tier, after the worker has stopped. A value it builds that a binding or a value handed to App.Manage also holds — the binding's own value, or a wrapper that embeds its handle — shares that registration's readiness entry and teardown. A constructor that returns a method value hands over the function alone, which has no teardown.
The worker is a component of the App, in cfg's tier (internal by default), and stops before what its parameters depend on.
Continuous takes at most one configuration and panics on misuse: a nil worker, a w of none of the three forms, an invalid or duplicate name, more than one configuration, a rejected value, or a call after Finalize. Finalize reports a missing parameter, and the start a constructor's error, panic or nil worker.
func (*Workers) Lookup ¶ added in v0.25.0
func (s *Workers) Lookup(name string) (WorkerInfo, bool)
Lookup returns the worker registered under exactly name, or false. A name it does not know is the caller's error to report, never a pass.
func (*Workers) Scheduled ¶ added in v0.25.0
func (s *Workers) Scheduled(name, expr string, w any, cfg ...ScheduledConfig)
Scheduled registers w under name as a scheduled worker that runs once per activation of the cron expression expr. Runs never overlap: activations that pass during a run are skipped and logged. A failed run counts toward cfg.MaxConsecutiveFailures.
w is a worker, a run function or a constructor of a worker, as for Workers.Continuous. The worker is a component of the App, in cfg's tier (ingress by default: it stops with the listener, so no run starts during the drain); the value a constructor builds is internal, torn down after the HTTP drain. Every replica runs every schedule.
Scheduled panics on misuse — a nil worker, a w of none of the three forms, an invalid or duplicate name, more than one configuration, a rejected value, an expression that does not parse (ParseSchedule returns that error instead), a call after Finalize.
Example (Constructor) ¶
package main
import (
"context"
"fmt"
"log/slog"
"time"
"github.com/credo-go/credo"
)
// invoiceSweeper is a scheduled worker built by the DI container.
type invoiceSweeper struct {
log *slog.Logger
}
func newInvoiceSweeper(infra credo.Infra) *invoiceSweeper {
return &invoiceSweeper{log: infra.Logger}
}
// Run performs one activation.
func (s *invoiceSweeper) Run(ctx context.Context) error {
run, _ := credo.CurrentWorkerRun(ctx)
s.log.InfoContext(ctx, "sweeping invoices", "run_id", run.ID)
return nil
}
func main() {
app, err := credo.New()
if err != nil {
panic(err)
}
// The constructor is not a binding: the start walk builds the worker
// after its parameters' components have started, and nothing else
// resolves it.
app.Workers().Scheduled("invoice-sweeper", "@every 1m", newInvoiceSweeper, credo.ScheduledConfig{
RunOnStart: true,
RunTimeout: 15 * time.Second,
MaxConsecutiveFailures: 3,
})
info, ok := app.Workers().Lookup("invoice-sweeper")
fmt.Println(ok, info.Kind, info.Schedule)
fmt.Println(info.Scheduled.Tier, info.Scheduled.RunOnStart, info.Scheduled.RunTimeout,
info.Scheduled.MaxConsecutiveFailures)
}
Output: true scheduled @every 1m ingress true 15s 3
func (*Workers) Snapshot ¶ added in v0.25.0
func (s *Workers) Snapshot() []WorkerInfo
Snapshot returns one WorkerInfo per worker of the App, in registration order: its resolved configuration and its live state.
Source Files
¶
- accesslog.go
- appconfig.go
- bind.go
- binderror.go
- component.go
- compress.go
- context.go
- credo.go
- decompress.go
- di.go
- dierrors.go
- dispatch.go
- doc.go
- envelopebypass.go
- errorcode.go
- errors.go
- executor.go
- features.go
- finalize_trigger.go
- group.go
- handler.go
- health.go
- host.go
- i18n.go
- infra.go
- interfaces.go
- json.go
- lifecycle.go
- lifecycle_error.go
- lifecycle_manager.go
- lifecycle_start.go
- mux.go
- pool.go
- prepare.go
- recover.go
- reload.go
- request.go
- requestid.go
- response.go
- route.go
- routectx.go
- server.go
- signal_unix.go
- sourceloc.go
- static.go
- stdmiddleware.go
- tls_rotation.go
- urlgen.go
- user.go
- walk.go
- worker.go
- workers.go
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 readiness engine the root package runs them through.
|
Package health defines stable, bounded health probes and the readiness engine the root package runs them through. |
|
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. |
|
worker
Package worker is the engine behind the root package's workers: the run loop of each kind, the restart backoff, the run outcome classification, the schedule loop and the cron parser.
|
Package worker is the engine behind the root package's workers: the run loop of each kind, the restart backoff, the run outcome classification, the schedule loop and the cron parser. |
|
Package middleware provides built-in HTTP middleware for the Credo framework.
|
Package middleware provides built-in HTTP middleware for the Credo framework. |
|
ratelimit
Package ratelimit provides token-bucket rate-limiting middleware for the Credo framework, over go-limiter's store contract.
|
Package ratelimit provides token-bucket rate-limiting middleware for the Credo framework, over go-limiter's store contract. |
|
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, starting an App served through ServeHTTP, 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, starting an App served through ServeHTTP, 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. |