Fiber — Interfaces#

Interface catalog#

Ctx#

  • Package: github.com/gofiber/fiber/v3
  • File: ctx_interface_gen.go (generated by ifacemaker)
  • 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.Context adapter methods (Deadline, Done, Err), and io.Writer (Write). Also includes Req() Req and Res() Res accessors 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 satisfying CustomCtx (which embeds Ctx) and setting Config.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 — ifacemaker derives it from DefaultCtx annotations, preventing interface/implementation drift. The Req() and Res() 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 request
    • release() — internal pool return hook
    • Abandon() / 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 Ctx with pool lifecycle management and routing state mutation. Because all extra methods except Abandon/IsAbandoned/ForceRelease are unexported, external code cannot satisfy CustomCtx without embedding DefaultCtx, which is the intended extension pattern.
  • Implementations: DefaultCtx (sole production implementation). Users extending the context must embed DefaultCtx and override desired methods.
  • Design quality: Clean separation of concerns: the public Ctx hides all internals; CustomCtx adds 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) and Group (path-prefixed sub-router) satisfy this interface, enabling a uniform API for defining routes at any nesting level. All method handlers accept any to 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 (Router on every method) enables chaining. The any-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/storage repository.
  • Implementations: internal/storage wrapper (used within the monorepo), plus the entire gofiber/storage ecosystem (Redis, PostgreSQL, MongoDB, DynamoDB, S3, etc.)
  • Design quality: Excellent ISP adherence — 9 focused methods covering CRUD + Reset + Close. The parallel *WithContext variants 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 (via String() and State()), 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 as net/http.Server and testcontainers. String() satisfying fmt.Stringer implicitly 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 by ctx.Render(). The layout variadic arg enables master-page composition.
  • Implementations: Adapters exist for html/template, Django, Pug, Jet, Ace, Amber, Handlebars, Mustache — maintained in the gofiber/template repository.
  • Design quality: Minimal (2 methods). Clean ISP example. The io.Writer output parameter rather than returning a []byte avoids 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(). The Body() binder checks MIMETypes() 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 all Bind.*() methods after successful parsing (unless SkipValidation(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 via App.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 generic T parameter gives access to the underlying logger for fine-tuning without losing type safety.
  • Implementations: defaultLogger (stdlib log-based, included); adapters for zerolog, zap, logrus, slog available in gofiber/contrib.
  • Design quality: Excellent ISP via composition. Building AllLogger from three orthogonal sub-interfaces (Logger, FormatLogger, WithLogger) lets users implement only the style they need at lower levels. The generic ConfigurableLogger[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 large Ctx is justified as a generated surface. All other interfaces follow ISP closely.

  • Embedding: Pervasive and structured:

    • CustomCtx embeds Ctx
    • CommonLogger embeds Logger + FormatLogger + WithLogger
    • AllLogger[T] embeds CommonLogger + 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.ContextDefaultCtx implements it (Deadline/Done/Err/Value)
    • io.WriterDefaultCtx.Write() enables fmt.Fprintf(ctx, ...)
    • fmt.StringerService.String() satisfies it implicitly

Key abstractions#

  1. 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.

  2. 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 *WithContext dual of each method was a v3 design decision that adds cancellation support without a breaking change.

  3. Router — The fluent registration interface unified across App and Group. Its significance is that it enables sub-routers and mount points to be expressed identically to top-level routes, making the route tree composable. The any-typed handler arguments are the interface’s one weak point.

  4. 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.

  5. 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 unified AllLogger umbrella for full-featured adapters.


Interface-driven extensibility#

Fiber’s extensibility is almost entirely interface-based:

  • Template engines — swap via Config.Views (Views interface). Ten+ official adapters in gofiber/template.
  • Storage backends — swap via middleware Config.Storage fields (Storage interface). Twenty+ official adapters in gofiber/storage.
  • Custom request context — embed DefaultCtx, add fields/methods, set Config.NewCtxFunc. The CustomCtx interface (with its internal unexported methods) ensures the framework can manage the context pool regardless of the concrete type.
  • Body parsers — register via App.RegisterCustomBinder() (CustomBinder interface). Dispatched automatically from Bind.Body() by MIME type.
  • Struct validation — plug in any validator library via Config.StructValidator (StructValidator interface, 1 method).
  • Route constraints — register via App.AddCustomConstraint() (CustomConstraint interface).
  • Logging — swap via log.SetLogger() (AllLogger[T] interface). Adapters in gofiber/contrib.
  • Serialization codecs — not interfaces but function fields in Config (JSONEncoder, JSONDecoder, CBOREncoder, etc.) — a pragmatic alternative to interfaces for single-function extension points.