Skip to content

Latest commit

 

History

History
433 lines (328 loc) · 62.7 KB

File metadata and controls

433 lines (328 loc) · 62.7 KB
id fiber
title 📦 Fiber
description Fiber represents the fiber package where you start to create an instance.
sidebar_position 1

import Reference from '@site/src/components/reference';

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
AppName string Sets the application name used in logs and the Server header ""
BodyLimit int Sets the maximum allowed size for a request body. Zero or negative values fall back to the default limit. 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. 4 * 1024 * 1024
CaseSensitive bool When enabled, /Foo and /foo are different routes. When disabled, /Foo and /foo are treated the same. false
ColorScheme Colors You can define custom color scheme. They'll be used for startup message, route list and some middlewares. DefaultColors
CompressedFileSuffixes 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"}
Concurrency int Maximum number of concurrent connections. 256 * 1024
DisableDefaultContentType bool When true, omits the default Content-Type header from the response. false
DisableDefaultDate bool When true, omits the Date header from the response. false
DisableHeaderNormalizing bool By default all header names are normalized: conteNT-tYPE -> Content-Type false
DisableKeepalive bool Disables keep-alive connections so the server closes each connection after the first response. false
DisablePreParseMultipartForm 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
DisableHeadAutoRegister 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. false
EnableIPValidation bool If set to true, c.IP() and c.IPs() will validate IP addresses before returning them. Also, c.IP() will return only the first valid IP rather than just the raw header value that may be a comma separated string.

WARNING: There is a small performance cost to doing this validation. Keep disabled if speed is your only concern and your application is behind a trusted proxy that already validates this header.
false
EnableSplittingOnParsers bool Splits query, body, and header parameters on commas when enabled.

For example, /api?foo=bar,baz becomes foo[]=bar&foo[]=baz.
false
TrustProxy bool When true, Fiber validates the proxy IP against TrustProxyConfig.Proxies.

By default, c.Protocol(), c.IP(), and c.Hostname() read values from standard X-Forwarded headers. If the remote IP matches a trusted proxy, these methods behave as if TrustProxy were disabled. Otherwise, c.Protocol() reflects the connection scheme, c.IP() uses RemoteIP() from Fasthttp, and c.Hostname() uses fasthttp.Request.URI().Host()
false
ErrorHandler ErrorHandler ErrorHandler is executed when an error is returned from fiber.Handler. Mounted fiber error handlers are retained by the top-level app and applied on prefix associated requests. DefaultErrorHandler
GETOnly bool Rejects all non-GET requests 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. false
IdleTimeout 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. nil
Immutable 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
JSONEncoder utils.JSONMarshal Allowing for flexibility in using another json library for encoding. json.Marshal
JSONDecoder utils.JSONUnmarshal Allowing for flexibility in using another json library for decoding. json.Unmarshal
CBOREncoder utils.CBORMarshal Allowing for flexibility in using another cbor library for encoding. *binder.UnimplementedCborMarshal
CBORDecoder utils.CBORUnmarshal Allowing for flexibility in using another cbor library for decoding. *binder.UnimplementedCborUnmarshal
MsgpackEncoder utils.MsgpackMarshal Allowing for flexibility in using another msgpack library for encoding. *binder.UnimplementedMsgpackMarshal
MsgpackDecoder utils.MsgpackUnmarshal Allowing for flexibility in using another msgpack library for decoding. *binder.UnimplementedMsgpackUnmarshal
PassLocalsToViews bool PassLocalsToViews Enables passing of the locals set on a fiber.Ctx to the template engine. See our Template Middleware for supported engines. false
ProxyHeader string This will enable c.IP() to return the value of the given header key. By default c.IP()will return the Remote IP from the TCP connection, this property can be useful if you are behind a load balancer e.g. X-Forwarded-*. ""
ReadBufferSize int per-connection buffer size for requests' reading. This also limits the maximum header size. Increase this buffer if your clients send multi-KB RequestURIs and/or multi-KB headers (for example, BIG cookies). 4096
ReadTimeout time.Duration The amount of time allowed to read the full request, including the body. The default timeout is unlimited. nil
ReduceMemoryUsage bool Aggressively reduces memory usage at the cost of higher CPU usage if set to true. false
RequestMethods []string RequestMethods provides customizability for HTTP methods. You can add/remove methods as you wish. DefaultMethods
ServerHeader string Enables the Server HTTP header with the given value. ""
StreamRequestBody bool StreamRequestBody enables request body streaming, and calls the handler sooner when given body is larger than the current limit. false
StrictRouting bool When enabled, the router treats /foo and /foo/ as different. Otherwise, the router treats /foo and /foo/ as the same. false
StructValidator 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
TrustProxyConfig TrustProxyConfig Configure trusted proxy IP's. Look at TrustProxy doc.

TrustProxyConfig.Proxies can take IP or IP range addresses.
nil
UnescapePath bool Converts all encoded characters in the route back before setting the path for the context, so that the routing can also work with URL encoded special characters false
Views Views Views is the interface that wraps the Render function. See our Template Middleware for supported engines. nil
ViewsLayout string Views Layout is the global layout for all template render until override on Render function. See our Template Middleware for supported engines. ""
WriteBufferSize int Per-connection buffer size for responses' writing. 4096
WriteTimeout time.Duration The maximum duration before timing out writes of the response. The default timeout is unlimited. nil
XMLEncoder utils.XMLMarshal Allowing for flexibility in using another XML library for encoding. xml.Marshal
XMLDecoder utils.XMLUnmarshal Allowing for flexibility in using another XML library for decoding. xml.Unmarshal

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
BeforeServeFunc func(app *App) error Allows customizing and accessing fiber app before serving the app. nil
CertClientFile string Path of the client certificate. If you want to use mTLS, you must enter this field. ""
CertFile string Path of the certificate file. If you want to use TLS, you must enter this field. ""
CertKeyFile string Path of the certificate's private key. If you want to use TLS, you must enter this field. ""
DisableStartupMessage bool When set to true, it will not print out the «Fiber» ASCII art and listening address. false
EnablePrefork bool When set to true, this will spawn multiple Go processes listening on the same port. See Prefork for more details. false
DisableReuseportFallback bool When set to true, prefork will fail if SO_REUSEPORT is not supported instead of falling back to file descriptor sharing. Only relevant when EnablePrefork is true. false
DisableChildRecovery bool When set to true, disables automatic recovery of crashed child processes in prefork mode. Only relevant when EnablePrefork is true. false
MaxChildRecoveries int Maximum number of times a child process can be recovered before giving up. Set to 0 for unlimited recoveries. Only relevant when EnablePrefork is true and DisableChildRecovery is false. 0 (unlimited)
EnablePrintRoutes bool If set to true, will print all routes with their method, path, and handler. false
GracefulContext context.Context Field to shutdown Fiber by given context gracefully. nil
ShutdownTimeout time.Duration Specifies the maximum duration to wait for the server to gracefully shutdown. When the timeout is reached, the graceful shutdown process is interrupted and forcibly terminated, and the context.DeadlineExceeded error is passed to the OnPostShutdown callback. Set to 0 to disable the timeout and wait indefinitely. 10 * time.Second
ListenerAddrFunc func(addr net.Addr) Allows accessing and customizing net.Listener. nil
ListenerNetwork string Known networks are "tcp", "tcp4" (IPv4-only), "tcp6" (IPv6-only), "unix" (Unix Domain Sockets). WARNING: When prefork is set to true, only "tcp4" and "tcp6" can be chosen. tcp4
UnixSocketFileMode os.FileMode FileMode to set for Unix Domain Socket (ListenerNetwork must be "unix") 0770
TLSConfigFunc func(tlsConfig *tls.Config) Allows customizing tls.Config as you want. Ignored when TLSConfig is set. nil
TLSConfig *tls.Config Recommended base TLS configuration (cloned). Use for external certificate providers via GetCertificate. When set, other TLS fields are ignored. nil
AutoCertManager *autocert.Manager Manages TLS certificates automatically using the ACME protocol. Enables integration with Let's Encrypt or other ACME-compatible providers. nil
TLSMinVersion uint16 Allows customizing the TLS minimum version. 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})

This distributes the incoming connections between the spawned processes and allows more requests to be handled simultaneously.

How it works:

  • On systems with SO_REUSEPORT support (Linux, macOS, FreeBSD): Each child process creates its own listener using SO_REUSEPORT, allowing the kernel to load-balance connections efficiently.
  • On systems without SO_REUSEPORT (older systems, AIX, Solaris): Fiber automatically falls back to file descriptor sharing, where the master process creates a single listener and shares it with all children. Prefork remains active!
  • You can control this behavior with DisableReuseportFallback (see below).

Advanced Configuration:

app.Listen(":8080", fiber.ListenConfig{
    EnablePrefork: true,
    // Automatically restart crashed child processes (default: enabled)
    DisableChildRecovery: false,
    // Maximum recovery attempts per child before giving up (0 = unlimited)
    MaxChildRecoveries: 10,
})
app.Listen(":8080", fiber.ListenConfig{
    EnablePrefork: true,
    // Fail if SO_REUSEPORT is not supported (no fallback)
    DisableReuseportFallback: true,
})

Child Process Recovery:

By default, if a child process crashes, it will be automatically restarted to maintain the desired number of worker processes. You can:

  • Disable recovery entirely with DisableChildRecovery: true
  • Limit recovery attempts with MaxChildRecoveries: N

Prefork with Custom Listener:

You can also use prefork with a custom listener created via reuseport.Listen:

import "github.com/valyala/fasthttp/reuseport"

ln, err := reuseport.Listen("tcp4", ":8080")
if err != nil {
    panic(err)
}

app.Listener(ln, fiber.ListenConfig{EnablePrefork: true})

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

  • TLSConfig is preferred and ignores CertFile/CertKeyFile, CertClientFile, AutoCertManager, TLSMinVersion, and TLSConfigFunc.
  • AutoCertManager cannot be combined with CertFile/CertKeyFile.

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 and ClientCAs. 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)

Server

Server returns the underlying fasthttp server

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 will forcefully close any active connections after the timeout expires.

ShutdownWithContext shuts down the server including by force if the context's deadline is exceeded. 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

Helper functions

NewError

NewError creates a new HTTPError instance with an optional message.

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 HTTPError instance with an optional formatted message.

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})