Episode 1 of 8

Intro to the Fiber Web Framework

Get started with Go Fiber — the fastest Go web framework inspired by Express.js. Learn what Fiber is, why it's blazing fast, how to install it, create your first server, and understand the core concepts that make Fiber the top choice for building Go web applications.

If you've ever used Express.js in Node.js and wished you could have that same clean, intuitive API in Go — Fiber is exactly that. Built on top of Fasthttp (the fastest HTTP engine for Go), Fiber delivers Express-like simplicity with Go's raw performance. In benchmarks, Fiber handles 2-3x more requests per second than Gin and Echo while using less memory. This tutorial series will take you from zero to building production-ready APIs with Fiber.

What is Fiber?

Fiber is an Express-inspired web framework built on top of Fasthttp. It's designed to ease things up for fast development with zero memory allocation and performance in mind. Key features include:

  • Express-like syntax — If you know Express.js, you already know 80% of Fiber
  • Built on Fasthttp — Up to 10x faster than net/http based frameworks
  • Zero memory allocation — Fiber reuses memory aggressively for maximum throughput
  • Middleware support — Logger, CORS, Rate Limiter, Helmet, and 20+ built-in middlewares
  • Low learning curve — Simple, intuitive API that feels natural
  • WebSocket support — Built-in WebSocket upgrade handling
  • Template engines — Support for HTML, Pug, Handlebars, and more

Fiber vs Other Go Frameworks

How does Fiber compare to other popular Go frameworks?

Fiber vs Gin: Fiber is faster (Fasthttp vs net/http), has Express-like syntax (familiar to JavaScript developers), and uses less memory per request. Gin has a larger ecosystem and community, and uses the standard net/http library (which some prefer for compatibility). Choose Fiber for: maximum performance and Express familiarity. Choose Gin for: largest community and standard library compatibility.

Fiber vs Echo: Both are fast and have similar API designs. Fiber is ~2x faster in benchmarks due to Fasthttp. Echo uses net/http and has excellent documentation. Fiber has more built-in middlewares. Both are excellent choices — Fiber wins on raw speed.

Fiber vs Chi: Chi is minimalistic and uses the standard net/http library. Fiber is more opinionated with more built-in features. Chi is better for developers who want a thin router on top of net/http. Fiber is better for developers who want a full-featured framework.

Installation and Setup

First, make sure you have Go installed (version 1.21 or later). Create a new project:

mkdir fiber-tutorial
cd fiber-tutorial
go mod init fiber-tutorial
go get github.com/gofiber/fiber/v2

That's it — Fiber is installed. Let's create our first server.

Your First Fiber Server

Create a file called main.go:

package main

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

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

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

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

Run it with go run main.go and visit http://localhost:3000. You'll see "Hello, Fiber! 🚀".

Let's break down what's happening:

  • fiber.New() creates a new Fiber application instance
  • app.Get("/", handler) registers a GET route at the root path
  • c *fiber.Ctx is the context object — it holds the request and response
  • c.SendString() sends a plain text response
  • app.Listen(":3000") starts the HTTP server on port 3000

Fiber App Configuration

You can customize the Fiber app with configuration options:

app := fiber.New(fiber.Config{
    AppName:       "My Fiber App v1.0",
    ServerHeader:  "Fiber",
    CaseSensitive: true,             // /Foo and /foo are different routes
    StrictRouting: true,             // /foo and /foo/ are different routes
    Prefork:       false,            // Enable prefork for multi-process
    BodyLimit:     10 * 1024 * 1024, // 10 MB body limit
    ReadTimeout:   10 * time.Second,
    WriteTimeout:  10 * time.Second,
    IdleTimeout:   120 * time.Second,
})

Important config options:

  • Prefork — Spawns multiple Go processes (one per CPU core) for maximum throughput. Enable in production for CPU-bound workloads.
  • BodyLimit — Maximum request body size. Default is 4 MB. Increase for file uploads.
  • ReadTimeout / WriteTimeout — Prevents slow clients from holding connections indefinitely.
  • CaseSensitive — By default, /Foo and /foo match the same route. Set to true for strict matching.

Routing Basics

Fiber supports all standard HTTP methods:

// GET — Read data
app.Get("/users", getUsers)

// POST — Create data
app.Post("/users", createUser)

// PUT — Update data (full replacement)
app.Put("/users/:id", updateUser)

// PATCH — Update data (partial)
app.Patch("/users/:id", patchUser)

// DELETE — Remove data
app.Delete("/users/:id", deleteUser)

// ALL — Match any HTTP method
app.All("/api/*", apiHandler)

Route Grouping

Group related routes together using app.Group():

func main() {
    app := fiber.New()

    // API v1 group
    v1 := app.Group("/api/v1")
    
    // /api/v1/users
    users := v1.Group("/users")
    users.Get("/", getUsers)        // GET /api/v1/users
    users.Post("/", createUser)     // POST /api/v1/users
    users.Get("/:id", getUser)      // GET /api/v1/users/:id
    users.Put("/:id", updateUser)   // PUT /api/v1/users/:id
    users.Delete("/:id", deleteUser) // DELETE /api/v1/users/:id

    // /api/v1/products
    products := v1.Group("/products")
    products.Get("/", getProducts)
    products.Post("/", createProduct)

    log.Fatal(app.Listen(":3000"))
}

Route groups keep your code organized and make it easy to apply middleware to specific groups (like authentication for protected routes).

Built-in Middleware

Fiber comes with many useful middlewares out of the box:

import (
    "github.com/gofiber/fiber/v2"
    "github.com/gofiber/fiber/v2/middleware/logger"
    "github.com/gofiber/fiber/v2/middleware/cors"
    "github.com/gofiber/fiber/v2/middleware/recover"
    "github.com/gofiber/fiber/v2/middleware/helmet"
)

func main() {
    app := fiber.New()

    // Logger — logs every request
    app.Use(logger.New())

    // Recover — catches panics and returns 500 instead of crashing
    app.Use(recover.New())

    // CORS — enables Cross-Origin Resource Sharing
    app.Use(cors.New(cors.Config{
        AllowOrigins: "http://localhost:3000, https://myapp.com",
        AllowMethods: "GET,POST,PUT,DELETE",
    }))

    // Helmet — sets security headers
    app.Use(helmet.New())

    app.Get("/", func(c *fiber.Ctx) error {
        return c.SendString("Secured with middleware!")
    })

    log.Fatal(app.Listen(":3000"))
}

Error Handling

Fiber provides a clean error handling mechanism:

// Custom error handler in config
app := fiber.New(fiber.Config{
    ErrorHandler: func(c *fiber.Ctx, err error) error {
        // Default to 500
        code := fiber.StatusInternalServerError

        // Check if it's a Fiber error
        if e, ok := err.(*fiber.Error); ok {
            code = e.Code
        }

        return c.Status(code).JSON(fiber.Map{
            "error":   true,
            "message": err.Error(),
        })
    },
})

// Return errors from handlers
app.Get("/user/:id", func(c *fiber.Ctx) error {
    id := c.Params("id")
    
    user, err := findUser(id)
    if err != nil {
        return fiber.NewError(fiber.StatusNotFound, "User not found")
    }
    
    return c.JSON(user)
})

Project Structure

For a well-organized Fiber project, follow this structure:

fiber-tutorial/
├── main.go              # Entry point — initializes app and starts server
├── go.mod
├── go.sum
├── config/
│   └── config.go        # App configuration
├── handlers/
│   ├── user.go          # User route handlers
│   └── product.go       # Product route handlers
├── middleware/
│   └── auth.go          # Custom middleware
├── models/
│   ├── user.go          # User model/struct
│   └── product.go       # Product model/struct
├── routes/
│   └── routes.go        # Route definitions
└── database/
    └── database.go      # Database connection

This separation of concerns keeps your codebase clean as the project grows. Each handler file contains related route handlers, models define your data structures, and routes wire everything together.

What's Next

You now understand what Fiber is, how to set it up, define routes, use middleware, and handle errors. In the next tutorial, we'll dive deeper into creating and testing API endpoints — building a complete CRUD API with proper request validation and structured responses.

GoFiberWeb DevelopmentTutorial