Fiber — API Surface#

API types#

Library (primary) + Plugin/Extension system (middleware)

Fiber has no gRPC, no CLI, no REST server of its own. It is the framework that user applications call. Its public surface is entirely a Go library API: a root package for building HTTP servers, 30+ self-contained middleware packages, a symmetric HTTP client package, helper packages (binder, extractors, log, addon/retry), and a bidirectional net/http bridge (middleware/adaptor).


Library API — Root package (github.com/gofiber/fiber/v3)#

App creation#

fiber.New(config ...Config) *App
fiber.NewWithCustomCtx(newCtxFunc func(app *App) CustomCtx, config ...Config) *App

New is the normal entry point. NewWithCustomCtx is the escape hatch for embedding application-specific data directly in the context type — a rare but fully supported extension point.

Route registration — Router interface#

All HTTP methods are available on *App and on *Group (and any value satisfying the Router interface):

app.Use(args ...any) Router           // prefix-matched middleware; variadic to accept path + handlers or handlers only
app.Get(path string, handler any, handlers ...any) Router
app.Head(path string, handler any, handlers ...any) Router
app.Post(path string, handler any, handlers ...any) Router
app.Put(path string, handler any, handlers ...any) Router
app.Delete(path string, handler any, handlers ...any) Router
app.Connect(path string, handler any, handlers ...any) Router
app.Options(path string, handler any, handlers ...any) Router
app.Trace(path string, handler any, handlers ...any) Router
app.Patch(path string, handler any, handlers ...any) Router
app.Add(methods []string, path string, handler any, handlers ...any) Router
app.All(path string, handler any, handlers ...any) Router

Handlers are declared as any rather than Handler to allow both func(Ctx) error and func(Ctx) (without error) signatures — Fiber coerces them internally via collectHandlers. The canonical handler type is type Handler = func(Ctx) error.

Route grouping and organisation#

app.Group(prefix string, handlers ...any) Router          // create a sub-router with a path prefix
app.Domain(host string) Router                            // create a sub-router scoped to a virtual host
app.Route(prefix string, fn func(router Router), ...) Router  // scoped block with a callback
app.RouteChain(path string) Register                      // fluent chain: .Get(h).Post(h).Delete(h)

RouteChain returns a Register interface for path-first chaining (uncommon style compared to Router but useful for REST resources):

app.RouteChain("/users").
    Get(listUsers).
    Post(createUser).
    RouteChain("/:id").
    Get(getUser).
    Put(updateUser).
    Delete(deleteUser)

Route metadata and inspection#

app.Name(name string) Router                  // name the last registered route
app.GetRoute(name string) Route               // retrieve a route by name
app.GetRoutes(filterUseOption ...bool) []Route // list all routes
app.RemoveRoute(path string, methods ...string)
app.RemoveRouteByName(name string, methods ...string)
app.RemoveRouteFunc(matchFunc func(r *Route) bool, methods ...string)
app.RebuildTree() *App                        // hot-reload routes at runtime

Route removal + RebuildTree is an unusual feature enabling dynamic route mutation without restart.

Route path syntax#

SyntaxExampleMeaning
Static/usersExact path
Named param/users/:idCaptures id
Optional param/news/:agency?Param may be absent
Wildcard/files/*Matches rest of path
Constraint/users/:id<int>Param must be an integer
Custom constraint/users/:name<min(3)>User-registered constraint

Built-in constraints: int, bool, float, alpha, guid, minLen(n), maxLen(n), len(n), betweenLen(n,m), min(n), max(n), range(min,max), datetime(layout), regex(pattern).

Custom constraints: implement CustomConstraint and call app.RegisterCustomConstraint(c).

Extension registration#

app.RegisterCustomBinder(b CustomBinder)          // add a custom request decoder (e.g., protobuf)
app.RegisterCustomConstraint(c CustomConstraint)  // add a custom route parameter constraint
app.SetTLSHandler(h *TLSHandler)                  // attach TLS SNI handler
app.ReloadViews() error                            // reload template engine

App lifecycle and introspection#

app.Listen(addr string, config ...ListenConfig) error
app.Listener(ln net.Listener, config ...ListenConfig) error
app.Shutdown() error
app.ShutdownWithTimeout(d time.Duration) error
app.ShutdownWithContext(ctx context.Context) error
app.Server() *fasthttp.Server                      // direct access to underlying fasthttp server
app.Handler() fasthttp.RequestHandler              // underlying request handler (for embedding/testing)
app.Hooks() *Hooks                                 // lifecycle event subscriptions
app.State() *State                                 // app-wide key-value store
app.Stack() [][]*Route                             // registered routes
app.HandlersCount() uint32
app.Config() Config

Testing support#

app.Test(req *http.Request, config ...TestConfig) (*http.Response, error)

app.Test is a first-class built-in: it sends an *http.Request through the fiber handler in-process (no real TCP) and returns a standard *http.Response. This is the primary integration testing primitive.

Ctx interface (generated, ~90 methods)#

Ctx is the request/response context passed to every handler. The interface is code-generated by ifacemaker from the concrete DefaultCtx struct (ctx_interface_gen.go). Key method groups:

GroupExample methods
Request metadataMethod(), Path(), OriginalURL(), IP(), IPs(), Hostname(), Protocol()
Request headersGet(key), GetHeaders(), GetReqHeaders()
Request bodyBody(), BodyRaw(), BodyParser(out)
BindingBind() *Bind — entry point for structured binding
ParamsParams(key), ParamsInt(key), ParamsBool(key), ParamsParser(out)
QueryQuery(key), QueryInt(key), QueryBool(key), Queries()
CookiesCookies(key), CookieParser(out)
ResponseStatus(code) Ctx, Set(key, val), JSON(v), XML(v), CBOR(v), Send(body), SendString(s), SendFile(path), SendStream(r)
RedirectRedirect() *Redirect
ViewsRender(name, bind)
Middleware flowNext() error, RestartRouting() error
LocalsLocals(key, [val]) any — handler-scoped KV store
ContextContext() context.Context, SetContext(ctx)
Raw accessRequest() *fasthttp.Request, Response() *fasthttp.Response, RequestCtx() *fasthttp.RequestCtx

CustomCtx interface extends Ctx with setIndexHandler, setRoute, setMatched, getApp — the hooks needed for a user-defined context type to work with the dispatch loop.


Plugin / Extension system — Middleware#

Mechanism#

All middleware follows one pattern:

// Every middleware exposes exactly this signature:
func New(config ...Config) fiber.Handler

fiber.Handler is func(Ctx) error. Middleware is attached via:

app.Use(middleware.New(middleware.Config{...}))    // global
app.Use("/api", middleware.New())                  // path-scoped
app.Get("/path", middleware1, middleware2, handler) // per-route inline

The 30+ bundled middleware packages#

PackagePurposeNotable config
basicauthHTTP Basic AuthUsers map or Authorizer func
cacheResponse cachingStorage backend (pluggable), Expiration, KeyGenerator
compressgzip/deflate/brotli/zstd response compressionLevel
corsCORS headersAllowOrigins, AllowHeaders, AllowMethods, etc.
csrfCSRF token validationKeyLookup, Storage, Session integration
earlydataTLS 1.3 0-RTT safe/unsafe routingIsEarlyData func, AllowEarlyData func
encryptcookieAES-GCM cookie encryptionKey, Except
envvarExposes env vars via HTTP endpointExportVars, NotExportVars
etagETag generation + conditional responsesWeak
expvarGo expvar HTTP endpointpath override
faviconServe favicon from file or bytesData, File, CacheControl
healthcheck/livez + /readyz endpointsLivenessProbe, ReadinessProbe funcs
helmetSecurity headers (CSP, HSTS, XFO, etc.)Per-header fields
idempotencyReplay protection for POST requestsStorage, KeyHeader, Lifetime
keyauthAPI key / Bearer token authKeyLookup or Validator func
limiterRate limitingMax, Expiration, Storage, KeyGenerator, LimitReached
loggerStructured request loggingFormat, Output io.Writer
paginateQuery string pagination helpersAttaches *Pagination to Locals
pprofGo pprof HTTP endpointpath prefix
proxyReverse proxyServers, balancer, ModifyRequest/ModifyResponse
recoverPanic recovery → ErrorHandlerStackTraceHandler
redirectBulk URL redirectsRules map, StatusCode
requestidAttach X-Request-IDGenerator func
responsetimeX-Response-Time headerFormat
rewriteURL rewritingRules map (regex supported)
sessionCookie-based sessionsStorage backend, Expiration, KeyGenerator
skipConditionally skip a handlerhandler, exclude func(Ctx) bool
staticStatic file servingRoot, Index, Browse, CacheDuration
timeoutPer-handler deadlinetimeout.New(h, Config{Timeout: 5s})
adaptornet/http ↔ fiber bridge(see below)

Storage extension point#

Many middleware packages (cache, csrf, idempotency, limiter, session) accept a Storage interface:

type Storage interface {
    Get(key string) ([]byte, error)
    Set(key string, val []byte, exp time.Duration) error
    Delete(key string) error
    Reset() error
    Close() error
}

This is the primary persistence extension point. Fiber’s gofiber/storage ecosystem provides implementations for Redis, Postgres, MySQL, SQLite, MongoDB, DynamoDB, Memcache, S3, etcd, etc.


net/http bridge — middleware/adaptor#

Provides full bidirectional translation between Fiber and standard net/http:

// net/http → Fiber (embed existing handlers)
adaptor.HTTPHandler(h http.Handler) fiber.Handler
adaptor.HTTPHandlerFunc(h http.HandlerFunc) fiber.Handler
adaptor.HTTPMiddleware(mw func(http.Handler) http.Handler) fiber.Handler
adaptor.HTTPHandlerWithContext(h http.Handler) fiber.Handler  // with LocalContext

// Fiber → net/http (expose Fiber app as standard handler)
adaptor.FiberHandler(h fiber.Handler) http.Handler
adaptor.FiberHandlerFunc(h fiber.Handler) http.HandlerFunc
adaptor.FiberApp(app *fiber.App) http.HandlerFunc

// Utilities
adaptor.ConvertRequest(c fiber.Ctx, forServer bool) (*http.Request, error)
adaptor.LocalContextFromHTTPRequest(r *http.Request) (context.Context, bool)

This is the escape hatch for using Gorilla/chi/stdlib middleware in Fiber or mounting Fiber apps inside standard servers.


HTTP Client — client package#

A full HTTP client with symmetric ergonomics to the server side.

Creating a client#

c := client.New()            // fresh client
c.SetBaseURL("https://api.example.com")
c.SetJSONMarshal(sonic.Marshal)  // swap JSON codec
c.AddRequestHook(...)
c.AddResponseHook(...)
c.SetRetryConfig(&RetryConfig{MaxRetries: 3, RetryIf: ...})

Request building — fluent style#

resp, err := c.R().
    SetHeader("Authorization", "Bearer "+token).
    SetJSON(payload).          // or SetXML / SetCBOR / SetForm / SetRawBody
    Post("https://api.example.com/users")

Shorthand methods on *Client:

c.Get(url, cfg ...Config) (*Response, error)
c.Post(url, cfg ...Config) (*Response, error)
c.Put(url, cfg ...Config) (*Response, error)
c.Patch(url, cfg ...Config) (*Response, error)
c.Delete(url, cfg ...Config) (*Response, error)
c.Head(url, cfg ...Config) (*Response, error)
c.Options(url, cfg ...Config) (*Response, error)

Response#

resp.Body() []byte
resp.JSON(v any) error
resp.XML(v any) error
resp.CBOR(v any) error
resp.Status() string
resp.StatusCode() int
resp.Header(key string) string
resp.Cookies() []*fasthttp.Cookie
resp.Close()

API style#

The client uses a fluent builder style on *Request (all Set* methods return *Request). The *Client itself is also fluent (all Set* return *Client). This mirrors Express.js’s res API on the server side.


Extractors package — extractors#

A standalone utility for extracting string values (tokens, API keys) from a request. Used internally by keyauth and available to users:

extractors.FromAuthHeader("Bearer")         // Authorization: Bearer <token>
extractors.FromCookie("session_token")
extractors.FromParam("api_key")             // URL parameter
extractors.FromForm("token")
extractors.FromHeader("X-API-Key")
extractors.FromQuery("api_key")
extractors.FromCustom("name", func(c fiber.Ctx) (string, error) { ... })
extractors.Chain(e1, e2, e3)               // try in order, return first success

Each extractor is a struct with a Extract(c fiber.Ctx) (string, error) method and introspection fields (Source, Argument).


Log package — log#

Logging interface hierarchy, not an implementation:

type Logger interface      { Trace/Debug/Info/Warn/Error/Fatal/Panic (msg, keysAndValues...) }
type FormatLogger interface { Tracef/Debugf/.../Panicf }
type WithLogger interface   { WithContext(ctx) CommonLogger }
type CommonLogger interface  // composes Logger + FormatLogger
type AllLogger[T any] interface  // composes everything + SetLevel + SetOutput

Users call log.SetLogger(myLogger) to swap the default logger. The default writes to stderr. This is not structured logging — it is a portability shim so library consumers can route Fiber’s internal log output into their own logger.


Addon — addon/retry#

A small standalone retry utility (not middleware — runs outside the HTTP request path):

eb := retry.NewExponentialBackoff(retry.Config{
    InitialInterval: 500 * time.Millisecond,
    MaxInterval:     2 * time.Second,
    MaxElapsedTime:  10 * time.Second,
    Multiplier:      2.0,
})
err := eb.Retry(func() error {
    return callExternalService()
})

Useful for database connection setup or external API calls at startup, wired into the Service lifecycle.


API style summary#

SurfaceStyle
App creationSingle struct config (fiber.Config{}) + optional args
Route registrationMethod chaining on Router interface
Middleware creationFunctional options: middleware.New(middleware.Config{})
Request context~90-method Ctx interface (code-generated)
HTTP clientFluent builder on *Request and *Client
ExtensionInterface satisfaction: Storage, Views, CustomBinder, CustomConstraint, Service

Backward compatibility#

Module is versioned at v3 (github.com/gofiber/fiber/v3). The most significant v2 → v3 breaking change was replacing the concrete *DefaultCtx in handler signatures with the Ctx interface — the handler type changed from func(*Ctx) error to func(Ctx) error. v3 also added CustomCtx, Service, State, extractors, CBOR support, and domain-based routing.