Learn Fiber Β· 6/14

Structuring Your Fiber Project

7 min read

Structuring Your Fiber Project πŸ“

Welcome back! So you've gotten your feet wet with Fiber, creating handlers and routes in a single file. That's fantastic for quick prototypes and small projects. But what happens when your application starts to grow? Imagine trying to build a skyscraper with the architectural plans for a single-story house. Things would get messy, confusing, and probably fall over. πŸ€ͺ

Similarly, as your web application or API gains more features, keeping everything in one main.go file becomes a recipe for disaster. It's hard to find things, difficult to maintain, and a nightmare for teamwork. This is where project structuring comes in, providing a blueprint for a clean, scalable, and maintainable application.


Beyond Single-File Apps: MVC and Clean Architecture πŸ—οΈ

The Problem: Your main.go is becoming a "God object," a single file that knows and does everything. It handles routes, database logic, and business rules. This makes it incredibly difficult to test, debug, and add new features without breaking existing ones.

The Solution: We can take inspiration from established architectural patterns like Model-View-Controller (MVC) and Clean Architecture to organize our code logically.

  • Model: Represents your data and business logic. Think of this as the brain of your application. It handles data validation and interaction with the database. For example, in a user management system, the User model would define the structure of a user and have functions to create, read, update, and delete users.
  • View: This is what the user sees. In a traditional web application, this would be your HTML templates. For a REST API, your "view" is the JSON response you send back to the client.
  • Controller (or Handler in Go terminology): Acts as the intermediary between the Model and the View. It receives incoming requests, uses the Model to perform actions, and then sends a response back (the View).

Clean Architecture takes this a step further by emphasizing a separation of concerns and making the application independent of frameworks, UI, and databases. The core idea is that your business logic should not be tightly coupled to the web framework you are using. This makes your application more resilient to change.

A typical project structure inspired by these patterns might look like this:

jboss-cli
/my-fiber-app
β”œβ”€β”€ /cmd
β”‚   └── /web
β”‚       └── main.go         // Entry point of your application
β”œβ”€β”€ /internal
β”‚   β”œβ”€β”€ /handlers           // Your request handlers (Controllers)
β”‚   β”œβ”€β”€ /models             // Your data structures
β”‚   └── /database           // Database connection and queries
β”œβ”€β”€ go.mod
β”œβ”€β”€ go.sum

This structure provides a clear separation of concerns. Your main.go is now just responsible for starting the server and setting up the routes. The actual business logic resides in the /internal directory.


Route Grouping and API Versioning 🚦

The Problem: As your API grows, you'll have more and more routes. Imagine an e-commerce API with routes for users, products, orders, and payments. Dumping them all in one place makes your main.go look like a tangled mess of spaghetti. 🍝 Additionally, what happens when you need to make breaking changes to your API? You can't just update a route and expect all your users to adapt immediately.

The Solution: Fiber provides a powerful feature called route grouping. It allows you to group related routes under a common prefix. This is also the perfect mechanism for API versioning.

Let's see it in action. Imagine we are building an API for a bookstore.

go
package main

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

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

    // Group for API version 1
    v1 := app.Group("/api/v1")

    // Routes for books in v1
    v1.Get("/books", getBooks)
    v1.Get("/books/:id", getBook)
    v1.Post("/books", createBook)

    // Group for API version 2 (maybe with a new feature)
    v2 := app.Group("/api/v2")

    // Routes for books in v2
    v2.Get("/books", getBooksV2) // A new and improved handler

    app.Listen(":3000")
}

// Handler functions (for brevity, we'll keep them simple)
func getBooks(c *fiber.Ctx) error {
    return c.SendString("All books from v1")
}

func getBook(c *fiber.Ctx) error {
    return c.SendString("A single book from v1")
}

func createBook(c *fiber.Ctx) error {
    return c.SendString("Creating a book in v1")
}

func getBooksV2(c *fiber.Ctx) error {
    return c.SendString("All books with new features from v2")
}

Now, your API has a clear structure. Users can access the first version of your API through /api/v1 and the new version through /api/v2. This allows you to introduce new features or make breaking changes without affecting existing users. It’s like having different-colored lanes on a highway, each leading to a specific destination.

Fun Fact: The concept of API versioning is crucial for the evolution of software. Think about your favorite apps on your phone. They get updates all the time, but older versions often continue to work for a while. That's thanks to careful versioning!


Separating Handlers and Controllers from Routes βœ‚οΈ

The Problem: Even with route grouping, our main.go can still get cluttered if we define all the handler functions directly within it. This violates the single-responsibility principle and makes our code harder to read and test.

The Solution: We move our handler functions into their own dedicated files and packages. Let's revisit our project structure and see how this fits in.

Our main.go in /cmd/web/main.go would now look something like this:

go
package main

import (
    "my-fiber-app/internal/handlers"
    "github.com/gofiber/fiber/v2"
)

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

    // API version 1 group
    v1 := app.Group("/api/v1")
    v1.Get("/books", handlers.GetBooks)
    v1.Get("/books/:id", handlers.GetBook)
    v1.Post("/books", handlers.CreateBook)


    app.Listen(":3000")
}

And our handlers would live in /internal/handlers/book_handler.go:

go
package handlers

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

func GetBooks(c *fiber.Ctx) error {
    return c.SendString("All books from our separated handler!")
}

func GetBook(c *fiber.Ctx) error {
    return c.SendString("A single book from our separated handler!")
}

func CreateBook(c *fiber.Ctx) error {
    return c.SendString("Creating a book from our separated handler!")
}

See how much cleaner our main.go is? Its only job is to set up the server and wire up the routes to the appropriate handlers. The handlers themselves are neatly organized in their own package, each responsible for a specific piece of functionality. This is like having a well-organized toolbox where every tool has its designated spot, making it easy to find what you need. πŸ› οΈ


Configuration Management with Environment Variables βš™οΈ

The Problem: Your application needs to connect to a database, listen on a specific port, and might have secret keys for external services. Hardcoding these values directly in your code is a huge security risk and makes it inflexible. You don't want to recompile your entire application just to change the database password. That's like soldering the key directly into your front door lock! πŸ”‘

The Solution: We use environment variables to store configuration. Environment variables are variables that are set in the operating system and are accessible to your running application. This allows you to configure your application externally without changing the code.

Go's standard library provides the os package to access environment variables. However, for a more robust solution, it's common to use a library like godotenv to load these variables from a .env file during development.

First, install the godotenv package:

bash
go get github.com/joho/godotenv

Next, create a .env file in the root of your project:

ini
# .env
PORT=8080
DB_HOST=localhost
DB_PORT=5432
DB_USER=myuser
DB_PASSWORD=mypassword
DB_NAME=mydatabase

Important: Always add your .env file to your .gitignore to avoid accidentally committing sensitive information to your version control system.

Now, in your main.go, you can load and use these variables:

go
package main

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

func main() {
    // Load .env file
    err := godotenv.Load()
    if err != nil {
        log.Println("Error loading .env file, using default or environment-set variables")
    }

    port := os.Getenv("PORT")
    if port == "" {
        port = "3000" // Default port if not set
    }

    app := fiber.New()

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

    log.Fatal(app.Listen(":" + port))
}

This approach makes your application much more flexible and secure. You can have different .env files for your development, staging, and production environments, each with its own specific configuration.

By following these structuring principles, you're not just writing code; you're building a solid foundation for a scalable and maintainable application. Happy coding! πŸš€


Further Reading & References

Challenge

Your task is to refactor and structure a basic Fiber web application by implementing API versioning using route grouping and separating handler logic from the main function.

Requirements:

  1. Define Handlers: Create four distinct handler functions outside of the main function. Each handler must accept a *fiber.Ctx and return an error.

    • getV1Books(c *fiber.Ctx) error: This handler should respond with the JSON object {"api_version": 1, "resource": "books"}.
    • getV1Authors(c *fiber.Ctx) error: This handler should respond with the JSON object {"api_version": 1, "resource": "authors"}.
    • getV2Books(c *fiber.Ctx) error: This handler should respond with the JSON object {"api_version": 2, "resource": "books", "status": "stable"}.
    • getV2Authors(c *fiber.Ctx) error: This handler should respond with the JSON object {"api_version": 2, "resource": "authors", "status": "stable"}.
  2. Structure Routes in main: Inside the main function, after initializing the Fiber app:

    • Create a route group for API version 1 with the prefix /api/v1.
    • Create a second route group for API version 2 with the prefix /api/v2.
    • Register GET routes for /books and /authors within each group, and wire them to the corresponding handler functions you created.

Expected result

The final submission should be a complete, single Go source file. It must contain:

  1. The main package declaration and the "github.com/gofiber/fiber/v2" import.
  2. The four required handler functions (getV1Books, getV1Authors, getV2Books, getV2Authors), each correctly implemented to return the specified JSON payload.
  3. A main function that initializes a Fiber app, creates two distinct route groups for /api/v1 and /api/v2, and correctly maps the GET /books and GET /authors endpoints within each group to their respective handlers.
go

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.