### Quick Start with html/template Engine
Source: https://github.com/gofiber/docs/blob/master/blog/2026-05-08-fiber-v3-template-engines.md
Initializes the html/template engine, specifying the directory for templates and their file extension. This setup is done once at application startup.
```go
import (
"github.com/gofiber/fiber/v3"
"github.com/gofiber/template/html/v2"
)
func main() {
// Point to your template directory and file extension
engine := html.New("./views", ".html")
app := fiber.New(fiber.Config{
Views: engine,
})
app.Get("/", func(c *fiber.Ctx) error {
return c.Render("index", fiber.Map{
"Title": "My App",
})
})
app.Listen(":3000")
}
```
--------------------------------
### Example: Set Base URL and Make Request
Source: https://github.com/gofiber/docs/blob/master/versioned_docs/version-v3.x/client/rest.md
Demonstrates setting a base URL for the client and then making a GET request. Ensure the URL is correctly formatted.
```go
cc := client.New()
cc.SetBaseURL("https://httpbin.org/")
resp, err := cc.Get("/get")
if err != nil {
panic(err)
}
fmt.Println(string(resp.Body()))
```
--------------------------------
### Install MsgPack Library
Source: https://github.com/gofiber/docs/blob/master/versioned_docs/version-v3.x/guide/advance-format.md
Install either the vmihailenco/msgpack or shamaton/msgpack/v3 library using go get.
```bash
go get github.com/vmihailenco/msgpack
# or
go get github.com/shamaton/msgpack/v3
```
--------------------------------
### Get Response Protocol Example
Source: https://github.com/gofiber/docs/blob/master/versioned_docs/version-v3.x/client/response.md
Demonstrates how to fetch and print the HTTP protocol used in a response.
```go
resp, err := client.Get("https://httpbin.org/get")
if err != nil {
panic(err)
}
fmt.Println(resp.Protocol())
```
--------------------------------
### Install CBOR Library
Source: https://github.com/gofiber/docs/blob/master/versioned_docs/version-v3.x/guide/advance-format.md
Install the fxamacker/cbor/v2 library using go get.
```bash
go get github.com/fxamacker/cbor/v2
```
--------------------------------
### Example: Accessing App Stack
Source: https://github.com/gofiber/docs/blob/master/versioned_docs/version-v3.x/api/ctx.md
This example demonstrates how to get the application's route stack using `c.App().Stack()` and return it as JSON.
```go
app.Get("/stack", func(c fiber.Ctx) error {
return c.JSON(c.App().Stack())
})
```
--------------------------------
### Type Example
Source: https://github.com/gofiber/docs/blob/master/versioned_docs/version-v3.x/api/ctx.md
Examples showing how to set the Content-Type header using file extensions and specifying character sets.
```go
app.Get("/", func(c fiber.Ctx) error {
c.Type(".html") // => "text/html"
c.Type("html") // => "text/html"
c.Type("png") // => "image/png"
c.Type("json", "utf-8") // => "application/json; charset=utf-8"
// ...
})
```
--------------------------------
### Add Service with Store Middleware
Source: https://github.com/gofiber/docs/blob/master/versioned_docs/version-v3.x/api/services.md
Demonstrates integrating a custom service with the Store middleware for dependency injection, using Redis as a backend with Testcontainers for setup. This example shows how to define a service, manage its lifecycle (start, state, terminate), and access its resources (like a Redis connection string) within the application.
```go
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"time"
"github.com/gofiber/fiber/v3"
"github.com/gofiber/fiber/v3/middleware/logger"
redisStore "github.com/gofiber/storage/redis/v3"
"github.com/redis/go-redis/v9"
tcredis "github.com/testcontainers/testcontainers-go/modules/redis"
)
const (
redisServiceName = "redis-store"
)
type User struct {
ID int `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
}
type redisService struct {
ctr *tcredis.RedisContainer
}
// Start initializes and starts the service. It implements the [fiber.Service] interface.
func (s *redisService) Start(ctx context.Context) error {
// start the service
c, err := tcredis.Run(ctx, "redis:latest")
if err != nil {
return err
}
s.ctr = c
return nil
}
// String returns a string representation of the service.
// It is used to print a human-readable name of the service in the startup message.
// It implements the [fiber.Service] interface.
func (s *redisService) String() string {
return redisServiceName
}
// State returns the current state of the service.
// It implements the [fiber.Service] interface.
func (s *redisService) State(ctx context.Context) (string, error) {
state, err := s.ctr.State(ctx)
if err != nil {
return "", fmt.Errorf("container state: %w", err)
}
return state.Status, nil
}
// Terminate stops and removes the service. It implements the [fiber.Service] interface.
func (s *redisService) Terminate(ctx context.Context) error {
// stop the service
return s.ctr.Terminate(ctx)
}
func main() {
cfg := &fiber.Config{}
// Initialize service.
cfg.Services = append(cfg.Services, &redisService{})
// Define a context provider for the services startup.
// This is useful to cancel the startup of the services if the context is canceled.
// Default is context.Background().
startupCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
cfg.ServicesStartupContextProvider = func() context.Context {
return startupCtx
}
// Define a context provider for the services shutdown.
// This is useful to cancel the shutdown of the services if the context is canceled.
// Default is context.Background().
shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
cfg.ServicesShutdownContextProvider = func() context.Context {
return shutdownCtx
}
app := fiber.New(*cfg)
// Initialize default config
app.Use(logger.New())
ctx := context.Background()
// Obtain the Redis service from the application's State.
redisSrv, ok := fiber.GetService[*redisService](app.State(), redisServiceName)
if !ok || redisSrv == nil {
log.Printf("Redis service not found")
return
}
// Obtain the connection string from the service.
connString, err := redisSrv.ctr.ConnectionString(ctx)
if err != nil {
log.Printf("Could not get connection string: %v", err)
return
}
// define a GoFiber session store, backed by the Redis service
store := redisStore.New(redisStore.Config{
URL: connString,
})
app.Post("/user/create", func(c fiber.Ctx) error {
var user User
if err := c.Bind().JSON(&user); err != nil {
return c.Status(fiber.StatusBadRequest).SendString(err.Error())
}
json, err := json.Marshal(user)
if err != nil {
return c.Status(fiber.StatusInternalServerError).SendString(err.Error())
}
// Save the user to the database.
err = store.Set(user.Email, json, time.Hour*24)
if err != nil {
return c.Status(fiber.StatusInternalServerError).SendString(err.Error())
}
return c.JSON(user)
})
app.Get("/user/:id", func(c fiber.Ctx) error {
id := c.Params("id")
user, err := store.Get(id)
if err == redis.Nil {
return c.Status(fiber.StatusNotFound).SendString("User not found")
} else if err != nil {
return c.Status(fiber.StatusInternalServerError).SendString(err.Error())
}
return c.JSON(string(user))
})
app.Listen(":3000")
}
```
--------------------------------
### Redirect Back - Example
Source: https://github.com/gofiber/docs/blob/master/versioned_docs/version-v3.x/api/redirect.md
Example demonstrating the `Back` method. It redirects to the previous page (referer) or to the root path if no referer is found.
```go
app.Get("/", func(c fiber.Ctx) error {
return c.SendString("Home page")
})
app.Get("/test", func(c fiber.Ctx) error {
c.Set("Content-Type", "text/html")
return c.SendString(`Back`)
})
app.Get("/back", func(c fiber.Ctx) error {
return c.Redirect().Back("/")
})
```
--------------------------------
### Single Page Application (SPA) Setup
Source: https://github.com/gofiber/docs/blob/master/versioned_docs/version-v3.x/middleware/static.md
Configure the Static middleware to serve files from the 'dist' directory for routes starting with '/web'. A separate route handles requests to `index.html` for SPA routing.
```go
app.Use("/web", static.New("", static.Config{
FS: os.DirFS("dist"),
}))
app.Get("/web*", func(c fiber.Ctx) error {
return c.SendFile("dist/index.html")
})
```
--------------------------------
### Start Local Development Server
Source: https://github.com/gofiber/docs/blob/master/README.md
Starts a local development server for live preview. Changes are reflected without server restart.
```bash
npm run start
```
--------------------------------
### Redirect to Route - Example
Source: https://github.com/gofiber/docs/blob/master/versioned_docs/version-v3.x/api/redirect.md
Example demonstrating redirection to a named route 'user' with parameters. It also shows how to include query parameters.
```go
app.Get("/", func(c fiber.Ctx) error {
// /user/fiber
return c.Redirect().Route("user", fiber.RedirectConfig{
Params: fiber.Map{
"name": "fiber",
},
})
})
app.Get("/with-queries", func(c fiber.Ctx) error {
// /user/fiber?data[0][name]=john&data[0][age]=10&test=doe
return c.Redirect().Route("user", fiber.RedirectConfig{
Params: fiber.Map{
"name": "fiber",
},
Queries: map[string]string{
"data[0][name]": "john",
"data[0][age]": "10",
"test": "doe",
},
})
})
app.Get("/user/:name", func(c fiber.Ctx) error {
return c.SendString(c.Params("name"))
}).Name("user")
```
--------------------------------
### Minimal Static Server Setup
Source: https://github.com/gofiber/docs/blob/master/blog/2026-02-13-static-server-with-fiber-v3.md
This minimal setup is sufficient for local demos and internal tools. For production, consider additional configuration for browsing, caching, and not-found handling.
```go
app := fiber.New()
app.Get("/*", static.New("./files"))
log.Fatal(app.Listen(":3000"))
```
--------------------------------
### Basic Fiber Listen Usage
Source: https://github.com/gofiber/docs/blob/master/versioned_docs/version-v3.x/api/fiber.md
Examples of how to use the Listen function to start a Fiber server. Includes basic port listening, enabling prefork, and specifying a custom host.
```go
// Listen on port :8080
app.Listen(":8080")
```
```go
// Listen on port :8080 with Prefork
app.Listen(":8080", fiber.ListenConfig{EnablePrefork: true})
```
```go
// Custom host
app.Listen("127.0.0.1:8080")
```
--------------------------------
### Install Fiber
Source: https://github.com/gofiber/docs/blob/master/versioned_docs/version-v3.x/intro.md
Install the Fiber framework using the go get command. Requires Go version 1.25 or higher.
```bash
go get github.com/gofiber/fiber/v3
```
--------------------------------
### Redirect to URL - Example
Source: https://github.com/gofiber/docs/blob/master/versioned_docs/version-v3.x/api/redirect.md
Example demonstrating how to use the `To` method to redirect to a specific URL, optionally setting the status code.
```go
app.Get("/coffee", func(c fiber.Ctx) error {
// => HTTP - GET 301 /teapot
return c.Redirect().Status(fiber.StatusMovedPermanently).To("/teapot")
})
app.Get("/teapot", func(c fiber.Ctx) error {
return c.Status(fiber.StatusTeapot).Send("🍵 short and stout 🍵")
})
```
--------------------------------
### Status Example
Source: https://github.com/gofiber/docs/blob/master/versioned_docs/version-v3.x/api/ctx.md
Examples demonstrating how to set the HTTP status code for different response scenarios.
```go
app.Get("/fiber", func(c fiber.Ctx) error {
c.Status(fiber.StatusOK)
return nil
})
app.Get("/hello", func(c fiber.Ctx) error {
return c.Status(fiber.StatusBadRequest).SendString("Bad Request")
})
app.Get("/world", func(c fiber.Ctx) error {
return c.Status(fiber.StatusNotFound).SendFile("./public/gopher.png")
})
```
--------------------------------
### CSRF Middleware Quick Start
Source: https://github.com/gofiber/docs/blob/master/versioned_docs/version-v3.x/middleware/csrf.md
Initialize the CSRF middleware with default configuration for development or a production-ready configuration. Production setup includes secure cookie settings and token extraction from headers.
```go
import (
"github.com/gofiber/fiber/v3"
"github.com/gofiber/fiber/v3/extractors"
"github.com/gofiber/fiber/v3/middleware/csrf"
)
// Default config (development only)
app.Use(csrf.New())
// Production config
app.Use(csrf.New(csrf.Config{
CookieName: "__Host-csrf_",
CookieSecure: true,
CookieHTTPOnly: true, // false for SPAs
CookieSameSite: "Lax",
CookieSessionOnly: true,
Extractor: extractors.FromHeader("X-Csrf-Token"),
Session: sessionStore,
// Redaction is enabled by default. Set DisableValueRedaction when you must expose tokens or storage keys in diagnostics.
// DisableValueRedaction: true,
}))
```
--------------------------------
### Install the Fiber CLI
Source: https://github.com/gofiber/docs/blob/master/blog/2026-05-11-fiber-cli.md
Install the Fiber CLI globally using `go install`. Ensure you have a recent Go version.
```bash
go install github.com/gofiber/cli/fiber@latest
```
--------------------------------
### Basic Template Rendering Example
Source: https://github.com/gofiber/docs/blob/master/versioned_docs/version-v3.x/guide/templates.md
This example shows how to render an 'index' template with a 'Title' variable passed to it.
```go
app.Get("/", func(c fiber.Ctx) error {
return c.Render("index", fiber.Map{
"Title": "Hello, World!",
})
})
```
```html
{{.Title}}
```
--------------------------------
### Clone and Run Fiber Recipes
Source: https://github.com/gofiber/docs/blob/master/blog/2026-05-10-fiber-v3-recipes.md
Instructions on how to clone the Fiber recipes repository and run a specific example. Most recipes start a server on port 3000.
```bash
git clone https://github.com/gofiber/recipes.git
cd recipes
cd auth-jwt
cat README.md
go run .
```
--------------------------------
### Send Response Body Example
Source: https://github.com/gofiber/docs/blob/master/versioned_docs/version-v3.x/api/ctx.md
Example of using the Send method to return a simple "Hello, World!" string as the response body.
```go
app.Get("/", func(c fiber.Ctx) error {
return c.Send([]byte("Hello, World!")) // => "Hello, World!"
})
```
--------------------------------
### Example: Add Multiple Query Parameters
Source: https://github.com/gofiber/docs/blob/master/versioned_docs/version-v3.x/client/request.md
Demonstrates adding multiple query parameters, including duplicate keys, to a request. The example then sends the request and prints the response body, which includes the parameters.
```go
req := client.AcquireRequest()
deffer client.ReleaseRequest(req)
req.AddParam("name", "john")
req.AddParam("hobbies", "football")
req.AddParam("hobbies", "basketball")
resp, err := req.Get("https://httpbin.org/response-headers")
if err != nil {
panic(err)
}
fmt.Println(string(resp.Body()))
```
```json
{
"Content-Length": "145",
"Content-Type": "application/json",
"hobbies": [
"football",
"basketball"
],
"name": "joe"
}
```
--------------------------------
### Redirect OldInput - Example
Source: https://github.com/gofiber/docs/blob/master/versioned_docs/version-v3.x/api/redirect.md
Example showing how to retrieve stored input data for the key 'name' using the `OldInput` method.
```go
app.Get("/name", func(c fiber.Ctx) error {
oldInput := c.Redirect().OldInput("name")
return c.SendString(oldInput)
})
```
--------------------------------
### Redirect to URL - More Examples
Source: https://github.com/gofiber/docs/blob/master/versioned_docs/version-v3.x/api/redirect.md
Additional examples showing various ways to use the `To` method, including relative paths, absolute URLs, and different status codes.
```go
app.Get("/", func(c fiber.Ctx) error {
// => HTTP - GET 303 /foo/bar
return c.Redirect().To("/foo/bar")
// => HTTP - GET 303 ../login
return c.Redirect().To("../login")
// => HTTP - GET 303 http://example.com
return c.Redirect().To("http://example.com")
// => HTTP - GET 301 https://example.com
return c.Redirect().Status(301).To("http://example.com")
})
```
--------------------------------
### Redirect Message - Example
Source: https://github.com/gofiber/docs/blob/master/versioned_docs/version-v3.x/api/redirect.md
Example showing how to retrieve a flash message associated with the key 'status' using the `Message` method.
```go
app.Get("/", func(c fiber.Ctx) error {
message := c.Redirect().Message("status")
return c.SendString(message)
})
```
--------------------------------
### Redirect OldInputs - Example
Source: https://github.com/gofiber/docs/blob/master/versioned_docs/version-v3.x/api/redirect.md
Example demonstrating how to retrieve all stored old input data using the `OldInputs` method and return it as JSON.
```go
app.Get("/", func(c fiber.Ctx) error {
oldInputs := c.Redirect().OldInputs()
return c.JSON(oldInputs)
})
```
--------------------------------
### Context String Representation Example
Source: https://github.com/gofiber/docs/blob/master/versioned_docs/version-v3.x/api/ctx.md
Example showing the output format of the String() method, which includes connection details and request information.
```go
app.Get("/", func(c fiber.Ctx) error {
c.String() // => "#0000000100000001 - 127.0.0.1:3000 <-> 127.0.0.1:61516 - GET http://localhost:3000/"
// ...
})
```
--------------------------------
### Redirect Messages - Example
Source: https://github.com/gofiber/docs/blob/master/versioned_docs/version-v3.x/api/redirect.md
Example demonstrating how to retrieve all flash messages using the `Messages` method and return them as JSON.
```go
app.Get("/", func(c fiber.Ctx) error {
messages := c.Redirect().Messages()
return c.JSON(messages)
})
```
--------------------------------
### Example: Iterate Over Request Headers
Source: https://github.com/gofiber/docs/blob/master/versioned_docs/version-v3.x/client/request.md
Demonstrates iterating through all request headers and printing their keys and values. This example adds multiple values for the same header key.
```go
req := client.AcquireRequest()
req.AddHeader("Golang", "Fiber")
req.AddHeader("Test", "123456")
req.AddHeader("Test", "654321")
for k, v := range req.Headers() {
fmt.Printf("Header Key: %s, Header Value: %v\n", k, v)
}
```
```sh
Header Key: Golang, Header Value: [Fiber]
Header Key: Test, Header Value: [123456 654321]
```
--------------------------------
### Example: Using Context for Goroutines
Source: https://github.com/gofiber/docs/blob/master/versioned_docs/version-v3.x/api/ctx.md
This example illustrates obtaining a `context.Context` from `fiber.Ctx` to safely use in a goroutine, ensuring it remains valid after the handler completes.
```go
app.Get("/", func(c fiber.Ctx) error {
ctx := c.Context()
go doWork(ctx)
return nil
})
```
--------------------------------
### Subdomain Routing Example in Fiber
Source: https://github.com/gofiber/docs/blob/master/versioned_docs/version-v3.x/extra/faq.md
This example demonstrates how to set up subdomain routing in Fiber by mapping different hostnames to distinct Fiber applications. It shows how to handle requests based on the incoming hostname.
```go
package main
import (
"log"
"github.com/gofiber/fiber/v3"
"github.com/gofiber/fiber/v3/middleware/logger"
)
type Host struct {
Fiber *fiber.App
}
func main() {
// Hosts
hosts := map[string]*Host{}
//-----
// API
//-----
api := fiber.New()
api.Use(logger.New(logger.Config{
Format: "[${ip}]:${port} ${status} - ${method} ${path}\n",
}))
hosts["api.localhost:3000"] = &Host{api}
api.Get("/", func(c fiber.Ctx) error {
return c.SendString("API")
})
//------
// Blog
//------
blog := fiber.New()
blog.Use(logger.New(logger.Config{
Format: "[${ip}]:${port} ${status} - ${method} ${path}\n",
}))
hosts["blog.localhost:3000"] = &Host{blog}
blog.Get("/", func(c fiber.Ctx) error {
return c.SendString("Blog")
})
//---------
// Website
//---------
site := fiber.New()
site.Use(logger.New(logger.Config{
Format: "[${ip}]:${port} ${status} - ${method} ${path}\n",
}))
hosts["localhost:3000"] = &Host{site}
site.Get("/", func(c fiber.Ctx) error {
return c.SendString("Website")
})
// Server
app := fiber.New()
app.Use(func(c fiber.Ctx) error {
host := hosts[c.Hostname()]
if host == nil {
return c.SendStatus(fiber.StatusNotFound)
} else {
host.Fiber.Handler()(c.Context())
return nil
}
})
log.Fatal(app.Listen(":3000"))
}
```
--------------------------------
### Fiber v2 vs v3 Utils Migration Example
Source: https://github.com/gofiber/docs/blob/master/versioned_docs/version-v3.x/whats_new.md
This example demonstrates how to update your code when migrating from Fiber v2's internal utils to Fiber v3's external `github.com/gofiber/utils/v2` module and the standard `strings` package.
```go
// v2
import oldutils "github.com/gofiber/fiber/v2/utils"
func demo() {
b := oldutils.TrimBytes([]byte(" fiber "))
id := oldutils.UUIDv4()
s := oldutils.GetString([]byte("foo"))
}
// v3
import (
"github.com/gofiber/utils/v2"
"strings"
)
func demo() {
s := utils.TrimSpace(" fiber ")
id := utils.UUIDv4()
str := utils.ToString([]byte("foo"))
t := strings.TrimRight("bar ", " ")
}
```
--------------------------------
### Redirect Status - Example
Source: https://github.com/gofiber/docs/blob/master/versioned_docs/version-v3.x/api/redirect.md
Example showing how to use the `Status` method to set a specific HTTP status code (e.g., 301 Moved Permanently) before redirecting.
```go
app.Get("/coffee", func(c fiber.Ctx) error {
// => HTTP - GET 301 /teapot
return c.Redirect().Status(fiber.StatusMovedPermanently).To("/teapot")
})
```
--------------------------------
### Service Start Method
Source: https://github.com/gofiber/docs/blob/master/versioned_docs/version-v3.x/api/services.md
The Start method is invoked by Fiber when the application begins its startup sequence. It should handle the initialization of the service and return an error if any issues occur.
```go
func (s *SomeService) Start(ctx context.Context) error
```
--------------------------------
### Simple GET Request Handler
Source: https://github.com/gofiber/docs/blob/master/versioned_docs/version-v3.x/partials/routing/handler.md
Example of a basic handler for a GET request to '/api/list'. It returns a string response.
```go
// Simple GET handler
app.Get("/api/list", func(c fiber.Ctx) error {
return c.SendString("I'm a GET request!")
})
```
--------------------------------
### SendEarlyHints Example
Source: https://github.com/gofiber/docs/blob/master/versioned_docs/version-v3.x/api/ctx.md
Example of using SendEarlyHints to send a preload link header for a JavaScript file, allowing the browser to start preloading resources.
```go
hints := []string{"; rel=preload; as=script"}
app.Get("/early", func(c fiber.Ctx) error {
if err := c.SendEarlyHints(hints); err != nil {
return err
}
return c.SendString("done")
})
```
--------------------------------
### Basic Timeout Example
Source: https://github.com/gofiber/docs/blob/master/versioned_docs/version-v3.x/middleware/timeout.md
This example demonstrates how to use the timeout middleware to enforce a 2-second deadline on a handler. The handler simulates work using sleepWithContext, which respects context cancellation.
```go
package main
import (
"context"
"fmt"
"log"
"time"
"github.com/gofiber/fiber/v3"
"github.com/gofiber/fiber/v3/middleware/timeout"
)
func sleepWithContext(ctx context.Context, d time.Duration) error {
select {
case <-time.After(d):
return nil
case <-ctx.Done():
return ctx.Err()
}
}
func main() {
app := fiber.New()
handler := func(c fiber.Ctx) error {
delay, _ := time.ParseDuration(c.Params("delay") + "ms")
if err := sleepWithContext(c.Context(), delay); err != nil {
return fmt.Errorf("%w: execution error", err)
}
return c.SendString("finished")
}
app.Get("/sleep/:delay", timeout.New(handler, timeout.Config{
Timeout: 2 * time.Second,
}))
log.Fatal(app.Listen(":3000"))
}
```
--------------------------------
### Example: Naming Routes
Source: https://github.com/gofiber/docs/blob/master/versioned_docs/version-v3.x/api/app.md
Demonstrates how to assign names to various routes, including those within a group, and then prints the application's route stack.
```go
package main
import (
"encoding/json"
"fmt"
"log"
"github.com/gofiber/fiber/v3"
)
func main() {
var handler = func(c fiber.Ctx) error { return nil }
app := fiber.New()
app.Get("/", handler)
app.Name("index")
app.Get("/doe", handler).Name("home")
app.Trace("/tracer", handler).Name("tracert")
app.Delete("/delete", handler).Name("delete")
a := app.Group("/a")
a.Name("fd.")
a.Get("/test", handler).Name("test")
data, _ := json.MarshalIndent(app.Stack(), "", " ")
fmt.Println(string(data))
log.Fatal(app.Listen(":3000"))
}
```
--------------------------------
### Minimal Fiber App
Source: https://github.com/gofiber/docs/blob/master/versioned_docs/version-v3.x/guide/routing.md
A basic Fiber application demonstrating how to set up a route and start the server. This serves as a foundational example for routing.
```go
package main
import "github.com/gofiber/fiber/v3"
func main() {
app := fiber.New()
app.Get("/", func(c fiber.Ctx) error {
return c.SendString("Hello, World!")
})
app.Listen(":3000")
}
```
--------------------------------
### Domain Routing Examples
Source: https://github.com/gofiber/docs/blob/master/versioned_docs/version-v3.x/whats_new.md
Demonstrates various ways to use domain routing, including static domains, domains with parameters, grouping routes under domains, applying middleware to domains, and mounting sub-applications.
```go
app := fiber.New()
// Static domain
app.Domain("api.example.com").Get("/users", func(c fiber.Ctx) error {
return c.SendString("API users")
})
// Domain with parameter
app.Domain(":user.blog.example.com").Get("/", func(c fiber.Ctx) error {
user := fiber.DomainParam(c, "user")
return c.SendString(user + "'s blog")
})
// Domain with groups
api := app.Domain("api.example.com")
v1 := api.Group("/v1")
v1.Get("/posts", listPosts)
// Domain with middleware
admin := app.Domain("admin.example.com")
admin.Use(authMiddleware)
admin.Get("/dashboard", dashboardHandler)
// Mount sub-applications on domain routers
subApp := fiber.New()
subApp.Get("/users", listUsers)
app.Domain("api.example.com").Use("/api", subApp)
// Fallback for unmatched domains
app.Get("/", func(c fiber.Ctx) error {
return c.SendString("default site")
})
```
--------------------------------
### Run Setup Checks
Source: https://github.com/gofiber/docs/blob/master/README.md
Performs TypeScript and build target checks.
```bash
npm run check
```
--------------------------------
### Configuring TLS Minimum Version for Listening
Source: https://github.com/gofiber/docs/blob/master/versioned_docs/version-v3.x/whats_new.md
Example of setting the minimum TLS version when starting a Fiber server listener with a specific configuration.
```go
app.Listen(":444", fiber.ListenConfig{TLSMinVersion: tls.VersionTLS12})
```
--------------------------------
### Basic Auth Client Example
Source: https://github.com/gofiber/docs/blob/master/versioned_docs/version-v3.x/client/examples.md
Demonstrates how a client sends credentials using the 'Authorization: Basic' header. Ensure the server is configured to handle basic authentication.
```go
package main
import (
"encoding/base64"
"fmt"
"github.com/gofiber/fiber/v3/client"
)
func main() {
cc := client.New()
out := base64.StdEncoding.EncodeToString([]byte("john:doe"))
resp, err := cc.Get("http://localhost:3000", client.Config{
Header: map[string]string{
"Authorization": "Basic " + out,
},
})
if err != nil {
panic(err)
}
fmt.Print(string(resp.Body()))
}
```
--------------------------------
### Download File Example
Source: https://github.com/gofiber/docs/blob/master/versioned_docs/version-v3.x/api/ctx.md
Demonstrates how to use the Download method to send a file to the client, with an option to override the default filename.
```go
app.Get("/", func(c fiber.Ctx) error {
return c.Download("./files/report-12345.pdf")
// => Download report-12345.pdf
return c.Download("./files/report-12345.pdf", "report.pdf")
// => Download report.pdf
})
```
--------------------------------
### Basic Host Authorization Setup
Source: https://github.com/gofiber/docs/blob/master/versioned_docs/version-v3.x/middleware/hostauthorization.md
Configure the middleware with a list of allowed hosts to protect your application.
```go
app.Use(hostauthorization.New(hostauthorization.Config{
AllowedHosts: []string{"api.myapp.com"},
}))
app.Get("/users", func(c fiber.Ctx) error {
return c.JSON(getUsers())
})
// Host: api.myapp.com → 200 OK
// Host: evil.com → 403 Forbidden
```
--------------------------------
### Helmet Middleware Usage
Source: https://github.com/gofiber/docs/blob/master/versioned_docs/version-v3.x/middleware/helmet.md
This example demonstrates how to integrate the Helmet middleware into a Fiber application. It shows the basic setup and how to apply it globally using `app.Use()`.
```APIDOC
## Helmet Middleware Usage
### Description
This example demonstrates how to integrate the Helmet middleware into a Fiber application. It shows the basic setup and how to apply it globally using `app.Use()`.
### Method
`app.Use()`
### Endpoint
Applies to all routes.
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```go
package main
import (
"github.com/gofiber/fiber/v3"
"github.com/gofiber/fiber/v3/middleware/helmet"
)
func main() {
app := fiber.New()
// Add Helmet middleware
app.Use(helmet.New())
app.Get("/", func(c fiber.Ctx) error {
return c.SendString("Welcome!")
})
app.Listen(":3000")
}
```
### Response
#### Success Response (200)
None specific to middleware setup.
#### Response Example
None
```
--------------------------------
### Next Example
Source: https://github.com/gofiber/docs/blob/master/versioned_docs/version-v3.x/api/ctx.md
Demonstrates the chaining of middleware and routes using the Next function. Multiple routes can be executed in sequence.
```go
app.Get("/", func(c fiber.Ctx) error {
fmt.Println("1st route!")
return c.Next()
})
app.Get("*", func(c fiber.Ctx) error {
fmt.Println("2nd route!")
return c.Next()
})
app.Get("/", func(c fiber.Ctx) error {
fmt.Println("3rd route!")
return c.SendString("Hello, World!")
})
```
--------------------------------
### Example: GetRoute and Generate URL
Source: https://github.com/gofiber/docs/blob/master/versioned_docs/version-v3.x/api/app.md
Shows how to retrieve a route by name and then use it to generate a URL with parameters. It also demonstrates retrieving and printing route details.
```go
package main
import (
"encoding/json"
"fmt"
"log"
"github.com/gofiber/fiber/v3"
)
func main() {
app := fiber.New()
app.Get("/", handler).Name("index")
app.Get("/user/:name/:id", handler).Name("user")
route := app.GetRoute("index")
data, _ := json.MarshalIndent(route, "", " ")
fmt.Println(string(data))
userRoute := app.GetRoute("user")
location, _ := userRoute.URL(fiber.Map{"name": "john", "id": 1})
fmt.Println(location) // /user/john/1
log.Fatal(app.Listen(":3000"))
}
```
--------------------------------
### Get TLS ClientHelloInfo
Source: https://github.com/gofiber/docs/blob/master/versioned_docs/version-v3.x/api/ctx.md
Retrieves information from a TLS ClientHello message. This is useful for guiding application logic related to TLS connections, such as certificate selection.
```go
app.Get("/hello", func(c fiber.Ctx) error {
chi := c.ClientHelloInfo()
// ...
})
```
--------------------------------
### Retrieve and Print Response Cookies Example
Source: https://github.com/gofiber/docs/blob/master/versioned_docs/version-v3.x/client/response.md
Shows how to get all cookies from a response and print their keys and values. Note that the cookie slice is only valid until the response is released.
```go
resp, err := client.Get("https://httpbin.org/cookies/set/go/fiber")
if err != nil {
panic(err)
}
cookies := resp.Cookies()
for _, cookie := range cookies {
fmt.Printf("%s => %s\n", string(cookie.Key()), string(cookie.Value()))
}
```
--------------------------------
### Basic SendFile Example
Source: https://github.com/gofiber/docs/blob/master/versioned_docs/version-v3.x/api/ctx.md
Demonstrates basic usage of SendFile to transfer a file and how to disable compression.
```go
app.Get("/not-found", func(c fiber.Ctx) error {
return c.SendFile("./public/404.html")
// Disable compression
return c.SendFile("./static/index.html", fiber.SendFile{
Compress: false,
})
})
```
--------------------------------
### TLS Client Example
Source: https://github.com/gofiber/docs/blob/master/versioned_docs/version-v3.x/client/examples.md
Demonstrates configuring a client to trust a specific certificate for TLS connections. Ensure the 'ssl.cert' file is accessible.
```go
package main
import (
"crypto/tls"
"crypto/x509"
"fmt"
"os"
"github.com/gofiber/fiber/v3/client"
)
func main() {
cc := client.New()
certPool, err := x509.SystemCertPool()
if err != nil {
panic(err)
}
cert, err := os.ReadFile("ssl.cert")
if err != nil {
panic(err)
}
certPool.AppendCertsFromPEM(cert)
cc.SetTLSConfig(&tls.Config{
RootCAs: certPool,
})
resp, err := cc.Get("https://localhost:3000")
if err != nil {
panic(err)
}
fmt.Print(string(resp.Body()))
}
```
--------------------------------
### Example: Add and Send File
Source: https://github.com/gofiber/docs/blob/master/versioned_docs/version-v3.x/client/request.md
Shows how to add a file to the request using its path and then send the request.
```go
req := client.AcquireRequest()
defere client.ReleaseRequest(req)
req.AddFile("test.txt")
resp, err := req.Post("https://httpbin.org/post")
if err != nil {
panic(err)
}
fmt.Println(string(resp.Body()))
```
```json
{
"args": {},
"data": "",
"files": {
"file1": "This is an empty file!\n"
},
"form": {},
// ...
}
```
--------------------------------
### GoFiber Route Definition Signature
Source: https://github.com/gofiber/docs/blob/master/versioned_docs/version-v3.x/intro.md
Illustrates the function signature for defining routes in GoFiber. The 'Get' method is an example, with 'Post', 'Put', and 'Delete' working similarly. It takes a path, a handler, and optional additional handlers.
```go
func (app *App) Get(path string, handler any, handlers ...any) Router
```
--------------------------------
### Debug Endpoint to Verify Reverse Proxy Configuration
Source: https://github.com/gofiber/docs/blob/master/versioned_docs/version-v3.x/guide/reverse-proxy.md
An example Fiber route that returns debugging information about the client IP, trusted proxy status, and raw header values to verify reverse proxy setup.
```go
app.Get("/debug", func(c fiber.Ctx) error {
return c.JSON(fiber.Map{
"c.IP()": c.IP(), // Should show real client IP
"X-Forwarded-For": c.Get("X-Forwarded-For"), // Raw header value
"IsProxyTrusted": c.IsProxyTrusted(), // Should be true
"RemoteIP": c.RequestCtx().RemoteIP().String(), // Proxy IP
})
})
```
--------------------------------
### Use Registered Custom Tag in Logger Format
Source: https://github.com/gofiber/docs/blob/master/versioned_docs/version-v3.x/middleware/logger.md
After installing middleware that registers a custom logger tag, you can use this tag within the logger's format string. This example shows how to include the 'tenant' tag in the log format.
```go
app.Use(tenantmw.New())
app.Use(logger.New(logger.Config{
Format: "${tenant} ${status} ${method} ${path}\n",
}))
```
--------------------------------
### SendStream Example
Source: https://github.com/gofiber/docs/blob/master/versioned_docs/version-v3.x/api/ctx.md
Example of sending a simple byte stream as the response body.
```go
app.Get("/", func(c fiber.Ctx) error {
return c.SendStream(bytes.NewReader([]byte("Hello, World!")))
// => "Hello, World!"
})
```
--------------------------------
### Manual Toolchain Build and Run
Source: https://github.com/gofiber/docs/blob/master/blog/2026-02-14-spa-delivery-with-fiber-v3.md
Build the frontend assets using yarn and then run the Go application locally.
```bash
# Option B: Manual toolchain
cd web && yarn install && yarn build
cd ..
go run ./cmd/react-router/main.go
```
--------------------------------
### Install Project Dependencies
Source: https://github.com/gofiber/docs/blob/master/README.md
Installs all necessary project dependencies using npm ci.
```bash
npm ci
```
--------------------------------
### SendStreamWriter Example
Source: https://github.com/gofiber/docs/blob/master/versioned_docs/version-v3.x/api/ctx.md
Example of using SendStreamWriter to write a simple string to the response body.
```go
app.Get("/", func (c fiber.Ctx) error {
return c.SendStreamWriter(func(w *bufio.Writer) {
fmt.Fprintf(w, "Hello, World!\n")
})
// => "Hello, World!"
})
```
--------------------------------
### Example: GetRoutes with Filter
Source: https://github.com/gofiber/docs/blob/master/versioned_docs/version-v3.x/api/app.md
Demonstrates how to retrieve all routes, filtering out those registered by middleware, and then prints the resulting list of routes.
```go
package main
import (
"encoding/json"
"fmt"
"log"
"github.com/gofiber/fiber/v3"
)
func main() {
app := fiber.New()
app.Post("/", func(c fiber.Ctx) error {
return c.SendString("Hello, World!")
}).Name("index")
routes := app.GetRoutes(true)
data, _ := json.MarshalIndent(routes, "", " ")
fmt.Println(string(data))
log.Fatal(app.Listen(":3000"))
}
```
--------------------------------
### TLS Server Example
Source: https://github.com/gofiber/docs/blob/master/versioned_docs/version-v3.x/client/examples.md
Shows how to configure a Fiber server to use TLS certificates for secure connections. The 'ssl.cert' and 'ssl.key' files must be provided.
```go
package main
import (
"github.com/gofiber/fiber/v3"
)
func main() {
app := fiber.New()
app.Get("/", func(c fiber.Ctx) error {
return c.SendString("Hello, World!")
})
err := app.Listen(":3000", fiber.ListenConfig{
CertFile: "ssl.cert",
CertKeyFile: "ssl.key",
})
if err != nil {
panic(err)
}
}
```
--------------------------------
### Format Response Example (With Default)
Source: https://github.com/gofiber/docs/blob/master/versioned_docs/version-v3.x/api/ctx.md
Illustrates using the Format method with a default handler, which is used when no other content type matches the Accept header.
```go
// Accept: application/json => {"command":"eat","subject":"fruit"}
// Accept: text/plain => Eat Fruit!
// Accept: application/xml => Eat Fruit!
app.Get("/default", func(c fiber.Ctx) error {
textHandler := func(c fiber.Ctx) error {
return c.SendString("Eat Fruit!")
}
handlers := []fiber.ResFmt{
{"application/json", func(c fiber.Ctx) error {
return c.JSON(fiber.Map{
"command": "eat",
"subject": "fruit",
})
}},
{"text/plain", textHandler},
{"default", textHandler},
}
return c.Format(handlers...)
})
```
--------------------------------
### Express.js Middleware Example
Source: https://github.com/gofiber/docs/blob/master/blog/2026-04-16-fiber-v3-express-style-handlers.md
An example of logging middleware in Express.js that logs the request method, path, and duration.
```javascript
// Express.js
app.use((req, res, next) => {
const start = Date.now();
res.on('finish', () => {
console.log(`${req.method} ${req.path} - ${Date.now() - start}ms`);
});
next();
});
app.get('/users/:id', (req, res) => {
const user = findUser(req.params.id);
if (!user) {
return res.status(404).json({ error: 'not found' });
}
res.json(user);
});
```
--------------------------------
### Start Service Method
Source: https://github.com/gofiber/docs/blob/master/versioned_docs/version-v3.x/api/services.md
Starts the service. Fiber calls this method when the application begins its startup sequence.
```APIDOC
## Start
Starts the service. Fiber calls this when the application starts.
```go
func (s *SomeService) Start(ctx context.Context) error
```
```
--------------------------------
### Basic Auth Server Example
Source: https://github.com/gofiber/docs/blob/master/versioned_docs/version-v3.x/client/examples.md
Shows a server-side implementation of basic authentication using the Fiber middleware. Passwords should be securely hashed.
```go
package main
import (
"github.com/gofiber/fiber/v3"
"github.com/gofiber/fiber/v3/middleware/basicauth"
)
func main() {
app := fiber.New()
app.Use(
basicauth.New(basicauth.Config{
Users: map[string]string{
// "doe" hashed using SHA-256
"john": "{SHA256}eZ75KhGvkY4/t0HfQpNPO1aO0tk6wd908bjUGieTKm8=",
},
}),
)
app.Get("/", func(c fiber.Ctx) error {
return c.SendString("Hello, World!")
})
app.Listen(":3000")
}
```
--------------------------------
### RouteChain Example
Source: https://github.com/gofiber/docs/blob/master/versioned_docs/version-v3.x/api/app.md
Demonstrates how to use RouteChain for declaring routes and applying middleware. Use `RouteChain` as a chainable route declaration method.
```go
package main
import (
"log"
"github.com/gofiber/fiber/v3"
)
func main() {
app := fiber.New()
// Use `RouteChain` as a chainable route declaration method
app.RouteChain("/test").Get(func(c fiber.Ctx) error {
return c.SendString("GET /test")
})
app.RouteChain("/events").All(func(c fiber.Ctx) error {
// Runs for all HTTP verbs first
// Think of it as route-specific middleware!
return c.Next()
}).
Get(func(c fiber.Ctx) error {
return c.SendString("GET /events")
}).
Post(func(c fiber.Ctx) error {
// Maybe add a new event...
return c.SendString("POST /events")
})
// Combine multiple routes
app.RouteChain("/reports").RouteChain("/daily").Get(func(c fiber.Ctx) error {
return c.SendString("GET /reports/daily")
})
// Use multiple methods
app.RouteChain("/api").Get(func(c fiber.Ctx) error {
return c.SendString("GET /api")
}).Post(func(c fiber.Ctx) error {
return c.SendString("POST /api")
})
log.Fatal(app.Listen(":3000"))
}
```
--------------------------------
### Matched Example
Source: https://github.com/gofiber/docs/blob/master/versioned_docs/version-v3.x/api/ctx.md
An example middleware that checks if the current request path was matched. If not matched, it returns a 404 Not Found status.
```go
app.Use(func(c fiber.Ctx) error {
if c.Matched() {
return c.Next()
}
return c.Status(fiber.StatusNotFound).SendString("Not Found")
})
```
--------------------------------
### Fiber App Domain Routing Example
Source: https://github.com/gofiber/docs/blob/master/versioned_docs/version-v3.x/api/app.md
Demonstrates various ways to use the `Domain` method, including static domains, domains with parameters, composable groups with middleware, mounting sub-applications, and fallback routes.
```go
package main
import (
"log"
"github.com/gofiber/fiber/v3"
)
func main() {
app := fiber.New()
// Static domain — only matches requests to api.example.com
app.Domain("api.example.com").Get("/users", func(c fiber.Ctx) error {
return c.SendString("API users list")
})
// Domain with parameter
app.Domain(":user.blog.example.com").Get("/", func(c fiber.Ctx) error {
user := fiber.DomainParam(c, "user")
return c.SendString(user + "'s blog")
})
// Composable with groups and middleware
admin := app.Domain("admin.example.com")
admin.Use(func(c fiber.Ctx) error {
// Only runs for admin.example.com
c.Set("X-Admin", "true")
return c.Next()
})
admin.Get("/dashboard", func(c fiber.Ctx) error {
return c.SendString("Admin Dashboard")
})
// Mount sub-applications on domain routers
subApp := fiber.New()
subApp.Get("/users", func(c fiber.Ctx) error {
return c.SendString("Users list")
})
app.Domain("api.example.com").Use("/api", subApp)
// Fallback for unmatched domains
app.Get("/", func(c fiber.Ctx) error {
return c.SendString("Default site")
})
log.Fatal(app.Listen(":3000"))
}
```
--------------------------------
### Pug Template Example
Source: https://github.com/gofiber/docs/blob/master/blog/2026-05-08-fiber-v3-template-engines.md
A Pug template that renders a title using Pug's syntax, equivalent to the HTML example.
```pug
h1= Title
p Welcome to #{Title}
```
--------------------------------
### Fiber App Testing Example
Source: https://github.com/gofiber/docs/blob/master/versioned_docs/version-v3.x/api/app.md
Demonstrates how to create a test request, set custom headers, perform the test, and process the response.
```go
package main
import (
"fmt"
"io"
"log"
"net/http"
"net/http/httptest"
"github.com/gofiber/fiber/v3"
)
func main() {
app := fiber.New()
// Create route with GET method for test:
app.Get("/", func(c fiber.Ctx) error {
fmt.Println(c.BaseURL()) // => http://google.com
fmt.Println(c.Get("X-Custom-Header")) // => hi
return c.SendString("hello, World!")
})
// Create http.Request
req := httptest.NewRequest("GET", "http://google.com", nil)
req.Header.Set("X-Custom-Header", "hi")
// Perform the test
resp, _ := app.Test(req)
// Do something with the results:
if resp.StatusCode == fiber.StatusOK {
body, _ := io.ReadAll(resp.Body)
fmt.Println(string(body)) // => hello, World!
}
}
```
--------------------------------
### Example: Set Cookie and Make Request
Source: https://github.com/gofiber/docs/blob/master/versioned_docs/version-v3.x/client/rest.md
Demonstrates setting a cookie for the client and then making a request to an endpoint that inspects cookies. The server should return the set cookie.
```go
cc := client.New()
cc.SetCookie("john", "doe")
resp, err := cc.Get("https://httpbin.org/cookies")
if err != nil {
panic(err)
}
fmt.Println(string(resp.Body()))
```
--------------------------------
### Send GET Request
Source: https://github.com/gofiber/docs/blob/master/versioned_docs/version-v3.x/client/request.md
Sends an HTTP GET request to the specified URL. Use this method to retrieve data from a server.
```go
func (r *Request) Get(url string) (*Response, error)
```
--------------------------------
### Redirect Example
Source: https://github.com/gofiber/docs/blob/master/versioned_docs/version-v3.x/api/ctx.md
Demonstrates how to use the Redirect method to send an HTTP redirect response to a different URL.
```go
app.Get("/coffee", func(c fiber.Ctx) error {
return c.Redirect().To("/teapot")
})
app.Get("/teapot", func(c fiber.Ctx) error {
return c.Status(fiber.StatusTeapot).Send("🍵 short and stout 🍵")
})
```
--------------------------------
### SendStreamWriter Example with Flushing
Source: https://github.com/gofiber/docs/blob/master/versioned_docs/version-v3.x/api/ctx.md
Example demonstrating how to use w.Flush() within SendStreamWriter to send data incrementally and handle client disconnections.
```go
app.Get("/wait", func(c fiber.Ctx) error {
return c.SendStreamWriter(func(w *bufio.Writer) {
// Begin Work
fmt.Fprintf(w, "Please wait for 10 seconds\n")
if err := w.Flush(); err != nil {
log.Print("Client disconnected!")
return
}
// Send progress over time
time.Sleep(time.Second)
for i := 0; i < 9; i++ {
fmt.Fprintf(w, "Still waiting...\n")
if err := w.Flush(); err != nil {
// If client disconnected, cancel work and finish
log.Print("Client disconnected!")
return
}
time.Sleep(time.Second)
}
// Finish
fmt.Fprintf(w, "Done!\n")
})
})
```
--------------------------------
### Switching to Pug Template Engine
Source: https://github.com/gofiber/docs/blob/master/blog/2026-05-08-fiber-v3-template-engines.md
Demonstrates how to switch from the html/template engine to the Pug engine by changing the import and constructor. Handlers and layouts remain the same.
```go
import "github.com/gofiber/template/pug/v2"
engine := pug.New("./views", ".pug")
```