π¦ Fiber
Server startβ
Newβ
This method creates a new App named instance. You can pass optional config when creating a new instance.
func New(config ...Config) *App
// Default config
app := fiber.New()
// ...
Configβ
You can pass an optional Config when creating a new Fiber instance.
// Custom config
app := fiber.New(fiber.Config{
CaseSensitive: true,
StrictRouting: true,
ServerHeader: "Fiber",
AppName: "Test App v1.0.1",
})
// ...
Config fieldsβ
| Property | Type | Description | Default |
|---|---|---|---|
string | Sets the application name, which is shown in the startup message, passed to the OnListen hooks as ListenData.AppName, and used in the default SharedState key prefix. It does not set the Server header; use ServerHeader for that. | "" | |
int | Sets the maximum allowed size for a request body. Zero or negative values fall back to the default limit, fiber.DefaultBodyLimit. If the size exceeds the configured limit, it sends 413 - Request Entity Too Large response. This limit also applies when running Fiber through the adaptor middleware from net/http, when decoding compressed request bodies via Ctx.Body(), when parsing multipart form data via Ctx.MultipartForm(), and when copying an uploaded file with Ctx.SaveFileToStorage(). | 4 * 1024 * 1024 | |
bool | When enabled, /Foo and /foo are different routes. When disabled, /Foo and /foo are treated the same. A file server opens the name the router matched, so on a case-insensitive filesystem middleware mounted on /private does not cover /PRIVATE when this is enabled; see Static. | false | |
utils.CBORUnmarshal | Allowing for flexibility in using another cbor library for decoding. | binder.UnimplementedCborUnmarshal | |
utils.CBORMarshal | Allowing for flexibility in using another cbor library for encoding. | binder.UnimplementedCborMarshal | |
Colors | You can define custom color scheme. They'll be used for startup message, route list and some middlewares. The fields are Black, Red, Green, Yellow, Blue, Magenta, Cyan, White and Reset, each an ANSI escape sequence; a field left empty falls back to its DefaultColors value. | DefaultColors | |
map[string]string | Adds a suffix to the original file name and tries saving the resulting compressed file under the new file name. | {"gzip": ".fiber.gz", "br": ".fiber.br", "zstd": ".fiber.zst"} | |
int | Maximum number of concurrent connections. Zero or negative values fall back to the default, fiber.DefaultConcurrency. | 256 * 1024 | |
bool | When true, omits the default Content-Type header from the response. | false | |
bool | When true, omits the Date header from the response. | false | |
bool | Disables redirect flash messages: Redirect().With and WithInput set no cookie, Messages and OldInput report nothing, and the scan of every request's headers for an incoming fiber_flash cookie is skipped. Flash messages travel in that cookie, so only clients that keep cookies across a redirect (browsers, typically) ever receive them; deployments whose clients do not can turn them off. | false | |
bool | Prevents Fiber from automatically registering HEAD routes for each GET route so you can supply custom HEAD handlers; manual HEAD routes still override the generated ones. A mounted sub-app that sets this option, or that leaves HEAD out of its RequestMethods, gets no generated HEAD routes for its routes, even when the app it is mounted on generates them for its own. | false | |
bool | By default all header names are normalized: conteNT-tYPE -> Content-Type | false | |
bool | Disables keep-alive connections so the server closes each connection after the first response. | false | |
bool | Will not pre parse Multipart Form data if set to true. This option is useful for servers that desire to treat multipart form data as a binary blob, or choose when to parse the data. | false | |
bool | If set to true, c.IP() and c.IPs() will validate IP addresses before returning them. Also, c.IP() will return a single validated IP rather than the raw header value, which for X-Forwarded-For may be a comma-separated chain: when TrustProxyConfig names proxy IPs or ranges (Proxies, Loopback, Private or LinkLocal), the chain is walked from right to left and those proxies are skipped; otherwise, including when only UnixSocket is trusted, the first valid IP from the left is returned (see Ctx.IP). Enable it whenever c.IP() is used as a single client identifier and the header can carry a chain, for example by the limiter middleware or an IP allowlist.WARNING: There is a small performance cost to doing this validation. It is not needed when your reverse proxy overwrites this header with a single client IP or you use a single-IP header such as X-Real-IP; keep it disabled there if speed is your main concern. | false | |
bool | Splits query, body, and header parameters on commas when enabled. For example, /api?foo=bar,baz becomes foo[]=bar&foo[]=baz. | false | |
ErrorHandler | ErrorHandler is executed when an error is returned from fiber.Handler, and for a request fasthttp refuses before routing. Mounted fiber error handlers are retained by the top-level app and applied on requests under a literal mount prefix; see App.ErrorHandler. | DefaultErrorHandler | |
bool | Rejects every method except GET and HEAD if set to true. This option is useful as anti-DoS protection for servers accepting only GET requests. The request size is limited by ReadBufferSize if GETOnly is set. A rejected request is answered 405 Method Not Allowed with Allow: GET, HEAD. | false | |
time.Duration | The maximum amount of time to wait for the next request when keep-alive is enabled. If IdleTimeout is zero, the value of ReadTimeout is used. | 0 | |
bool | When enabled, all values returned by context methods are immutable. By default, they are valid until you return from the handler; see issue #185. | false | |
utils.JSONUnmarshal | Allowing for flexibility in using another json library for decoding. | json.Unmarshal | |
utils.JSONMarshal | Allowing for flexibility in using another json library for encoding. | json.Marshal | |
int | Sets the maximum number of ranges parsed from a Range header. Zero or negative values fall back to the default limit, fiber.DefaultMaxRanges. If the limit is exceeded, the request is rejected with 416 - Requested Range Not Satisfiable and Content-Range: bytes */<size>. | 16 | |
utils.MsgPackUnmarshal | Allowing for flexibility in using another msgpack library for decoding. | binder.UnimplementedMsgpackUnmarshal | |
utils.MsgPackMarshal | Allowing for flexibility in using another msgpack library for encoding. | binder.UnimplementedMsgpackMarshal | |
bool | Controls whether StoreInContext also propagates values into the request context.Context for Fiber-backed contexts. StoreInContext always writes to c.Locals(). ValueFromContext for Fiber-backed contexts always reads from c.Locals(). | false | |
bool | PassLocalsToViews Enables passing of the locals set on a fiber.Ctx to the template engine. See our Template Middleware for supported engines. | false | |
string | Specifies the header name to read the client's real IP address from when behind a reverse proxy. Common values: fiber.HeaderXForwardedFor, "X-Real-IP", "CF-Connecting-IP" (Cloudflare). Important: This setting requires TrustProxy to be enabled; TrustProxyConfig controls which proxy IPs are trusted for reading this header. Without TrustProxy, this setting has no effect and c.IP() will always return the remote IP from the TCP connection. Behavior note: X-Forwarded-For often contains a comma-separated chain of IP addresses. With the default EnableIPValidation = false, c.IP() will return the raw header value (the whole chain) rather than a single parsed client IP. With EnableIPValidation = true, c.IP() walks the chain from right to left, skips every IP that matches the proxy IPs or ranges in TrustProxyConfig, and returns the first non-trusted IP; with only UnixSocket trusted there are no proxy IPs to skip and the first valid IP from the left is returned (see Ctx.IP). Enable it whenever c.IP() is used as a single client identifier and the header can carry a chain, for example by the limiter middleware or an IP allowlist. Your reverse proxy should still overwrite or sanitize this header based on the real client connection, or provide a single-IP header such as "X-Real-IP" or a provider-specific header like "CF-Connecting-IP"; with a single address in the header, validation is not required to get a usable client IP. Security Warning: Headers can be easily spoofed. Always configure TrustProxyConfig to validate the proxy IP address, otherwise malicious clients can forge headers to bypass IP-based access controls. | "" | |
int | per-connection buffer size for requests' reading. This also limits the maximum header size: a request whose headers do not fit is answered 431 Request Header Fields Too Large. Increase this buffer if your clients send multi-KB RequestURIs and/or multi-KB headers (for example, BIG cookies). Zero or negative values fall back to the default, fiber.DefaultReadBufferSize. | 8192 | |
time.Duration | The amount of time allowed to read the full request, including the body. The default timeout is unlimited. | 0 | |
bool | Aggressively reduces memory usage at the cost of higher CPU usage if set to true. | false | |
any | Configures the compiler used for regex() route constraints. Assign regexp.MustCompile or coregex.MustCompile directly to switch engines. It must be a function of the form func(string) T, where T has a MatchString(string) bool method; fiber.New panics for anything else. Fiber reuses the compiled matcher across requests, so the returned value must be safe for concurrent use. Fiber may invoke RegexHandler more than once per route while parsing raw and normalized route patterns during registration. | regexp.MustCompile | |
[]string | RequestMethods provides customizability for HTTP methods. You can add/remove methods as you wish. The order is the one App.Stack reports. DefaultMethods holds GET, HEAD, POST, PUT, DELETE, CONNECT, OPTIONS, TRACE, PATCH and QUERY. Registering a route for a method that is not listed panics, and a request with such a method is answered 501 Not Implemented. | DefaultMethods | |
string | Enables the Server HTTP header with the given value. | "" | |
[]Service | Services that Fiber starts, in order, while fiber.New creates the app, and terminates in reverse order after shutdown. fiber.New panics when a service is nil, shares the name its String() method returns with another service, or fails to start. See Services. | nil | |
func() context.Context | Returns the context that Fiber passes to the Terminate method of each service when it shuts the services down. | A provider that returns context.Background() | |
func() context.Context | Returns the context that Fiber passes to the Start method of each service, and to its State method when it prints the startup message. | A provider that returns context.Background() | |
string | Prefix of the keys that SharedState writes to SharedStorage. When it is empty, Fiber uses gofiber-shared-state-, followed by the AppName and a hyphen if AppName is set. | "" | |
Storage | Storage behind SharedState, which prefork workers and other processes can share when the storage itself is shared. The SharedState methods return ErrSharedStorageNotConfigured while it is nil. Fiber closes it on shutdown, after the services are terminated. | nil | |
bool | When enabled, requests whose path and method match no registered route are answered with 404 (or 405 when the path exists for other methods) before the middleware chain runs, avoiding work on requests to unregistered paths (bots, scanners, bad URLs). Warning: middleware never runs for skipped requests, so Use-based responders on unregistered paths (catch-all 404 pages, static, proxy, healthcheck, rewrite/redirect middleware) and logger/metrics visibility stop working for them. Rate limiters are in the same position: requests to unregistered paths are neither counted nor throttled, and leave no trace in the access log. CORS preflight requests are exempt so cors middleware keeps working. Customize the responses via ErrorHandler. With more than 64 entries in RequestMethods the option has no effect and requests go through the normal router. | false | |
bool | StreamRequestBody enables request body streaming, and calls the handler sooner when given body is larger than the current limit. | false | |
bool | When enabled, the router treats /foo and /foo/ as different, for parametric routes such as /users/:id/ as well. Otherwise, the router treats /foo and /foo/ as the same. | false | |
StructValidator | If you want to validate header/form/query... automatically when to bind, you can define struct validator. Fiber doesn't have default validator, so it'll skip validator step if you don't use any validator. | nil | |
bool | Enables trust of reverse proxy headers. When enabled, Fiber will check if the request is coming from a trusted proxy (configured in TrustProxyConfig) before reading values from proxy headers. Required for: Using ProxyHeader to read client IP from headers like X-Forwarded-For. Behavior when enabled: If the remote IP is trusted (matches TrustProxyConfig), then c.IP() reads from ProxyHeader (when configured; otherwise it uses RemoteIP()), c.Scheme() first checks standard proxy scheme headers (X-Forwarded-Proto, X-Forwarded-Protocol, X-Forwarded-Ssl, X-Url-Scheme) and falls back to the actual connection scheme if none are set, and c.Hostname() prefers X-Forwarded-Host but falls back to the request Host header when the proxy header is not present. If the remote IP is NOT trusted, these methods ignore proxy headers and use the actual connection values instead. Security: This prevents header spoofing by validating the proxy's IP address. Always configure TrustProxyConfig when enabling this option and set ProxyHeader if you want c.IP() to use a specific header. | false | |
TrustProxyConfig | Configures which proxy IP addresses or ranges to trust. Only effective when TrustProxy is enabled. Fields: β’ Proxies - List of trusted proxy IPs or CIDR ranges (e.g., []string{"10.10.0.58", "192.168.0.0/24"}); fiber.New logs a warning for an entry it cannot parse and does not trust it β’ Loopback - Trust loopback addresses (127.0.0.0/8, ::1/128) β’ Private - Trust all private IP ranges (10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, fc00::/7) β’ LinkLocal - Trust link-local addresses (169.254.0.0/16, fe80::/10) β’ UnixSocket - Trust Unix domain socket connections Example: For an app behind Nginx at 10.10.0.58, use TrustProxyConfig{Proxies: []string{"10.10.0.58"}} or TrustProxyConfig{Private: true} if using private network IPs. | {} (DefaultTrustProxyConfig) | |
bool | The router always normalizes the request path before matching, as RFC 3986 Section 6.2.2 describes: percent-encoded unreserved characters (letters, digits, -, ., _, ~) are decoded, every other escape keeps its encoding with uppercase hex digits, and . and .. segments are removed, so /%70rivate and /x/../private both match /private while /a%2Fb and //private stay as sent. When enabled, every escape is decoded, so that routing, ctx.Path() and ctx.Params() work with the fully decoded path. Only %XX escapes are decoded: a + stays a +, as it is an ordinary path character, and a malformed escape is left as it is | false | |
Views | Views is the interface that wraps the Render function. See our Template Middleware for supported engines. A nil value, a typed nil pointer included, means that no view engine is configured. | nil | |
string | Views Layout is the global layout for all template render until override on Render function. See our Template Middleware for supported engines. | "" | |
int | Per-connection buffer size for responses' writing. Zero or negative values fall back to the default, fiber.DefaultWriteBufferSize. | 8192 | |
time.Duration | The maximum duration before timing out writes of the response. The default timeout is unlimited. | 0 | |
utils.XMLUnmarshal | Allowing for flexibility in using another XML library for decoding. | xml.Unmarshal | |
utils.XMLMarshal | Allowing for flexibility in using another XML library for encoding. | xml.Marshal |
Server listeningβ
Configβ
You can pass an optional ListenConfig when calling the Listen or Listener method.
// Custom config
app.Listen(":8080", fiber.ListenConfig{
EnablePrefork: true,
DisableStartupMessage: true,
})
Config fieldsβ
| Property | Type | Description | Default |
|---|---|---|---|
func(app *App) error | Allows customizing and accessing fiber app before serving the app. If it returns an error, Listen and Listener return that error without serving, and Listen closes the listener it created. It is not called when EnablePrefork is enabled. | nil | |
string | Path of the CA bundle used to verify client certificates, for mTLS on the CertFile/CertKeyFile path. Ignored when TLSConfig is set: that config is served as supplied and this field does not modify it, so a client certificate is required only if its ClientAuth is a Require mode, verified against its ClientCAs. Fiber logs a warning when both are supplied. | "" | |
string | Path of the certificate file. If you want to use TLS, you must enter this field together with CertKeyFile; setting only one of them makes Listen return fiber.ErrCertFileAndKeyRequired instead of silently serving plaintext HTTP. | "" | |
string | Path of the certificate's private key. If you want to use TLS, you must enter this field together with CertFile. | "" | |
bool | When set to true, it will not print out the Β«FiberΒ» ASCII art and listening address. | false | |
bool | When set to true, this will spawn multiple Go processes listening on the same port. | false | |
bool | If set to true, will print all routes with their method, path, name, and handlers. | false | |
context.Context | Field to shutdown Fiber by given context gracefully. With EnablePrefork it stops only the process it is canceled in; see Prefork. | nil | |
time.Duration | Specifies the maximum duration to wait for the server to gracefully shutdown. When the timeout is reached, the shutdown stops waiting, without closing the connections that are still active, and the context.DeadlineExceeded error is passed to the OnPostShutdown callback. A zero value applies the default; set a negative value to disable the timeout and wait indefinitely. | 10 * time.Second | |
func(addr net.Addr) | Called with the net.Addr of the listener that Listen creates, for example to read the port the OS picked for :0; with prefork, once in each child process. Listener does not call it. | nil | |
string | Known networks are "tcp" (fiber.NetworkTCP), "tcp4" (fiber.NetworkTCP4, IPv4-only), "tcp6" (fiber.NetworkTCP6, IPv6-only), "unix" (fiber.NetworkUnix, Unix Domain Sockets). WARNING: When prefork is set to true, only "tcp4" and "tcp6" can be chosen. | tcp4 | |
time.Duration | Delays the respawn of a crashed child process by this duration. Only applies when prefork is enabled. | 0 (respawn immediately) | |
int | Defines the maximum number of child process restarts after crashes before the prefork master exits with an error. Only applies when prefork is enabled. | max(1, runtime.GOMAXPROCS(0) / 2) | |
time.Duration | How long the prefork master waits for child processes to exit after SIGTERM before sending SIGKILL during shutdown. On Windows children are always killed immediately. Only applies when prefork is enabled. | 5 * time.Second | |
PreforkLogger | Sets a custom logger for the prefork process manager. It is any value with a Printf(format string, args ...any) method, such as a *log.Logger. Only applies when prefork is enabled. | Fiber logger | |
os.FileMode | FileMode to set for Unix Domain Socket (ListenerNetwork must be "unix") | 0770 | |
func(tlsConfig *tls.Config) | Allows customizing tls.Config as you want. Ignored when TLSConfig is set. | nil | |
*tls.Config | Recommended base TLS configuration (cloned). Use for external certificate providers via GetCertificate. When set, other TLS fields are ignored. | nil | |
*autocert.Manager | Manages TLS certificates automatically using the ACME protocol. Enables integration with Let's Encrypt or other ACME-compatible providers. Combining it with CertFile or CertKeyFile makes Listen return fiber.ErrAutoCertWithCertFile, unless TLSConfig is set, which makes Fiber ignore the other TLS fields. | nil | |
uint16 | Allows customizing the TLS minimum version. Only tls.VersionTLS12 and tls.VersionTLS13 are accepted; Listen panics for any other value. Ignored when TLSConfig is set. | tls.VersionTLS12 |
Listenβ
Listen serves HTTP requests from the given address.
func (app *App) Listen(addr string, config ...ListenConfig) error
// Listen on port :8080
app.Listen(":8080")
// Listen on port :8080 with Prefork
app.Listen(":8080", fiber.ListenConfig{EnablePrefork: true})
// Custom host
app.Listen("127.0.0.1:8080")
Preforkβ
Prefork is a feature that allows you to spawn multiple Go processes listening on the same port. This can be useful for scaling across multiple CPU cores.
app.Listen(":8080", fiber.ListenConfig{EnablePrefork: true})
Depending on the operating system, prefork can distribute incoming connections between the spawned processes and allow more requests to be handled simultaneously.
On Linux, prefork typically relies on the SO_REUSEPORT socket option for kernel-assisted load distribution across workers. On Windows, Fiber falls back to SO_REUSEADDR; this is not a functional equivalent to Linux SO_REUSEPORT as it lacks native load balancing and may allow other processes to bind to the same port. Operators should validate this behavior against their security and availability requirements.
Shutdownβ
Each prefork process handles shutdown on its own. A GracefulContext canceled in a child drains that child's connections, honoring ShutdownTimeout. Canceled in the master, it only runs the master's shutdown hooks: the master never serves requests itself and keeps supervising the children until it exits, and a child whose master is gone exits immediately, without draining. To stop a prefork deployment gracefully, deliver the signal to every process, for example to the whole process group as systemd does by default, so that each child's GracefulContext observes it. Explicit Shutdown* calls behave the same way: they only affect the process they run in.
Security Considerationsβ
Prefork changes the port-ownership model from strict single-owner binding to an intentional multi-listener setup. In shared hosts, a local co-resident attacker with sufficient privileges may be able to race for shared binds or receive a portion of traffic, depending on platform behavior and user boundaries.
- Run prefork only within a trusted boundary (same deployment unit / same trust domain).
- Use a dedicated service account for Fiber workers; avoid broad shared-user deployments.
- Prefer container or VM isolation and avoid shared host namespaces for unrelated workloads.
- If strict single-owner port semantics are required, run Fiber without prefork.
TLSβ
Prefer TLSConfig for TLS configuration so you can fully control certificates and settings. When TLSConfig is set, Fiber ignores CertFile, CertKeyFile, CertClientFile, TLSMinVersion, AutoCertManager, and TLSConfigFunc.
TLS serves HTTPs requests from the given address using certFile and keyFile paths as TLS certificate and key file.
app.Listen(":443", fiber.ListenConfig{CertFile: "./cert.pem", CertKeyFile: "./cert.key"})
TLS with client CA certificateβ
CertClientFile only configures the client CA for mTLS when using CertFile/CertKeyFile. If TLSConfig is set, CertClientFile is ignored, so configure client CAs in the provided tls.Config instead.
app.Listen(":443", fiber.ListenConfig{
CertFile: "./cert.pem",
CertKeyFile: "./cert.key",
CertClientFile: "./ca-chain-cert.pem",
})
TLS AutoCert support (ACME / Let's Encrypt)β
Provides automatic access to certificates management from Let's Encrypt and any other ACME-based providers.
// Certificate manager
certManager := &autocert.Manager{
Prompt: autocert.AcceptTOS,
// Replace with your domain name
HostPolicy: autocert.HostWhitelist("example.com"),
// Folder to store the certificates
Cache: autocert.DirCache("./certs"),
}
app.Listen(":444", fiber.ListenConfig{
AutoCertManager: certManager,
})
Precedence and conflictsβ
TLSConfigis preferred and ignoresCertFile/CertKeyFile,CertClientFile,AutoCertManager,TLSMinVersion, andTLSConfigFunc.AutoCertManagercannot be combined withCertFile/CertKeyFile:Listenreturnsfiber.ErrAutoCertWithCertFile.
TLS with external certificate providerβ
Use TLSConfig to supply a base tls.Config that can fetch certificates at runtime. TLSConfig is cloned and used as-is.
app.Listen(":443", fiber.ListenConfig{
TLSConfig: &tls.Config{
GetCertificate: func(info *tls.ClientHelloInfo) (*tls.Certificate, error) {
return myProvider.Certificate(info.ServerName)
},
},
})
Mutual TLS with TLSConfigβ
Use TLSConfig to configure mutual TLS by setting ClientAuth to a Require mode and ClientCAs to the roots it verifies against. This replaces CertClientFile when you manage TLS configuration directly.
certPEM := []byte(certPEMString)
keyPEM := []byte(keyPEMString)
caPEM := []byte(caPEMString)
cert, err := tls.X509KeyPair(certPEM, keyPEM)
if err != nil {
log.Fatal(err)
}
clientCAs := x509.NewCertPool()
if ok := clientCAs.AppendCertsFromPEM(caPEM); !ok {
log.Fatal("failed to append client CA")
}
app.Listen(":443", fiber.ListenConfig{
TLSConfig: &tls.Config{
Certificates: []tls.Certificate{cert},
ClientAuth: tls.RequireAndVerifyClientCert,
ClientCAs: clientCAs,
},
})
Load certificates from memory or environment variables and provide them via TLSConfig.
certPEM := []byte(certPEMString)
keyPEM := []byte(keyPEMString)
cert, err := tls.X509KeyPair(certPEM, keyPEM)
if err != nil {
log.Fatal(err)
}
app.Listen(":443", fiber.ListenConfig{
TLSConfig: &tls.Config{
Certificates: []tls.Certificate{cert},
},
})
certPEM := []byte(os.Getenv("TLS_CERT_PEM"))
keyPEM := []byte(os.Getenv("TLS_KEY_PEM"))
cert, err := tls.X509KeyPair(certPEM, keyPEM)
if err != nil {
log.Fatal(err)
}
app.Listen(":443", fiber.ListenConfig{
TLSConfig: &tls.Config{
Certificates: []tls.Certificate{cert},
},
})
Listenerβ
You can pass your own net.Listener using the Listener method. This method can be used to enable TLS/HTTPS with a custom tls.Config.
func (app *App) Listener(ln net.Listener, config ...ListenConfig) error
ln, _ := net.Listen("tcp", ":3000")
cer, _:= tls.LoadX509KeyPair("server.crt", "server.key")
ln = tls.NewListener(ln, &tls.Config{Certificates: []tls.Certificate{cer}})
app.Listener(ln)
Listener serves the listener exactly as supplied. It ignores the TLS fields of the ListenConfig (CertFile, CertKeyFile, CertClientFile, TLSConfig, TLSConfigFunc, AutoCertManager and TLSMinVersion), EnablePrefork and ListenerAddrFunc, and it logs a warning when it is given a TLS field or EnablePrefork. To serve TLS, wrap the listener with tls.NewListener as above; to require client certificates, give that tls.Config a ClientAuth Require mode and the ClientCAs to verify against. GracefulContext, ShutdownTimeout, BeforeServeFunc, DisableStartupMessage and EnablePrintRoutes work as they do for Listen.
Serverβ
Server returns the underlying fasthttp server. Fiber wraps its HeaderReceived callback when it starts serving, and keeps calling the one you set, including one set in BeforeServeFunc.
func (app *App) Server() *fasthttp.Server
func main() {
app := fiber.New()
app.Server().MaxConnsPerIP = 1
// ...
}
Server Shutdownβ
Shutdown gracefully shuts down the server without interrupting any active connections. Shutdown works by first closing all open listeners and then waits indefinitely for all connections to return to idle before shutting down.
ShutdownWithTimeout stops waiting once the timeout expires and returns context.DeadlineExceeded; it does not close connections that are still active.
ShutdownWithContext does the same, bounded by the context instead of a timeout. Shutdown hooks will still be executed, even if an error occurs during the shutdown process, as they are deferred to ensure cleanup happens regardless of errors.
func (app *App) Shutdown() error
func (app *App) ShutdownWithTimeout(timeout time.Duration) error
func (app *App) ShutdownWithContext(ctx context.Context) error
Shutdown / ShutdownWithTimeout / ShutdownWithContext wait for in-flight handlers (including streaming responses written with SendStream / SendStreamWriter) until they return or the timeout fires. The timeout is measured from the start of shutdown; if a handler finishes before the deadline, shutdown returns without waiting for the full timeout.
Call Shutdown* from a separate goroutine while Listen / Listener runs, and keep the process alive until Shutdown* returns. Set a non-zero ReadTimeout: a connection that has not sent its first request yet, such as a browser preconnect, otherwise holds the shutdown until the timeout, or forever with Shutdown. Long-lived streams should end once c.RequestCtx().Done() is closed.
ListenConfig.ShutdownTimeout is applied only when Fiber runs its built-in graceful shutdown path (for example with GracefulContext). If you call app.ShutdownWithTimeout yourself, that argument is the one that applies. On that built-in path Listen / Listener returns only once the shutdown has finished, so the caller may exit as soon as it returns; an explicit Shutdown* call still needs the process kept alive until it returns. That wait includes the OnPreShutdown and OnPostShutdown hooks, which ShutdownTimeout does not bound. The OnPreShutdown and OnPostShutdown hooks run exactly once per shutdown, whether it was started by the context or by an explicit Shutdown* call, and not at all when Listen fails before serving.
With prefork enabled, Shutdown* and GracefulContext act only on the process they run in; see Prefork.
Helper functionsβ
NewErrorβ
NewError creates a new *fiber.Error with an optional message. Without one, the message is the standard text of the status code.
func NewError(code int, message ...string) *Error
app.Get("/", func(c fiber.Ctx) error {
return fiber.NewError(782, "Custom error message")
})
NewErrorfβ
NewErrorf creates a new *fiber.Error with an optional formatted message. With two or more arguments, the first is the format string.
func NewErrorf(code int, message ...any) *Error
app.Get("/", func(c fiber.Ctx) error {
return fiber.NewErrorf(782, "Custom error %s", "message")
})
IsChildβ
IsChild determines if the current process is a result of Prefork.
func IsChild() bool
// Config app
app := fiber.New()
app.Get("/", func(c fiber.Ctx) error {
if !fiber.IsChild() {
fmt.Println("I'm the parent process")
} else {
fmt.Println("I'm a child process")
}
return c.SendString("Hello, World!")
})
// ...
// With prefork enabled, the parent process will spawn child processes
app.Listen(":8080", fiber.ListenConfig{EnablePrefork: true})