How do I add middleware with Fiber in Go?

In this guide, we will explore how to add middleware to a Fiber application in Go. Middleware in Fiber allows you to add functionality to your routes, such as logging, authentication, and request parsing, among others.

This tutorial demonstrates adding middleware using Fiber in Go, enhancing your web application's capabilities and performance.

Go middleware, Fiber framework, Go web application, middleware example, Fiber routes

package main

import (
    "github.com/gofiber/fiber/v2"
)

// Middleware function to log requests
func logger(c *fiber.Ctx) error {
    // Log the request method and URL
    fmt.Printf("%s %s\n", c.Method(), c.Path())
    // Call the next handler in the chain
    return c.Next()
}

func main() {
    // Create a new Fiber app
    app := fiber.New()

    // Use the logger middleware for all routes
    app.Use(logger)

    // Define a simple route
    app.Get("/", func(c *fiber.Ctx) error {
        return c.SendString("Hello, World!")
    })

    // Start the server on port 3000
    app.Listen(":3000")
}

Go middleware Fiber framework Go web application middleware example Fiber routes