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(c *credo.Context) error {
return c.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. Four tiers run in order: PreRouting (before the match, 404 and 405 included) → routed (App.Middleware, every route and mount) → group → route. Routed and group middleware are 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).
- 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). The access log is one Observer of the final response; App.AddObserver adds others, which receive the same Exchange.
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. Reload follows the same split by cause: it re-reads files and runs the live sections' callbacks, so App.Reload returns an error, and so does declaring a section live over a configuration that cannot reload, a constructor error at Resolve or at start.
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(c *credo.Context) error {
return c.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
Example (MatchingOrder) ¶
The first candidate that matches the path and serves the method answers; a 405 lists the methods of every candidate that matches the path.
package main
import (
"fmt"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"github.com/credo-go/credo"
)
// newExampleApp returns an App that loads no configuration from disk and logs
// nowhere, so an example's output is its own.
func newExampleApp() *credo.App {
app, err := credo.New(credo.WithLogger(slog.New(slog.DiscardHandler)))
if err != nil {
panic(err)
}
return app
}
// exServe sends one request through app and prints the status, the Allow or
// Location header when set, and the body.
func exServe(app *credo.App, method, target string) {
req := httptest.NewRequest(method, target, nil)
rec := httptest.NewRecorder()
app.ServeHTTP(rec, req)
line := fmt.Sprintf("%s %s → %d", method, target, rec.Code)
if allow := rec.Header().Get("Allow"); allow != "" {
line += " Allow: " + allow
}
if loc := rec.Header().Get("Location"); loc != "" {
line += " Location: " + loc
}
if body, _ := io.ReadAll(rec.Body); len(body) > 0 {
line += " " + string(body)
}
fmt.Println(line)
}
// exText answers with s.
func exText(s string) credo.Handler {
return func(c *credo.Context) error { return c.Response().Text(http.StatusOK, s) }
}
func main() {
app := newExampleApp()
app.GET("/users/new", exText("newUserForm"))
app.POST("/users/{id}", func(c *credo.Context) error {
return c.Response().Text(http.StatusOK, "updateUser "+c.Request().RouteParam("id"))
})
exServe(app, http.MethodGet, "/users/new")
exServe(app, http.MethodPost, "/users/new")
exServe(app, http.MethodDelete, "/users/new")
}
Output: GET /users/new → 200 newUserForm POST /users/new → 200 updateUser new DELETE /users/new → 405 Allow: GET, HEAD, POST {"success":false,"error":{"code":"method_not_allowed","message":"Method Not Allowed"}}
Example (ParameterNames) ¶
Route names belong to the endpoint: routes that share a dynamic segment name it each their own way, and a parameter value is decoded once.
package main
import (
"fmt"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"github.com/credo-go/credo"
)
// newExampleApp returns an App that loads no configuration from disk and logs
// nowhere, so an example's output is its own.
func newExampleApp() *credo.App {
app, err := credo.New(credo.WithLogger(slog.New(slog.DiscardHandler)))
if err != nil {
panic(err)
}
return app
}
// exServe sends one request through app and prints the status, the Allow or
// Location header when set, and the body.
func exServe(app *credo.App, method, target string) {
req := httptest.NewRequest(method, target, nil)
rec := httptest.NewRecorder()
app.ServeHTTP(rec, req)
line := fmt.Sprintf("%s %s → %d", method, target, rec.Code)
if allow := rec.Header().Get("Allow"); allow != "" {
line += " Allow: " + allow
}
if loc := rec.Header().Get("Location"); loc != "" {
line += " Location: " + loc
}
if body, _ := io.ReadAll(rec.Body); len(body) > 0 {
line += " " + string(body)
}
fmt.Println(line)
}
func main() {
app := newExampleApp()
app.GET("/v1/crm/customers/{id}", func(c *credo.Context) error {
return c.Response().Text(http.StatusOK, "id="+c.Request().RouteParam("id"))
})
app.GET("/v1/crm/customers/{customer_id}/timeline", func(c *credo.Context) error {
return c.Response().Text(http.StatusOK, "customer_id="+c.Request().RouteParam("customer_id"))
})
exServe(app, http.MethodGet, "/v1/crm/customers/a%2Fb")
exServe(app, http.MethodGet, "/v1/crm/customers/%252F/timeline")
}
Output: GET /v1/crm/customers/a%2Fb → 200 id=a/b GET /v1/crm/customers/%252F/timeline → 200 customer_id=%2F
Example (TrailingSlashRedirect) ¶
A path that matches only with its trailing slash toggled is redirected: 301 for GET and HEAD, 308 otherwise, the query preserved.
package main
import (
"fmt"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"github.com/credo-go/credo"
)
// newExampleApp returns an App that loads no configuration from disk and logs
// nowhere, so an example's output is its own.
func newExampleApp() *credo.App {
app, err := credo.New(credo.WithLogger(slog.New(slog.DiscardHandler)))
if err != nil {
panic(err)
}
return app
}
// exServe sends one request through app and prints the status, the Allow or
// Location header when set, and the body.
func exServe(app *credo.App, method, target string) {
req := httptest.NewRequest(method, target, nil)
rec := httptest.NewRecorder()
app.ServeHTTP(rec, req)
line := fmt.Sprintf("%s %s → %d", method, target, rec.Code)
if allow := rec.Header().Get("Allow"); allow != "" {
line += " Allow: " + allow
}
if loc := rec.Header().Get("Location"); loc != "" {
line += " Location: " + loc
}
if body, _ := io.ReadAll(rec.Body); len(body) > 0 {
line += " " + string(body)
}
fmt.Println(line)
}
// exText answers with s.
func exText(s string) credo.Handler {
return func(c *credo.Context) error { return c.Response().Text(http.StatusOK, s) }
}
func main() {
app := newExampleApp()
app.GET("/users", exText("users"))
app.POST("/users", exText("created"))
exServe(app, http.MethodGet, "/users/?page=2")
exServe(app, http.MethodPost, "/users/")
}
Output: GET /users/?page=2 → 301 Location: /users?page=2 POST /users/ → 308 Location: /users
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
- type AccessLogConfig
- type App
- func (app *App) AddLivenessCheck(name string, checker HealthChecker)
- func (app *App) AddObserver(o Observer)
- 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](section config.Section[T]) (T, error)
- func (app *App) GetRoute(name string) *Route
- 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) Middleware(middlewares ...Middleware)
- func (app *App) Mount(pattern string, handler http.Handler)
- func (app *App) MustGetConfig[T any](section config.Section[T]) 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) 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) PreRouting(middlewares ...Middleware)
- 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) (config.ReloadResult, error)
- func (app *App) RemoveMeta[T any](key Key[T])
- 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[T any](key Key[T], val T)
- 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) UseModules(mods ...Module)
- 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[T any](key Key[T]) (T, bool)
- func (c *Context) GetUser[T any]() (T, bool)
- func (c *Context) HasRequestLogger() bool
- func (c *Context) HasRoute() 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) Route() *Route
- func (c *Context) Set[T any](key Key[T], val T)
- 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
- func (c *Context) Within(ctx context.Context, next Handler) error
- type ContinuousConfig
- type DIPanicError
- type DIPanicPhase
- type DecompressConfig
- type ErrorBody
- type ErrorInfo
- type ErrorRenderer
- type ErrorResponse
- type Exchange
- func (ex *Exchange) Bytes() int64
- func (ex *Exchange) Context() context.Context
- func (ex *Exchange) Duration() time.Duration
- func (ex *Exchange) ErrorCode() string
- func (ex *Exchange) Get[T any](key Key[T]) (T, bool)
- func (ex *Exchange) GetUser[T any]() (T, bool)
- func (ex *Exchange) Method() string
- func (ex *Exchange) OriginalPath() string
- func (ex *Exchange) PanicRecovered() bool
- func (ex *Exchange) Path() string
- func (ex *Exchange) RemoteAddr() string
- func (ex *Exchange) RequestID() string
- func (ex *Exchange) Route() string
- func (ex *Exchange) RouteName() string
- func (ex *Exchange) Status() int
- func (ex *Exchange) UserAgent() string
- 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[T any](key Key[T]) *Group
- func (g *Group) SetMeta[T any](key Key[T], val T) *Group
- 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 Key
- type LifecycleEntry
- type LifecycleError
- type LifecycleOutcome
- type LifecyclePhase
- type MessageKey
- type MessageKeyResolver
- type MessageRef
- type MessageScope
- type Middleware
- type Module
- type Observer
- 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) Context() context.Context
- 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
- func (r *Request) Std() *http.Request
- 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) 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) GetMeta[T any](key Key[T]) (T, bool)
- func (r *Route) GetMethod() string
- func (r *Route) GetName() string
- func (r *Route) GetPattern() string
- func (r *Route) Middleware(m ...Middleware) *Route
- func (r *Route) Name(name string) *Route
- func (r *Route) RemoveMeta[T any](key Key[T]) *Route
- func (r *Route) SetMeta[T any](key Key[T], val T) *Route
- type RouteInfo
- type RouteKind
- type Schedule
- type ScheduledConfig
- type Starter
- type StaticCacheContext
- type StaticConfig
- type StaticRoute
- func (sr *StaticRoute) BuildURI(filePath string) (string, error)
- func (sr *StaticRoute) Middleware(m ...Middleware) *StaticRoute
- func (sr *StaticRoute) Name(name string) *StaticRoute
- func (sr *StaticRoute) RemoveMeta[T any](key Key[T]) *StaticRoute
- func (sr *StaticRoute) SetMeta[T any](key Key[T], val T) *StaticRoute
- type StdMiddleware
- type SuccessRenderer
- type Tier
- type Worker
- type WorkerInfo
- type WorkerKind
- type WorkerRun
- type WorkerStatus
- type Workers
Examples ¶
- Package (BootstrapOrder)
- Package (MatchingOrder)
- Package (ParameterNames)
- Package (TrailingSlashRedirect)
- App.AddObserver
- App.Host
- App.Middleware
- App.Mount
- App.Routes
- App.ServeHTTP (Stopped)
- App.Shutdown
- App.Start
- App.StatusHandler
- App.Workers
- BindError
- Context.Render
- Context.Set
- Context.Within
- CurrentWorkerRun
- NewKey
- Request.BindBody
- Request.BindQuery
- Response.JSON
- Route.BuildURI
- WithJSONOptions
- Workers.Scheduled (Constructor)
- WrapStdMiddleware
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 ( // CodeValidationFailed is the 422 code for validation errors. CodeValidationFailed = "validation_failed" // CodeBindFailed is the 400 code for a request body or parameter that // cannot be decoded into its target ([BindError]). CodeBindFailed = "bind_failed" // CodeUnsupportedContentEncoding is the 415 code for a request body whose // Content-Encoding the decompression feature ([App.UseDecompress]) has // not unwrapped. The encoding is in the details, under "encoding". CodeUnsupportedContentEncoding = "unsupported_content_encoding" // CodeInvalidBindTarget is the 500 code for a bind target the binder // cannot fill — nil, not a pointer, or with a field of a type it does not // bind — a developer error, reported without client-facing detail and // logged with the reason. CodeInvalidBindTarget = "invalid_bind_target" )
Framework error codes carried on the wire in addition to the status-derived defaults (see errorcode.go). A code a status derives needs no constant: NewHTTPError(http.StatusNotFound) carries "not_found".
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).
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.
var MetaAccessLog = NewKey[bool]("credo.accesslog")
MetaAccessLog is the route-meta key that toggles built-in access logging for a route — or, inherited through the group parent chain, 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 (Route.GetMeta reads the route before its parents), so a noisy group can be silenced while one route inside it stays logged, with true.
Health probes use it internally; see HealthConfig.LogRequests.
var MetaRawResponse = NewKey[bool]("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.
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.
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.
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
// [Exchange], and emits the record on true. It cannot restore a record
// MinLevel rejected. It may be called concurrently for multiple requests
// and must be concurrency-safe. A panic inside it is logged as a
// framework diagnostic and the record is skipped; with [WithoutRecover]
// the panic propagates.
ResultFilter func(ex *Exchange) bool
// Attrs returns application attributes for a record that is a candidate
// for emission: after MetaAccessLog, MinLevel and ResultFilter, and only
// when the logger is enabled for the record's level. They are emitted
// inside one "attrs" group, so an application attribute never shadows a
// framework attribute; "attrs" is a reserved key on the access record.
// The returned slice passes to the framework and must not be reused. A
// panic inside Attrs is logged as a framework diagnostic and the record
// is emitted without the group; with [WithoutRecover] the panic
// propagates. Attrs may be called concurrently and must be
// concurrency-safe.
Attrs func(ex *Exchange) []slog.Attr
}
AccessLogConfig configures the access-log feature installed by App.UseAccessLog. The zero value selects every default.
type App ¶
type App struct {
// contains filtered or unexported fields
}
App is the main Credo application. It holds the router, middleware stack, 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) AddObserver ¶ added in v0.26.0
AddObserver adds o to the observers of every request's final response. Observers run in registration order; App.UseAccessLog registers the access log in the same order. AddObserver panics for a nil observer and after the App was prepared or shut down.
Example ¶
Observers see the final response — an error envelope included — with the classified error code and the request's values.
app := newExampleApp()
app.UseRequestID()
app.AddObserver(exObserver{})
app.GET("/orders/{id}", func(c *credo.Context) error {
c.Set(Tenant, &TenantInfo{Name: "acme"})
return credo.NewHTTPError(http.StatusConflict)
})
req := httptest.NewRequest(http.MethodGet, "/orders/7", nil)
req.Header.Set("X-Request-ID", "req-1")
rec := httptest.NewRecorder()
app.ServeHTTP(rec, req)
fmt.Println(rec.Code, rec.Header().Get("X-Request-ID"))
Output: GET /orders/{id} 409 conflict req-1 acme 409 req-1
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 section from the application's RawConfig (auto-loaded or supplied via WithRawConfig) with config.Section.Decode. It is the composition root's reader, for code that holds the App rather than its configuration:
var DatabaseSection = config.Section[DatabaseConfig]("database")
db, err := app.GetConfig(DatabaseSection)
db, err := app.GetConfig[DatabaseConfig]("database") // the untyped key converts
A service receives its section through the container instead, bound with app.Provide(DatabaseSection.Decode); a handler cannot reach this method, as there is no App accessor on *Context. A missing section, a decode failure or a failed validation returns an error naming the key, with the zero value of T.
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.
Example ¶
A host pattern selects its own routes before the path lookup, and its parameters share the route's namespace.
package main
import (
"fmt"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"github.com/credo-go/credo"
)
// newExampleApp returns an App that loads no configuration from disk and logs
// nowhere, so an example's output is its own.
func newExampleApp() *credo.App {
app, err := credo.New(credo.WithLogger(slog.New(slog.DiscardHandler)))
if err != nil {
panic(err)
}
return app
}
// exServe sends one request through app and prints the status, the Allow or
// Location header when set, and the body.
func exServe(app *credo.App, method, target string) {
req := httptest.NewRequest(method, target, nil)
rec := httptest.NewRecorder()
app.ServeHTTP(rec, req)
line := fmt.Sprintf("%s %s → %d", method, target, rec.Code)
if allow := rec.Header().Get("Allow"); allow != "" {
line += " Allow: " + allow
}
if loc := rec.Header().Get("Location"); loc != "" {
line += " Location: " + loc
}
if body, _ := io.ReadAll(rec.Body); len(body) > 0 {
line += " " + string(body)
}
fmt.Println(line)
}
// exText answers with s.
func exText(s string) credo.Handler {
return func(c *credo.Context) error { return c.Response().Text(http.StatusOK, s) }
}
func main() {
app := newExampleApp()
app.GET("/", exText("landing"))
api := app.Host("api.example.com")
api.GET("/users", exText("users"))
tenant := app.Host("{tenant}.example.com")
tenant.GET("/dashboard", func(c *credo.Context) error {
return c.Response().Text(http.StatusOK, c.Request().RouteParam("tenant"))
})
exServe(app, http.MethodGet, "http://example.org/")
exServe(app, http.MethodGet, "http://API.example.com:8080/users")
exServe(app, http.MethodGet, "http://acme.example.com/dashboard")
}
Output: GET http://example.org/ → 200 landing GET http://API.example.com:8080/users → 200 users GET http://acme.example.com/dashboard → 200 acme
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) Middleware ¶ added in v0.26.0
func (app *App) Middleware(middlewares ...Middleware)
Middleware appends middleware to the routed tier: it runs on every route registered through the App — directly, in a group, in a host group, as a static route or as a mount — after the match and before group and route middleware, so it reads the matched route and its meta:
app.Middleware(middleware.ContractGuard()) // never runs for a 404 or a 405
It does not run for the router's own 404 and 405, which reach the App.PreRouting tier only. Like group middleware it is collected when the routes' chains are compiled, so it applies to routes registered before the call too. Must be called before the server starts; panics if called after compile.
Example ¶
The user chain runs PreRouting → routed → group → route → handler; the router's own 404 runs PreRouting alone.
tier := func(name string) credo.Middleware {
return func(next credo.Handler) credo.Handler {
return func(c *credo.Context) error {
fmt.Println(name)
return next(c)
}
}
}
app := newExampleApp()
app.PreRouting(tier("PreRouting"))
app.Middleware(tier("routed"))
api := app.Group("/api")
api.Middleware(tier("group"))
api.GET("/users", exText("users")).Middleware(tier("route"))
exServe(app, http.MethodGet, "/api/users")
exServe(app, http.MethodGet, "/missing")
Output: PreRouting routed group route GET /api/users → 200 users PreRouting GET /missing → 404 {"success":false,"error":{"code":"not_found","message":"Not Found"}}
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 c.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.
A mount is a route: a request it matches carries a Route whose pattern is the mount's prefix, with the App's meta and no name or method, so Context.HasRoute is true for it and its access record names the prefix. The route carries none of the prefix's parameters: they reach the mounted handler as path values, so a routed middleware on a parametric mount reads none through Request.RouteParam.
Middleware scope: the mounted handler runs inside the routed tier (App.Middleware), after App.PreRouting and the framework features that wrap every request, through a chain compiled as a route's is. A mount belongs to no group and has no route value of its own, so group and route middleware do not apply to it. Authentication registered with App.Middleware covers the mounted paths too.
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.
Example ¶
A mount hands its handler the path below the prefix in its wire spelling, and a parametric prefix's values as stdlib path values.
package main
import (
"fmt"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"github.com/credo-go/credo"
)
// newExampleApp returns an App that loads no configuration from disk and logs
// nowhere, so an example's output is its own.
func newExampleApp() *credo.App {
app, err := credo.New(credo.WithLogger(slog.New(slog.DiscardHandler)))
if err != nil {
panic(err)
}
return app
}
// exServe sends one request through app and prints the status, the Allow or
// Location header when set, and the body.
func exServe(app *credo.App, method, target string) {
req := httptest.NewRequest(method, target, nil)
rec := httptest.NewRecorder()
app.ServeHTTP(rec, req)
line := fmt.Sprintf("%s %s → %d", method, target, rec.Code)
if allow := rec.Header().Get("Allow"); allow != "" {
line += " Allow: " + allow
}
if loc := rec.Header().Get("Location"); loc != "" {
line += " Location: " + loc
}
if body, _ := io.ReadAll(rec.Body); len(body) > 0 {
line += " " + string(body)
}
fmt.Println(line)
}
func main() {
app := newExampleApp()
adminMux := http.NewServeMux()
adminMux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, r.URL.EscapedPath())
})
app.Mount("/admin", adminMux)
app.Mount("/t/{tenant}", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, r.PathValue("tenant")+" "+r.URL.EscapedPath())
}))
exServe(app, http.MethodGet, "/admin/a%2Fb")
exServe(app, http.MethodGet, "/admin")
exServe(app, http.MethodGet, "/t/ac%2Fme/x")
}
Output: GET /admin/a%2Fb → 200 /a%2Fb GET /admin → 200 / GET /t/ac%2Fme/x → 200 ac/me /x
func (*App) MustGetConfig ¶
MustGetConfig is like App.GetConfig but panics on error. It suits composition-root code where a missing or invalid required section 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) 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) PreRouting ¶ added in v0.26.0
func (app *App) PreRouting(middlewares ...Middleware)
PreRouting appends middleware that runs before the match, on every request, the router's own 404 and 405 included. No route is matched yet, so a middleware here cannot read route meta: one that does belongs on App.Middleware. PreRouting is for what acts before the match or on a request no route matches — CORS answering a preflight, Rewrite changing the path that routing matches, Secure's headers and a rate limit that cover the 404 and 405 too.
The user tiers run PreRouting → App.Middleware → Group.Middleware → Route.Middleware, each in registration order. Must be called before the server starts; panics if called after compile.
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 re-reads the configuration and applies it to its live sections (ADR-020) through config.Config.Reload, and returns that reload's result: the keys it changed, the live sections it replaced, the keys whose change takes a restart and the file keys a later source keeps. A section bound through config.Section.Decode is a snapshot, and its changed keys are reported as needing a restart, as is every changed key outside a live section; a reload never rebuilds a DI singleton (ADR-004). Reload logs the result, so an endpoint or an orchestrator hook that calls it can also return it to the operator.
A live section that fails to decode or validate aborts the reload: nothing is published, the result says so and why, and the error names the section. An config.Live.OnChange callback's error or panic is joined into the returned error after the publish; nothing rolls back, and the process never terminates.
Reload succeeds only while the server is running, and only over a configuration built by config.Load or config.LoadBytes: any other RawConfig cannot reload, and Reload returns an error naming its type. 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. The callbacks receive 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 the internal tier (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. Configuration files are not watched.
func (*App) RemoveMeta ¶
RemoveMeta removes the App's value of a meta key. Must be called before the server starts; panics if called after compile, and for a zero Key.
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 meta (RouteInfo.GetMeta), 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 is freshly allocated; the caller owns it.
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.
Example ¶
app.Routes returns every route and every mount in a deterministic order.
package main
import (
"fmt"
"log/slog"
"net/http"
"github.com/credo-go/credo"
)
// newExampleApp returns an App that loads no configuration from disk and logs
// nowhere, so an example's output is its own.
func newExampleApp() *credo.App {
app, err := credo.New(credo.WithLogger(slog.New(slog.DiscardHandler)))
if err != nil {
panic(err)
}
return app
}
// exText answers with s.
func exText(s string) credo.Handler {
return func(c *credo.Context) error { return c.Response().Text(http.StatusOK, s) }
}
func main() {
app := newExampleApp()
app.GET("/users/{id}", exText("user")).Name("user.show")
app.Mount("/admin", http.NotFoundHandler())
for _, ri := range app.Routes() {
if ri.Kind == credo.RouteKindMount {
fmt.Println("mount", ri.Pattern, ri.Methods)
continue
}
fmt.Println(ri.Method, ri.Pattern, ri.Name, ri.AutoHead)
}
}
Output: mount /admin [DELETE GET HEAD OPTIONS PATCH POST PUT QUERY] GET /users/{id} user.show false HEAD /users/{id} true
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.
Example (Stopped) ¶
A stopped App answers every request with the callback-free 503 envelope, and cannot be run again.
app := newExampleApp()
app.GET("/", exText("hello"))
exServe(app, http.MethodGet, "/")
if err := app.Shutdown(context.Background()); err != nil {
panic(err)
}
exServe(app, http.MethodGet, "/")
fmt.Println(app.Start(context.Background()))
Output: GET / → 200 hello GET / → 503 {"success":false,"error":{"code":"service_unavailable","message":"Service Unavailable"}} credo: Start: app cannot be run after shutdown; create a new App
func (*App) SetMeta ¶
SetMeta sets the App's value of a meta key, which every route inherits unless a group or the route sets the key itself. Must be called before the server starts; panics if called after compile, and for a zero Key.
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.
Example ¶
The start walk starts the internal tier in dependency order, then its start hooks, then the ingress tier and its hooks. The drain stops the ingress tier — its stop hooks LIFO, then its components — beside the HTTP drain, then the internal tier the same way, components in reverse dependency order.
app := newExampleApp()
app.Provide(func() *exDB { return &exDB{} })
app.Provide(func(db *exDB) *exRepo { return &exRepo{db: db} })
app.Manage(&exConsumer{}, credo.Ingress())
app.OnStart(hook("internal OnStart 1"))
app.OnStart(hook("internal OnStart 2"))
app.OnStart(hook("ingress OnStart"), credo.Ingress())
app.OnStop(hook("internal OnStop 1"))
app.OnStop(hook("internal OnStop 2"))
app.OnStop(hook("ingress OnStop"), credo.Ingress())
ctx := context.Background()
if err := app.Start(ctx); err != nil {
panic(err)
}
fmt.Println("state:", app.State())
if err := app.Shutdown(ctx); err != nil {
panic(err)
}
fmt.Println("state:", app.State())
Output: start db start repo internal OnStart 1 internal OnStart 2 start consumer ingress OnStart state: running ingress OnStop stop consumer internal OnStop 2 internal OnStop 1 stop repo stop db state: stopped
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.
Example ¶
An App with something to start refuses ServeHTTP until its start phase has run.
app := newExampleApp()
app.Provide(func() *exDB { return &exDB{} })
app.GET("/", exText("hello"))
func() {
defer func() { fmt.Println("panics before Start:", recover() != nil) }()
app.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/", nil))
}()
if err := app.Start(context.Background()); err != nil {
panic(err)
}
defer func() { _ = app.Shutdown(context.Background()) }()
exServe(app, http.MethodGet, "/")
Output: panics before Start: true start db GET / → 200 hello stop db
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 App.PreRouting middleware and without a matched route (Context.HasRoute reports false); the routed tier does not run.
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.
Example ¶
A custom 404 answers when no route matches; it is not an error handler.
package main
import (
"fmt"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"github.com/credo-go/credo"
)
// newExampleApp returns an App that loads no configuration from disk and logs
// nowhere, so an example's output is its own.
func newExampleApp() *credo.App {
app, err := credo.New(credo.WithLogger(slog.New(slog.DiscardHandler)))
if err != nil {
panic(err)
}
return app
}
// exServe sends one request through app and prints the status, the Allow or
// Location header when set, and the body.
func exServe(app *credo.App, method, target string) {
req := httptest.NewRequest(method, target, nil)
rec := httptest.NewRecorder()
app.ServeHTTP(rec, req)
line := fmt.Sprintf("%s %s → %d", method, target, rec.Code)
if allow := rec.Header().Get("Allow"); allow != "" {
line += " Allow: " + allow
}
if loc := rec.Header().Get("Location"); loc != "" {
line += " Location: " + loc
}
if body, _ := io.ReadAll(rec.Body); len(body) > 0 {
line += " " + string(body)
}
fmt.Println(line)
}
func main() {
app := newExampleApp()
app.StatusHandler(http.StatusNotFound, func(c *credo.Context) error {
return c.Response().JSON(http.StatusNotFound, map[string]string{"error": "not found"})
})
exServe(app, http.MethodGet, "/missing")
}
Output: GET /missing → 404 {"error":"not found"}
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, and the application's attributes from Attrs in an "attrs" group. The access log is an Observer: it records the final response — error rendering, panic recovery and response finalization included — so status and bytes are what the client received, and it runs among the observers in the order UseAccessLog was called relative to App.AddObserver. Order: Skipper → request → MetaAccessLog → status/level → MinLevel → ResultFilter → logger level → Attrs → 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 the PreRouting 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) UseModules ¶ added in v0.26.0
UseModules runs every module's Services in order, then every module's Handlers in order:
app.UseModules(users.Module{}, billing.Module{})
The services of a later module are therefore registered before the handlers of an earlier one resolve. A registration from a Handlers method after the first Resolve panics as every late registration does, naming the call that finalized the container.
UseModules is called once: a second call would register its services after the first call's handlers had finalized the container, so it panics, naming the remedy of passing every module to one call. It panics too, like every Use* registration, when called 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.
Example ¶
A decode failure is a typed *credo.BindError, rendered as 400 bind_failed with one violation whose code is the reason.
type Person struct {
Age int `json:"age"`
}
app := newExampleApp()
app.POST("/people", func(c *credo.Context) error {
var p Person
return c.Request().BindBody(&p)
})
exPost(app, "/people", `{"name":"x","age":"12"}`)
Output: 400 {"success":false,"error":{"code":"bind_failed","message":"Malformed Request","violations":[{"field":"age","code":"type_mismatch","message":"must be of type integer","params":{"expected":"integer","offset":18}}]}}
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 the request's values.
Each request gets its own Context, one allocation that holds its Request, its Response and the first route parameters. A *Context kept past its request reads that request's state and no other. It is not safe for concurrent use: its context head moves as scopes return. Its response cannot be written after the handler returns, as net/http forbids for every ResponseWriter.
Context does not implement context.Context: its head moves as scopes open and return, so a *Context held as a context.Context would not be one fixed context. Call Context.Context to obtain the request's context.Context, a fixed node, 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 Context for w and r without an App. It is for unit tests of the hooks that take a *Context — a locale detector, a Skipper, an ErrorRenderer, the middleware around an auth.Authenticator — and of a Request or a Response, taken with Context.Request and Context.Response.
A Context built without an App has what the App supplies to a served request missing: no route (Context.Route is nil and there are no route parameters), no request ID unless one is set, no translation (the locale is empty and Context.T returns its key), no trusted proxies (Request.RealIP and Request.Scheme read the peer alone), the package default logger, the framework's default JSON profile and multipart memory limit, no strict body decoding, and no success renderer (Context.Render writes plain JSON). Nothing finalizes it: a returned error is not rendered, and no observer or access record sees the request.
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:
c.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 request's current context.Context, its head: the request's own context, the values set with Context.Set as nodes over it, and the deadline or span of the scope it is read in (Context.Within, a stdlib middleware wrapped with WrapStdMiddleware). Request.Context returns the same 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(c.Context(), func(txCtx context.Context) error {
return service.Update(txCtx)
})
The returned context is made of immutable nodes, so it may be handed to a goroutine: later Set calls do not change it. It is canceled when the request completes. For background work that must outlive the request, detach it with context.WithoutCancel:
bg := context.WithoutCancel(c.Context()) go process(bg)
Context deliberately does NOT implement context.Context itself: its head moves as scopes open and return, so a *Context held as a context.Context would not be one fixed context, and a *Context is not safe for concurrent use. Context hands back the head as it stands instead.
func (*Context) Get ¶
Get returns the value set under key and reports whether one was set. It reads the request's current context, so a value a stdlib middleware put there with the key is found too, while a layer that passed on a context not derived from the request's hides the values set before it. A nil interface value reports false.
Get panics for a zero Key.
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: c.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; a request a App.Mount matches has the mount's route. It is false before the match — in App.PreRouting middleware — and inside custom 404/405 status handlers. A middleware that enforces route meta fails closed without a route, since a guard that passes such a request lets every request through:
if !c.HasRoute() {
return errors.New("authz: no route; register the middleware with app.Middleware, a group or a route")
}
scopes, _ := c.Route().GetMeta(RequiredScopes)
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 by middleware.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.
Example ¶
Render routes a success body through the installed SuccessRenderer; the raw helpers never do.
app := newExampleApp()
app.UseSuccessRenderer(func(c *credo.Context, info credo.RenderInfo) any {
return map[string]any{"success": true, "data": info.Data}
})
app.GET("/users", func(c *credo.Context) error {
return c.Render(http.StatusOK, []string{"ada"})
})
app.GET("/webhook", func(c *credo.Context) error {
return c.Response().JSON(http.StatusOK, map[string]bool{"ok": true})
}).SetMeta(credo.MetaRawResponse, true)
exServe(app, http.MethodGet, "/users")
exServe(app, http.MethodGet, "/webhook")
Output: GET /users → 200 {"data":["ada"],"success":true} GET /webhook → 200 {"ok":true}
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: c.RequireUser[*User]().
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) Set ¶
Set stores val under key for the rest of the request. The value is a node over the request's context, so Context.Context, Request.Context and every context derived from them after the call carry it, and stdlib code reads it with ctx.Value(key). Setting a key again replaces its value.
A value set inside a scope — Context.Within, a stdlib middleware wrapped with WrapStdMiddleware — outlives the scope: when the scope ends, the values set inside it are applied again over the outer context. It records a fact about the request; a value that must end with its scope, such as a transaction, belongs in the context given to Within.
Set panics for a zero Key.
Example ¶
A typed key carries a request value: Set takes only a value of the key's type, Get returns it typed, and stdlib code reads it with Value and the key.
app := newExampleApp()
app.PreRouting(func(next credo.Handler) credo.Handler {
return func(c *credo.Context) error {
c.Set(Tenant, &TenantInfo{Name: "acme"}) // a value of another type does not compile
return next(c)
}
})
app.GET("/whoami", func(c *credo.Context) error {
t, ok := c.Get(Tenant) // t is a *TenantInfo
std := c.Request().Std().Context().Value(Tenant).(*TenantInfo)
return c.Response().Text(http.StatusOK, fmt.Sprint(t.Name, " ", ok, " ", std.Name))
})
exServe(app, http.MethodGet, "/whoami")
Output: GET /whoami → 200 acme true acme
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:
c.SetLogger(c.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 c.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. Like a value of Context.Set, a user set inside a scope outlives it.
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"}
c.TPlural("items", 1) // "1 item"
c.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.
func (*Context) Within ¶ added in v0.26.0
Within runs next with ctx as the request's context and reverts when next returns or panics. It is how a layer opens a scope: inside it, Context.Context, Request.Context and Request.Std carry ctx, so a deadline or a span ctx holds reaches the handler and everything it calls.
func Deadline(d time.Duration) credo.Middleware {
return func(next credo.Handler) credo.Handler {
return func(c *credo.Context) error {
ctx, cancel := context.WithTimeout(c.Context(), d)
defer cancel()
return c.Within(ctx, next)
}
}
}
ctx is derived from c.Context(); one that is not cuts the inner chain off from the values set before it, through Context.Get as through Value. When next returns, the request's context is the outer one again — a deadline or a span ends with its scope — and the values set inside the scope with Context.Set are applied again over it: a user or a tenant is a fact about the request, not about one layer. A value the scope owns, such as a transaction, goes into ctx and ends with it.
The embedded *http.Request is kept in step: Within installs one copy of it that carries ctx and restores the outer request afterwards. Assigning c.Request().Request a request with a new context does not change the request's context; in debug mode the Context reports such a request once per route.
Example ¶
app := newExampleApp()
app.PreRouting(func(next credo.Handler) credo.Handler {
return func(c *credo.Context) error {
err := next(c)
_, hasDeadline := c.Context().Deadline()
t, _ := c.Get(Tenant)
fmt.Println("after the scope: deadline", hasDeadline, "tenant", t.Name)
return err
}
})
app.Middleware(Deadline(time.Second))
app.GET("/", func(c *credo.Context) error {
_, hasDeadline := c.Context().Deadline()
fmt.Println("inside the scope: deadline", hasDeadline)
c.Set(Tenant, &TenantInfo{Name: "acme"})
return c.Response().NoContent(http.StatusNoContent)
})
app.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/", nil))
Output: inside the scope: deadline true after the scope: deadline false tenant acme
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 effective catalog key before resolution: the explicit
// key carried by the error, the configured resolver result, or the bare
// Code when neither exists. It is empty when the error carries literal
// text ([HTTPError.WithMessage]).
MessageKey MessageKey
// Message is the resolved human-readable message: the error's literal
// text, the catalog's message for the key, or the built-in message for the
// code, then the status text. A key is never the message.
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 Exchange ¶ added in v0.26.0
type Exchange struct {
// contains filtered or unexported fields
}
Exchange is the immutable record of one request and its final response that an Observer receives. It is valid only during Observe: an observer copies what it keeps, apart from the request's context, which Exchange.Context returns and which may be kept.
The status, the byte count and the duration are final. Bytes counts the bytes the underlying transport writer accepted — compressed output when response compression applied. Duration runs from executor entry to response finalization; the observers themselves are excluded. If recovery is disabled and a panic escaped, Status is the 500 fallback while Bytes reflects only what was written before the panic.
func (*Exchange) Bytes ¶ added in v0.26.0
Bytes returns the body bytes the underlying transport writer accepted, after compression.
func (*Exchange) Context ¶ added in v0.26.0
Context returns the request's context as it stands when the response is final: the values set through Context.Set and the user, read with Value and their keys, and whatever a layer enclosing the observers put there, such as a span. Its nodes are never modified, so it may be kept beyond Observe; it is cancelled when the request ends.
func (*Exchange) Duration ¶ added in v0.26.0
Duration returns the time from executor entry to response finalization.
func (*Exchange) ErrorCode ¶ added in v0.26.0
ErrorCode returns the error code the pipeline classified for the response, captured before the error renderer ran: for a recovered panic, the code of the 500 it rendered; after a fallback — an error renderer that panicked or returned an invalid status — the fallback's code. It is "" when the pipeline rendered nothing: no error, an error returned after the response was committed or hijacked, a handler that wrote its own error response, and an escaped panic with recovery disabled. It is never inferred from the status.
func (*Exchange) Get ¶ added in v0.26.0
Get returns the value set under key and reports whether one was set, as Context.Get does at the end of the request. A value set inside a scope is visible. Get panics for a zero Key.
func (*Exchange) GetUser ¶ added in v0.26.0
GetUser returns the authenticated user stored under type T and reports whether one was present, as Context.GetUser does: ex.GetUser[*User]().
func (*Exchange) OriginalPath ¶ added in v0.26.0
OriginalPath returns the path the client sent, before any rewrite.
func (*Exchange) PanicRecovered ¶ added in v0.26.0
PanicRecovered reports whether recovery caught a panic during the request.
func (*Exchange) Path ¶ added in v0.26.0
Path returns the path the request was served under, after any rewrite.
func (*Exchange) RemoteAddr ¶ added in v0.26.0
RemoteAddr returns the client address, as Request.RealIP reports it.
func (*Exchange) RequestID ¶ added in v0.26.0
RequestID returns the request's ID, or "" when App.UseRequestID is not installed.
func (*Exchange) Route ¶ added in v0.26.0
Route returns the matched route's registered pattern, for example "/v1/jobs/{job_id}", or "" when no route matched (404/405). A request a mount matched has the mount's pattern.
func (*Exchange) RouteName ¶ added in v0.26.0
RouteName returns the matched route's name, or "" when the route has none or no route matched.
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 (Route.GetMeta) and group middleware are both resolved by walking this chain once, when the routes' chains are compiled.
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 for Route.GetMeta. 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 the group's own value of a meta key, so that an outer group's or the App's shows through. Must be called before the server starts; panics if called after compile, and for a zero Key. Returns the Group for fluent chaining.
func (*Group) SetMeta ¶
SetMeta sets the group's value of a meta key. The routes of the group and of its sub-groups inherit it, whenever they were registered, unless a nearer group or the route sets the key itself. Must be called before the server starts; panics if called after compile, and for a zero Key. Returns the Group for fluent chaining.
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 catalog key for the message; it never
// contributes to Code. Attach one with [HTTPError.WithMessageKey].
MessageKey MessageKey `json:"message_key,omitempty"`
// Message is optional literal client text, rendered as is and never
// looked up; it wins over MessageKey. Attach it with
// [HTTPError.WithMessage]. Client input belongs in Details, not here.
Message string `json:"message,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 message: a catalog key or literal text.
Code is the primary wire identity; the message only affects the human-readable text. The message resolves in this order:
- Message, set with HTTPError.WithMessage — literal text, rendered as is
- MessageKey, set with HTTPError.WithMessageKey — looked up in the catalog; without one, the configured scoped resolver or the bare Code is the key
- the built-in message for the Code, then the status text
A key the catalog does not define is never rendered as text: it falls back to step 3, and in debug mode the pipeline warns with the key, the code and the route.
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>"). The message starts empty; attach a catalog key with HTTPError.WithMessageKey or literal text with HTTPError.WithMessage.
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, message, internal; empty segments are omitted.
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) WithMessage ¶ added in v0.26.0
WithMessage returns a copy of the error with literal client text as its message, rendered as is and never looked up. It wins over a message key. The text is the application's own; client input belongs in HTTPError.WithDetails.
func (*HTTPError) WithMessageKey ¶ added in v0.11.0
func (e *HTTPError) WithMessageKey(key MessageKey) *HTTPError
WithMessageKey returns a copy of the error with the catalog key of its message set. The key affects only the human-readable message, looked up in the catalog; a key the catalog does not define renders the built-in message for the Code, never the key. 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 Key ¶ added in v0.26.0
type Key[T any] struct { // contains filtered or unexported fields }
Key is a typed key: it names a request value, set with Context.Set and read with Context.Get, or a route meta value, set with Route.SetMeta and read with Route.GetMeta. The type parameter binds the value's type to the key, so a value of another type does not compile:
var Tenant = credo.NewKey[*TenantInfo]("tenant")
c.Set(Tenant, t) // t must be a *TenantInfo
t, ok := c.Get(Tenant) // t is a *TenantInfo
A key's identity is the value NewKey returns, not its name: two NewKey calls with one name are two keys, so the keys of two packages never collide. The name is for diagnostics only. (A MessageKey is the opposite: two message keys with one text are one catalog key.)
A request value lives in the request's context.Context: Key is the context key, so code that holds only a context.Context reads a value with the standard Value and the key, ctx.Value(Tenant).(*TenantInfo).
Declare keys with NewKey, as package-level variables. The zero Key, declared without NewKey, is not a key: every method that takes one panics with it, since all zero keys of one type would be one key.
func NewKey ¶ added in v0.26.0
NewKey returns a new key for values of type T. name is for diagnostics: it is what the key's String method returns, and it does not make two keys one.
Example ¶
A meta value set on a group reaches its routes, a route's own value overrides it, and middleware reads it with the key's type.
package main
import (
"fmt"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"github.com/credo-go/credo"
)
// newExampleApp returns an App that loads no configuration from disk and logs
// nowhere, so an example's output is its own.
func newExampleApp() *credo.App {
app, err := credo.New(credo.WithLogger(slog.New(slog.DiscardHandler)))
if err != nil {
panic(err)
}
return app
}
// exServe sends one request through app and prints the status, the Allow or
// Location header when set, and the body.
func exServe(app *credo.App, method, target string) {
req := httptest.NewRequest(method, target, nil)
rec := httptest.NewRecorder()
app.ServeHTTP(rec, req)
line := fmt.Sprintf("%s %s → %d", method, target, rec.Code)
if allow := rec.Header().Get("Allow"); allow != "" {
line += " Allow: " + allow
}
if loc := rec.Header().Get("Location"); loc != "" {
line += " Location: " + loc
}
if body, _ := io.ReadAll(rec.Body); len(body) > 0 {
line += " " + string(body)
}
fmt.Println(line)
}
// exText answers with s.
func exText(s string) credo.Handler {
return func(c *credo.Context) error { return c.Response().Text(http.StatusOK, s) }
}
var RequiresAuth = credo.NewKey[bool]("auth")
func main() {
app := newExampleApp()
// Middleware reads meta declaratively; the value is a bool, no assertion.
authMiddleware := func(next credo.Handler) credo.Handler {
return func(c *credo.Context) error {
if auth, _ := c.Route().GetMeta(RequiresAuth); auth {
return credo.NewHTTPError(http.StatusUnauthorized)
}
return next(c)
}
}
// Group-level — inherited by all child routes.
api := app.Group("/api").SetMeta(RequiresAuth, true)
api.Middleware(authMiddleware)
api.GET("/users", exText("users"))
// Route-level — overrides the group.
api.GET("/public", exText("public")).SetMeta(RequiresAuth, false)
exServe(app, http.MethodGet, "/api/users")
exServe(app, http.MethodGet, "/api/public")
}
Output: GET /api/users → 401 {"success":false,"error":{"code":"unauthorized","message":"Unauthorized"}} GET /api/public → 200 public
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 MessageKey ¶ added in v0.26.0
type MessageKey = validation.MessageKey
MessageKey is a catalog key: the exact key of a message in the application's translation catalog, never rendered as text. It is validation.MessageKey, whose violations carry a key too.
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. Middleware of every tier — PreRouting, routed, group and route — 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):
app.PreRouting(credo.WrapStdMiddleware(tracingMiddleware))
The middleware receives the standard request through Request.Std, so it reads the values set before it with ctx.Value(key). The context of the request it passes on becomes the request's context for the handlers after it — a deadline or a span it adds is visible through Context.Context — until it returns; the values those handlers set with Context.Set are then applied again over the outer context. A middleware that passes on a context not derived from the request's cuts the handlers after it off from the values set before it.
The middleware must call the next handler on the request's own goroutine and before it returns: the Context is not safe for concurrent use, so a middleware that runs the next handler on another goroutine, as http.TimeoutHandler does, is outside this contract.
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.
Example ¶
A stdlib middleware sees the Context's head through the request it is handed, and the context it passes on is the head of the inner chain.
app := newExampleApp()
app.PreRouting(func(next credo.Handler) credo.Handler {
return func(c *credo.Context) error {
c.Set(Tenant, &TenantInfo{Name: "acme"})
return next(c)
}
})
app.PreRouting(credo.WrapStdMiddleware(func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
t := r.Context().Value(Tenant).(*TenantInfo) // a value set before the middleware
ctx := context.WithValue(r.Context(), traceKey{}, "span-"+t.Name)
next.ServeHTTP(w, r.WithContext(ctx))
})
}))
app.GET("/", func(c *credo.Context) error {
return c.Response().Text(http.StatusOK, c.Context().Value(traceKey{}).(string))
})
exServe(app, http.MethodGet, "/")
Output: GET / → 200 span-acme
type Module ¶ added in v0.26.0
type Module interface {
// Services registers the module's services: Provide, ProvideValue,
// Manage, workers and the other registrations of the container spec's
// documented order before resolving.
Services(app *App)
// Handlers registers the module's entry points — routes, and anything
// else that registers through the App as routes do — and may Resolve
// the services they close over.
Handlers(app *App)
}
Module is a part of an application: its services, then its handlers. App.UseModules runs every module's Services before any module's Handlers, so the first Resolve inside a Handlers method comes after every registration and the implicit Finalize it triggers is safe.
Both methods are required; a module with nothing for one phase leaves that method empty. A module composed of others calls their methods from its own.
type Observer ¶ added in v0.26.0
type Observer interface {
Observe(ex *Exchange)
}
Observer observes each request after its response is final. Observe receives one immutable record of the exchange, Exchange; the response can no longer change, so an observer exports, counts or logs what happened.
Observers are added with App.AddObserver and run in registration order, after error rendering, panic recovery and response finalization, the compressor's trailer included. The access log installed by App.UseAccessLog is one of them. An observer may be called concurrently for multiple requests and must be concurrency-safe.
With recovery enabled, a panic inside Observe is logged as a framework Error diagnostic and that observer is skipped for the exchange; the observers after it still run. http.ErrAbortHandler, and every panic under WithoutRecover, propagate.
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.
Example ¶
Response.JSON encodes under the application's profile: nil slices and maps as [] and {}, map keys sorted, < > & literal, no trailing newline; WithJSONOptions overrides an axis for the whole application.
payload := map[string]any{"tags": []string(nil), "b": "<b>", "a": map[string]int(nil)}
handler := func(c *credo.Context) error { return c.Response().JSON(http.StatusOK, payload) }
app := newExampleApp()
app.GET("/", handler)
exServe(app, http.MethodGet, "/")
legacy, err := credo.New(
credo.WithLogger(slog.New(slog.DiscardHandler)),
credo.WithJSONOptions(jsonv2.FormatNilSliceAsNull(true), jsontext.EscapeForHTML(true)),
)
if err != nil {
panic(err)
}
legacy.GET("/", handler)
exServe(legacy, http.MethodGet, "/")
Output: GET / → 200 {"a":{},"b":"<b>","tags":[]} GET / → 200 {"a":{},"b":"\u003cb\u003e","tags":null}
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 and running the live sections' OnChange callbacks share 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 and rotates when its files change on disk, with no signal and no reload: the handshake that finds the last check older than a second stats both files (following symbolic links, so a Kubernetes Secret volume's link swap is a change) and, when either changed, loads the pair and swaps it in for new handshakes. A pair that fails to load keeps the current one and is logged once per change. Open connections are never affected. The paths are read at start: a new path takes a restart.
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 (c.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 catalog 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 MessageKey
// 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 MessageKey) RenderOption
RenderMessageKey attaches a catalog 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.
The request's current context is Request.Context, the same as Context.Context: it shadows the embedded request's Context. Hand stdlib code the standard request through Request.Std, which carries that context; the embedded *http.Request keeps the context it was built with and lags behind after a Context.Set.
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"). A violation names its field as the client sent it: by the json tag for a JSON body, and by the form tag for a form or multipart body.
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.
Example ¶
BindBody decodes and validates in one call: a decode error and a validation error alike return the default error envelope.
app := newExampleApp()
app.POST("/users", func(c *credo.Context) error {
var input CreateUserInput
if err := c.Request().BindBody(&input); err != nil {
return err // decode OR validation error → default error envelope
}
// input is GUARANTEED valid here
return c.Response().JSON(http.StatusCreated, input)
})
exPost(app, "/users", `{"name":"Ada","email":"ada@example.com"}`)
exPost(app, "/users", `{"name":"A","email":"ada@example.com"}`)
exPost(app, "/users", `{"name":"Ada","email":"ada@example.com"}{"name":"Eve"}`)
Output: 201 {"name":"Ada","email":"ada@example.com"} 422 {"success":false,"error":{"code":"validation_failed","message":"Validation Failed","violations":[{"field":"name","code":"length","message":"must be between 2 and 100 characters","params":{"max":100,"min":2}}]}} 400 {"success":false,"error":{"code":"bind_failed","message":"Malformed Request","violations":[{"field":"","code":"trailing_data","message":"request body must contain a single JSON value"}]}}
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"), and a violation names its field by the query tag.
In debug mode, a warning is logged when the target does not implement Validatable.
Example ¶
BindQuery reads the query string into a struct and validates it.
app := newExampleApp()
app.GET("/users", func(c *credo.Context) error {
var q ListUsersQuery
if err := c.Request().BindQuery(&q); err != nil {
return err
}
return c.Response().JSON(http.StatusOK, q)
})
exServe(app, http.MethodGet, "/users?page=2&per_page=20&sort=name")
exServe(app, http.MethodGet, "/users?page=2&per_page=20&sort=age")
Output: GET /users?page=2&per_page=20&sort=name → 200 {"Page":2,"PerPage":20,"Sort":"name"} GET /users?page=2&per_page=20&sort=age → 422 {"success":false,"error":{"code":"validation_failed","message":"Validation Failed","violations":[{"field":"sort","code":"in","message":"must be one of the allowed values"}]}}
func (*Request) Context ¶ added in v0.26.0
Context returns the request's current context.Context, the one Context.Context returns: it carries the values set with Context.Set and the deadline or span of the scope it is read in. It shadows the embedded *http.Request's Context, which returns the context that request was built with and lags behind after a Set.
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 c.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 := c.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. 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.
func (*Request) Std ¶ added in v0.26.0
Std returns the standard request carrying the request's current context, Context.Context. The call may replace the embedded *http.Request: when the embedded request already carries the context, Std returns it, otherwise it installs a copy that does and returns the copy, so a second call without a new Context.Set copies nothing. Hand Std's result to stdlib code; a multipart form that stdlib code parses on it stays under the request-end cleanup.
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 (*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.
Example ¶
A body-forbidding status is status-only: the helper writes neither the body nor its Content-Type.
app := newExampleApp()
app.GET("/", func(c *credo.Context) error {
return c.Response().JSON(http.StatusNoContent, map[string]string{"ignored": "body"})
})
rec := httptest.NewRecorder()
app.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/", nil))
fmt.Printf("%d %q %q\n", rec.Code, rec.Header().Get("Content-Type"), rec.Body.String())
Output: 204 "" ""
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) 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"
Example ¶
A named route builds its URL from decoded parameter values, escaping each path value for one segment; a host-scoped route fills its host first.
package main
import (
"fmt"
"log/slog"
"net/http"
"github.com/credo-go/credo"
)
// newExampleApp returns an App that loads no configuration from disk and logs
// nowhere, so an example's output is its own.
func newExampleApp() *credo.App {
app, err := credo.New(credo.WithLogger(slog.New(slog.DiscardHandler)))
if err != nil {
panic(err)
}
return app
}
// exText answers with s.
func exText(s string) credo.Handler {
return func(c *credo.Context) error { return c.Response().Text(http.StatusOK, s) }
}
func main() {
app := newExampleApp()
app.GET("/products/{id}", exText("product")).Name("product.show")
app.Host("{tenant}.myapp.com").GET("/products/{id}", exText("product")).Name("tenant.product.show")
route := app.GetRoute("product.show")
uri, _ := route.BuildURI("42")
fmt.Println(uri)
uri, _ = route.BuildURI("a/b")
fmt.Println(uri)
url, _ := route.BuildURL("42") // a default route: the same as BuildURI
fmt.Println(url)
fmt.Printf("%q\n", route.GetHost())
url, _ = app.GetRoute("tenant.product.show").BuildURL("acme", "42")
fmt.Println(url)
_, err := route.BuildURI("42", "extra")
fmt.Println(err != nil)
}
Output: /products/42 /products/a%2Fb /products/42 "" acme.myapp.com/products/42 true
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) GetMeta ¶ added in v0.26.0
GetMeta returns the value of a meta key for this route and reports whether one was set: the route's own value, else its group's, then the outer groups', then the App's. The value has the key's type:
scopes, ok := c.Route().GetMeta(RequiredScopes) // scopes is a []Scope
Once the App is prepared, the route's resolved meta is a snapshot taken when its chain was compiled, so a request-time lookup does not walk the groups. GetMeta panics for a zero Key.
func (*Route) GetMethod ¶
GetMethod returns the HTTP method. It is empty for a mount's route, which answers every forwarded method.
func (*Route) GetPattern ¶
GetPattern returns the URL pattern; for a mount's route, the mount's prefix.
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) RemoveMeta ¶ added in v0.26.0
RemoveMeta removes the route's own value of a meta key, so that the value its groups or the App set shows through. Must be called before the server starts; panics if called after compile, and for a zero Key. Returns the Route for fluent chaining. A HEAD twin follows its GET route.
func (*Route) SetMeta ¶
SetMeta sets the route's value of a meta key, which overrides the value its groups and the App set. The value's type is the key's, checked at compile time:
var RequiredScopes = credo.NewKey[[]Scope]("auth.scope")
app.GET("/reports", h).SetMeta(RequiredScopes, []Scope{"reports:read"})
Must be called before the server starts; panics if called after compile, and for a zero Key. 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 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
// 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
// contains filtered or unexported fields
}
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.
RouteInfo.GetMeta reads the fully resolved route metadata (route ← group ← app; a mount's is the App's), taken when the RouteInfo was built. The values are read-only by convention — mutating a slice, map, or pointer read from it mutates the live route metadata.
func (RouteInfo) GetMeta ¶ added in v0.26.0
GetMeta returns the route's resolved value of a meta key — the route's own, else its groups', else the App's — and reports whether one was set, as Route.GetMeta does; a mount reports the App's. GetMeta panics for a zero Key.
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, forwarded method set and meta (the App's) are exposed in // introspection, never its internal routes. RouteKindMount RouteKind = "mount" )
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, error)
BuildURI returns the URL path for a file within this static endpoint. The file path is slash-separated and relative to the prefix (leading slashes are ignored); each segment is percent-encoded, so the URL serves the file it names. An empty file path returns the prefix with its trailing slash:
sr.BuildURI("css/app.css") → "/static/css/app.css", nil
sr.BuildURI("a b/ü.txt") → "/static/a%20b/%C3%BC.txt", nil
sr.BuildURI("") → "/static/", nil
It returns an error, naming the path and the reason, for a path no URL can represent: one that is not valid UTF-8, which the router answers with 400, and one with a "." or ".." segment, which a client removes before it sends the request (RFC 3986, section 5.2.4), so that the URL would name another file or leave the prefix.
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) RemoveMeta ¶ added in v0.26.0
func (sr *StaticRoute) RemoveMeta[T any](key Key[T]) *StaticRoute
RemoveMeta removes the static routes' own value of a meta key, so that the value their group or the App set shows through.
Must be called before the server starts; panics if called after compile, and for a zero Key.
func (*StaticRoute) SetMeta ¶
func (sr *StaticRoute) SetMeta[T any](key Key[T], val T) *StaticRoute
SetMeta sets a meta value 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, and for a zero Key.
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 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
- bind_fieldnames.go
- binderror.go
- component.go
- compress.go
- context.go
- contexthead.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
- key.go
- lifecycle.go
- lifecycle_error.go
- lifecycle_manager.go
- lifecycle_start.go
- module.go
- mux.go
- observer.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
- worker.go
- workers.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package auth provides authentication infrastructure for Credo applications.
|
Package auth provides authentication infrastructure for Credo applications. |
|
jwtauth
Package jwtauth provides a JWT authenticator for Credo applications.
|
Package jwtauth provides a JWT authenticator 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 errors: a Kind, the Provider interface that exposes one, and Error, the error a domain layer returns without naming a transport status.
|
Package fault defines transport-neutral semantic errors: a Kind, the Provider interface that exposes one, and Error, the error a domain layer returns without naming a transport status. |
|
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
|
|
|
credential
Package credential extracts a credential from an HTTP request for the authenticators of auth and auth/jwtauth: from a header after an optional scheme prefix, a query parameter or a cookie.
|
Package credential extracts a credential from an HTTP request for the authenticators of auth and auth/jwtauth: from a header after an optional scheme prefix, a query parameter or a cookie. |
|
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. |
|
machinecode
Package machinecode holds the machine-code grammar that the root's HTTPError and fault.Error share: fault cannot import the root.
|
Package machinecode holds the machine-code grammar that the root's HTTPError and fault.Error share: fault cannot import the root. |
|
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, asserting on structured log output, and checking that every message key is in the catalogs.
|
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, asserting on structured log output, and checking that every message key is in the catalogs. |
|
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. |