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) *AppNew 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) RouterHandlers 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 runtimeRoute removal + RebuildTree is an unusual feature enabling dynamic route mutation without restart.
Route path syntax#
| Syntax | Example | Meaning |
|---|---|---|
| Static | /users | Exact path |
| Named param | /users/:id | Captures 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 engineApp 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() ConfigTesting 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:
| Group | Example methods |
|---|---|
| Request metadata | Method(), Path(), OriginalURL(), IP(), IPs(), Hostname(), Protocol() |
| Request headers | Get(key), GetHeaders(), GetReqHeaders() |
| Request body | Body(), BodyRaw(), BodyParser(out) |
| Binding | Bind() *Bind — entry point for structured binding |
| Params | Params(key), ParamsInt(key), ParamsBool(key), ParamsParser(out) |
| Query | Query(key), QueryInt(key), QueryBool(key), Queries() |
| Cookies | Cookies(key), CookieParser(out) |
| Response | Status(code) Ctx, Set(key, val), JSON(v), XML(v), CBOR(v), Send(body), SendString(s), SendFile(path), SendStream(r) |
| Redirect | Redirect() *Redirect |
| Views | Render(name, bind) |
| Middleware flow | Next() error, RestartRouting() error |
| Locals | Locals(key, [val]) any — handler-scoped KV store |
| Context | Context() context.Context, SetContext(ctx) |
| Raw access | Request() *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.Handlerfiber.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 inlineThe 30+ bundled middleware packages#
| Package | Purpose | Notable config |
|---|---|---|
basicauth | HTTP Basic Auth | Users map or Authorizer func |
cache | Response caching | Storage backend (pluggable), Expiration, KeyGenerator |
compress | gzip/deflate/brotli/zstd response compression | Level |
cors | CORS headers | AllowOrigins, AllowHeaders, AllowMethods, etc. |
csrf | CSRF token validation | KeyLookup, Storage, Session integration |
earlydata | TLS 1.3 0-RTT safe/unsafe routing | IsEarlyData func, AllowEarlyData func |
encryptcookie | AES-GCM cookie encryption | Key, Except |
envvar | Exposes env vars via HTTP endpoint | ExportVars, NotExportVars |
etag | ETag generation + conditional responses | Weak |
expvar | Go expvar HTTP endpoint | path override |
favicon | Serve favicon from file or bytes | Data, File, CacheControl |
healthcheck | /livez + /readyz endpoints | LivenessProbe, ReadinessProbe funcs |
helmet | Security headers (CSP, HSTS, XFO, etc.) | Per-header fields |
idempotency | Replay protection for POST requests | Storage, KeyHeader, Lifetime |
keyauth | API key / Bearer token auth | KeyLookup or Validator func |
limiter | Rate limiting | Max, Expiration, Storage, KeyGenerator, LimitReached |
logger | Structured request logging | Format, Output io.Writer |
paginate | Query string pagination helpers | Attaches *Pagination to Locals |
pprof | Go pprof HTTP endpoint | path prefix |
proxy | Reverse proxy | Servers, balancer, ModifyRequest/ModifyResponse |
recover | Panic recovery → ErrorHandler | StackTraceHandler |
redirect | Bulk URL redirects | Rules map, StatusCode |
requestid | Attach X-Request-ID | Generator func |
responsetime | X-Response-Time header | Format |
rewrite | URL rewriting | Rules map (regex supported) |
session | Cookie-based sessions | Storage backend, Expiration, KeyGenerator |
skip | Conditionally skip a handler | handler, exclude func(Ctx) bool |
static | Static file serving | Root, Index, Browse, CacheDuration |
timeout | Per-handler deadline | timeout.New(h, Config{Timeout: 5s}) |
adaptor | net/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 successEach 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 + SetOutputUsers 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#
| Surface | Style |
|---|---|
| App creation | Single struct config (fiber.Config{}) + optional args |
| Route registration | Method chaining on Router interface |
| Middleware creation | Functional options: middleware.New(middleware.Config{}) |
| Request context | ~90-method Ctx interface (code-generated) |
| HTTP client | Fluent builder on *Request and *Client |
| Extension | Interface 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.