Fiber — Interfaces#
Interface catalog#
Ctx#
- Package:
github.com/gofiber/fiber/v3 - File:
ctx_interface_gen.go(generated byifacemaker) - Methods: 100+ methods covering the full HTTP request/response lifecycle:
request headers/body/params, response writing, JSON/XML serialization,
routing (
Next,RestartRouting), context values (Locals), cookies, flash messages, redirect helpers, multipart, TLS info,context.Contextadapter methods (Deadline,Done,Err), andio.Writer(Write). Also includesReq() ReqandRes() Resaccessors that return focused sub-interfaces. - Purpose: Central handler contract — every user handler and middleware
receives a
Ctx. This single interface is the entire public API surface for request processing. - Implementations:
DefaultCtx(the only production implementation); user can supply a custom implementation by satisfyingCustomCtx(which embedsCtx) and settingConfig.NewCtxFunc. - Design quality: Deliberately wide (violates ISP by textbook definition)
but intentional: it mirrors the Express.js “one object does everything”
ergonomic. The interface is generated, not hand-written —
ifacemakerderives it fromDefaultCtxannotations, preventing interface/implementation drift. TheReq()andRes()sub-interfaces provide focused read-only views for code that only needs request or response access.
CustomCtx#
- Package:
github.com/gofiber/fiber/v3 - File:
ctx_interface.go - Methods: Embeds
Ctx(100+ methods) plus:Reset(fctx *fasthttp.RequestCtx)— re-initialize from a new requestrelease()— internal pool return hookAbandon()/IsAbandoned()/ForceRelease()— timeout-middleware pool lifecycle- Internal routing state accessors (unexported):
getMethodInt,getIndexRoute,getTreePathHash,getDetectionPath,getPathOriginal,getValues,getMatched,getSkipNonUseRoutes,setIndexHandler,setIndexRoute,setMatched,setSkipNonUseRoutes,setRoute
- Purpose: The internal interface used by the framework itself. Extends the
public
Ctxwith pool lifecycle management and routing state mutation. Because all extra methods exceptAbandon/IsAbandoned/ForceReleaseare unexported, external code cannot satisfyCustomCtxwithout embeddingDefaultCtx, which is the intended extension pattern. - Implementations:
DefaultCtx(sole production implementation). Users extending the context must embedDefaultCtxand override desired methods. - Design quality: Clean separation of concerns: the public
Ctxhides all internals;CustomCtxadds them back only for framework-level consumers (router, pool, timeout middleware). The unexported-method trick enforces embedding rather than full re-implementation.
Router#
- Package:
github.com/gofiber/fiber/v3 - File:
router.go - Methods:
Use(args ...any) Router Get/Head/Post/Put/Delete/Connect/Options/Trace/Patch(path string, handler any, handlers ...any) Router Add(methods []string, path string, handler any, handlers ...any) Router All(path string, handler any, handlers ...any) Router Group(prefix string, handlers ...any) Router Domain(host string) Router RouteChain(path string) Register Route(prefix string, fn func(router Router), name ...string) Router Name(name string) Router - Purpose: Fluent route registration contract. Both
App(top-level) andGroup(path-prefixed sub-router) satisfy this interface, enabling a uniform API for defining routes at any nesting level. All method handlers acceptanyto support both typed handlers (func(Ctx) error) and plain functions (for reflection-based generic handler support). - Implementations:
App,Group - Design quality: Well-sized (14 methods). The fluent return (
Routeron every method) enables chaining. Theany-typed handler arguments are unconventional and sacrifice compile-time type safety for flexibility — a deliberate ergonomic trade-off documented in the source.
Storage#
- Package:
github.com/gofiber/fiber/v3 - File:
storage_interface.go - Methods:
Get(key string) ([]byte, error) GetWithContext(ctx context.Context, key string) ([]byte, error) Set(key string, val []byte, exp time.Duration) error SetWithContext(ctx context.Context, key string, val []byte, exp time.Duration) error Delete(key string) error DeleteWithContext(ctx context.Context, key string) error Reset() error ResetWithContext(ctx context.Context) error Close() error - Purpose: Pluggable key-value storage backend. Used by session, cache,
rate-limiter, CSRF, and other stateful middleware packages. The interface
provides a uniform API over Redis, Memcached, Postgres, SQLite, Badger,
in-memory, and 20+ other backends available in the
gofiber/storagerepository. - Implementations:
internal/storagewrapper (used within the monorepo), plus the entiregofiber/storageecosystem (Redis, PostgreSQL, MongoDB, DynamoDB, S3, etc.) - Design quality: Excellent ISP adherence — 9 focused methods covering
CRUD + Reset + Close. The parallel
*WithContextvariants for each mutating operation (added in v3) allow context-aware cancellation without breaking the simpler v2 API. Slightly redundant (each operation appears twice) but the pattern is explicit and composable.
Service#
- Package:
github.com/gofiber/fiber/v3 - File:
services.go - Methods:
Start(ctx context.Context) error String() string State(ctx context.Context) (string, error) Terminate(ctx context.Context) error - Purpose: Lifecycle contract for long-running dependencies (databases,
caches, message brokers). Services are registered in
Config.Services, started before the server accepts requests, displayed in the startup banner (viaString()andState()), and terminated on graceful shutdown. - Implementations: User-provided; no bundled implementations — the interface is a lightweight integration point, not a dependency.
- Design quality: Minimal and well-defined (4 methods). Follows the same
context-aware start/stop pattern asnet/http.Serverandtestcontainers.String()satisfyingfmt.Stringerimplicitly is a nice touch.
Views#
- Package:
github.com/gofiber/fiber/v3 - File:
ctx.go - Methods:
Load() error Render(out io.Writer, name string, binding any, layout ...string) error - Purpose: Template engine abstraction. Registered via
Config.Views.Load()is called once at startup to parse templates;Render()is called per-request byctx.Render(). Thelayoutvariadic arg enables master-page composition. - Implementations: Adapters exist for
html/template, Django, Pug, Jet, Ace, Amber, Handlebars, Mustache — maintained in thegofiber/templaterepository. - Design quality: Minimal (2 methods). Clean ISP example. The
io.Writeroutput parameter rather than returning a[]byteavoids allocation.
CustomBinder#
- Package:
github.com/gofiber/fiber/v3 - File:
bind.go - Methods:
Name() string MIMETypes() []string Parse(c Ctx, out any) error - Purpose: Extension point for user-defined MIME-type body parsers.
Registered via
App.RegisterCustomBinder(). TheBody()binder checksMIMETypes()before falling through to built-in content-type dispatch. - Implementations: User-provided
- Design quality: Well-segregated (3 methods). Simple and discoverable.
StructValidator#
- Package:
github.com/gofiber/fiber/v3 - File:
bind.go - Methods:
Validate(out any) error - Purpose: Post-binding struct validation hook. Registered via
Config.StructValidator. Called automatically by allBind.*()methods after successful parsing (unlessSkipValidation(true)is set). - Implementations: User-provided (e.g. wrapping
go-playground/validator) - Design quality: Single-method interface — perfectly minimal. Satisfiable by any existing validator library with a thin adapter.
CustomConstraint#
- Package:
github.com/gofiber/fiber/v3 - File:
path.go - Methods:
Name() string Execute(param string, args ...string) bool - Purpose: Custom route parameter constraints (e.g.
:id<uuid>,:version<semver>). Registered viaApp.AddCustomConstraint(). - Implementations: User-provided; built-in constraints (int, bool, float, alpha, guid, minLen, etc.) satisfy this interface internally.
- Design quality: Minimal (2 methods). Clean extension point.
Log interfaces (log package)#
- Package:
github.com/gofiber/fiber/v3/log - File:
log/log.go - Hierarchy:
Logger — Trace/Debug/Info/Warn/Error/Fatal/Panic (7 plain methods) FormatLogger — Tracef/.../Panicf (7 format methods) WithLogger — Tracew/.../Panicw (7 structured methods) CommonLogger — embeds Logger + FormatLogger + WithLogger (21 methods total) ConfigurableLogger[T] — SetLevel, SetOutput, Logger() T (3 methods) AllLogger[T] — embeds CommonLogger + ConfigurableLogger[T] + WithContext (25 methods) - Purpose: Pluggable leveled logging with three output styles (plain,
format, structured).
AllLogger[T]is the full contract for a custom logger adapter. The genericTparameter gives access to the underlying logger for fine-tuning without losing type safety. - Implementations:
defaultLogger(stdliblog-based, included); adapters for zerolog, zap, logrus, slog available ingofiber/contrib. - Design quality: Excellent ISP via composition. Building
AllLoggerfrom three orthogonal sub-interfaces (Logger,FormatLogger,WithLogger) lets users implement only the style they need at lower levels. The genericConfigurableLogger[T]cleanly exposes the concrete logger type without requiring type assertions.
Interface patterns#
Size distribution: Bimodal. One very large interface (
Ctx, 100+ methods) and many small focused ones (2–9 methods). The largeCtxis justified as a generated surface. All other interfaces follow ISP closely.Embedding: Pervasive and structured:
CustomCtxembedsCtxCommonLoggerembedsLogger + FormatLogger + WithLoggerAllLogger[T]embedsCommonLogger + ConfigurableLogger[T]
Implicit satisfaction: Mixed by design:
Storage,Views,CustomBinder,StructValidator— defined by the framework (consumer side), satisfied by third-party adapters (provider side). Classic consumer-defines-interface pattern.Ctx/CustomCtx— defined and provided by the framework itself; user customization requires embedding, not re-implementation.Router— defined and satisfied internally (App,Group); users receive the interface value, not the concrete type.
Stdlib interfaces used:
context.Context—DefaultCtximplements it (Deadline/Done/Err/Value)io.Writer—DefaultCtx.Write()enablesfmt.Fprintf(ctx, ...)fmt.Stringer—Service.String()satisfies it implicitly
Key abstractions#
Ctx— The single most important abstraction in Fiber. Every handler and middleware depends on it. Its width (100+ methods) reflects a conscious Express.js-inspired design: ergonomics over strict ISP. The generated-interface approach (ifacemaker) is the most architecturally notable feature — it turns a maintenance liability (keeping a 100-method interface in sync with its implementation) into an automated build step.Storage— The cross-cutting extension point that gives Fiber’s middleware ecosystem its flexibility. By defining a 9-method key-value interface, every stateful middleware (session, rate-limit, CSRF, cache) can be backed by Redis, Postgres, or an in-memory store with zero code changes. The*WithContextdual of each method was a v3 design decision that adds cancellation support without a breaking change.Router— The fluent registration interface unified acrossAppandGroup. Its significance is that it enables sub-routers and mount points to be expressed identically to top-level routes, making the route tree composable. Theany-typed handler arguments are the interface’s one weak point.Service— A lightweight but high-value interface that bridges the gap between “library” and “application server” use cases. By formalizing the start/stop contract for dependencies, Fiber lets users avoid manual shutdown hook wiring while keeping the framework free of DI framework dependencies.AllLogger[T]— The log package’s interface hierarchy is the cleanest example of interface composition in the codebase. It demonstrates how to give users maximum flexibility (implement only the sub-interface you need) while offering a unifiedAllLoggerumbrella for full-featured adapters.
Interface-driven extensibility#
Fiber’s extensibility is almost entirely interface-based:
- Template engines — swap via
Config.Views(Viewsinterface). Ten+ official adapters ingofiber/template. - Storage backends — swap via middleware
Config.Storagefields (Storageinterface). Twenty+ official adapters ingofiber/storage. - Custom request context — embed
DefaultCtx, add fields/methods, setConfig.NewCtxFunc. TheCustomCtxinterface (with its internal unexported methods) ensures the framework can manage the context pool regardless of the concrete type. - Body parsers — register via
App.RegisterCustomBinder()(CustomBinderinterface). Dispatched automatically fromBind.Body()by MIME type. - Struct validation — plug in any validator library via
Config.StructValidator(StructValidatorinterface, 1 method). - Route constraints — register via
App.AddCustomConstraint()(CustomConstraintinterface). - Logging — swap via
log.SetLogger()(AllLogger[T]interface). Adapters ingofiber/contrib. - Serialization codecs — not interfaces but function fields in
Config(JSONEncoder,JSONDecoder,CBOREncoder, etc.) — a pragmatic alternative to interfaces for single-function extension points.