Learn Fiber Β· 1/14

Introduction to Fiber and Setup

7 min read

Introduction to Fiber and Setup Fiber is a web framework for the Go programming language, inspired by Express.js, that aims to provide a fast and minimalist foundation for building web applications and APIs. It's built on top of Fasthttp, the fastest HTTP engine for Go, which contributes to its high performance.

1. Why Fiber? The Express.js of Go πŸš€

If you're coming from a Node.js background and have used Express.js, you'll feel right at home with Fiber. The philosophy behind Fiber is to provide a similar, easy-to-use API, which significantly lowers the learning curve for developers transitioning to Go.

The Problem: When building web applications in Go, the standard net/http package is powerful but can be verbose for building complex applications. It requires more boilerplate code for routing, middleware, and handling requests and responses.

How Fiber Solves It: Fiber abstracts away much of this complexity, offering a simple and elegant way to define routes, handle middleware, and manage the request-response cycle. This allows for rapid development without sacrificing performance.

Imagine this: You're a city planner (the developer) designing a new city (your web application). Using net/http is like laying every single brick and paving every road yourself. It gives you ultimate control, but it's slow and tedious. Fiber, on the other hand, is like having pre-fabricated road sections, buildings, and traffic light systems. You still get to design the city's layout, but the building blocks are already optimized and easy to assemble, letting you build a functional city much faster.

Key Features that make Fiber stand out:

  • Extreme Performance: Built on Fasthttp, Fiber is known for its speed and low memory footprint.
  • Zero Memory Allocation: Fiber is designed to be highly efficient by avoiding unnecessary memory allocations in the hot path of request handling.
  • Robust Routing: Defining routes is straightforward and intuitive, similar to Express.
  • Middleware Support: Easily add middleware for logging, authentication, CORS, and more.

🧠 Fun Fact: The name "Fiber" is a nod to its lightweight and fast nature, much like a single, efficient strand.

2. Setting up your Go Workspace for Fiber πŸ› οΈ

Before we can start building amazing things with Fiber, we need to get our development environment ready. Don't worry, it's a straightforward process.

The Problem: To start a new Go project, you need to properly initialize your project directory so that Go can manage your dependencies (like the Fiber framework).

The Solution: Go uses "modules" to manage dependencies. We'll create a new directory for our project and initialize it as a Go module.

Step-by-step Setup:

  1. Ensure Go is Installed: First things first, make sure you have Go installed on your system. You can check this by opening your terminal and running:

    bash
    go version

    If you don't have Go installed, you can download it from the official Go website. Fiber requires Go version 1.25 or higher.

  2. Create a Project Directory: Let's create a new folder for our project and navigate into it.

    bash
    mkdir my-fiber-app
    cd my-fiber-app
  3. Initialize Go Modules: Now, we'll initialize our project as a Go module. This will create a go.mod file, which will keep track of our project's dependencies.

    bash
    go mod init my-fiber-app

    This command creates a go.mod file that will look something like this:

    apache
    module my-fiber-app
    
    go 1.25
  4. Install Fiber: With our module initialized, we can now add Fiber as a dependency.

    bash
    go get -u github.com/gofiber/fiber/v3

    This command will download the Fiber package and add it as a requirement in your go.mod and go.sum files.

And that's it! Your workspace is now ready for some Fiber action. ✨

3. Your First Fiber App: Hello World! πŸ‘‹

It's a tradition in the programming world to start with a "Hello, World!" application. Let's create a simple web server that responds with this classic greeting.

The Problem: We need to create a basic web server that listens for incoming HTTP requests and sends back a simple text response.

The Solution: We'll use Fiber to create a new application instance, define a route for the root URL (/), and start a server to listen for requests.

Create a new file named main.go in your project directory and add the following code:

go
package main

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

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

    // 2. Define a route for GET requests to the root path "/"
    app.Get("/", func(c fiber.Ctx) error {
        // 3. Send a string response to the client
        return c.SendString("Hello, World!")
    })

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

Let's break down the code:

  1. app := fiber.New(): This line creates a new instance of a Fiber application. You can think of app as the central hub of your web application, responsible for handling routing and middleware.
  2. app.Get("/", ...): Here, we are defining a route. We are telling our Fiber app that when it receives a GET request to the path / (the root of our website), it should execute the function we provide.
  3. func(c fiber.Ctx) error { ... }: This is our route handler. It's a function that takes a fiber.Ctx object as an argument. This Ctx object (short for Context) is super important; it holds information about the incoming request and provides methods for sending a response.
  4. return c.SendString("Hello, World!"): Inside our handler, we use the SendString method on the context to send the text "Hello, World!" back to the client (the web browser).
  5. log.Fatal(app.Listen(":3000")): This line starts our web server and makes it listen for incoming connections on port 3000. We wrap it in log.Fatal so that if the server fails to start for any reason, the program will exit with an error message.

Run your application:

Now, head back to your terminal and run your application:

bash
go run main.go

If everything is correct, you won't see any output in the terminal. Open your web browser and navigate to http://localhost:3000.

You should see "Hello, World!" displayed on the page. Congratulations, you've just built your first Fiber web application! πŸŽ‰

4. Understanding the Fiber Application Instance 🏭

We've already used app := fiber.New() to create our application instance, but let's dive a little deeper into what this app object is and what it can do.

The Problem: We need a central point to configure our web application, define how it handles requests, and control its overall behavior.

The Solution: The Fiber App instance is the core of your application. It acts as the main entry point for all incoming requests and provides methods to define routes, register middleware, and configure application settings.

Think of the app instance as the manager of a busy restaurant. This manager is responsible for:

  • Greeting guests at the door (Handling incoming requests): When a new request comes in, the app instance is the first to receive it.
  • Directing guests to their tables (Routing): Based on the URL and HTTP method of the request, the app instance decides which route handler should process it.
  • Taking orders and sending them to the kitchen (Passing request data to handlers): The app instance provides the request data to the appropriate handler through the fiber.Ctx object.
  • Ensuring a pleasant dining experience (Middleware): The manager can have general rules that apply to all guests, like "everyone gets a glass of water." This is similar to how middleware in Fiber can process every request before it reaches the specific route handler.

Common App Methods:

  • HTTP Method Routing: You've already seen app.Get(). Fiber provides methods for all the standard HTTP verbs:

    • app.Post("/submit", ...)
    • app.Put("/update/:id", ...)
    • app.Delete("/delete/:id", ...)
    • app.All("/any", ...): This will match any HTTP method.
  • Grouping Routes: You can group related routes under a common prefix. This is great for organizing your API.

    go
    api := app.Group("/api")
    v1 := api.Group("/v1")
    v1.Get("/users", ...) // Responds to /api/v1/users
  • Serving Static Files: If you need to serve files like images, CSS, or JavaScript, you can use the Static method.

    go
    app.Static("/", "./public") // Serves files from the "public" directory
  • Configuration: When you create a new Fiber app with fiber.New(), you can pass in a configuration object to customize its behavior.

    go
    app := fiber.New(fiber.Config{
        AppName: "My Awesome App",
    })

The app instance is the foundation of your Fiber application. As you build more complex applications, you'll become very familiar with its powerful features.


πŸ“š References for Extra Reading:

Challenge

Your task is to build a Go Fiber web application that includes configuration, route grouping, and static file serving. Write all your code within the main function.

Requirements:

  1. Create a new Fiber app instance.
  2. Configure this instance with an AppName of "My Awesome API v1".
  3. Set up a route group for all routes prefixed with /api.
  4. Within the /api group, define a GET route for /status. This route's handler should send the string response "API is running".
  5. Also within the /api group, define a POST route for /echo. This handler should send the string response "Echo endpoint ready".
  6. Configure a static file server. Requests to the URL path /public should serve files from a hypothetical local directory named ./assets.
  7. Start the application to listen for incoming connections on port 8080.

Expected result

Your code should correctly set up a Fiber application according to all the specified requirements, including the app name, static file serving, route grouping, and specific handlers for the GET and POST endpoints, before starting the listener on the correct port.

go
package main

import (
	"log"

	"github.com/gofiber/fiber/v3"
)

func main() {
	app := fiber.New(fiber.Config{
		AppName: "My Awesome API v1",
	})

	app.Static("/public", "./assets")

	api := app.Group("/api")

	api.Get("/status", func(c fiber.Ctx) error {
		return c.SendString("API is running")
	})

	api.Post("/echo", func(c fiber.Ctx) error {
		return c.SendString("Echo endpoint ready")
	})

	log.Fatal(app.Listen(":8080"))
}
go

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.