Learn Gin Β· 7/12

Structuring Your Gin Application πŸ—οΈ

8 min read

Structuring Your Gin Application πŸ—οΈ

Welcome! So, you've gotten your hands dirty with Gin, creating routes and handlers, and it feels great. But you've probably noticed your main.go file is starting to look a little... crowded. It's like a party where everyone is in the kitchen – it works for a little while, but soon nobody can move.

This guide is all about giving your application room to breathe. We'll transform your single-file app into a well-organized, scalable, and maintainable project.

1. Moving Beyond main.go: Best Practices for Project Layout

The Problem: When you start a new Gin project, it's tempting to put everything into a single main.go file. It's simple and it works. But as you add more routes, database logic, and utility functions, that one file becomes a "God object" – a monolithic beast that's terrifying to modify and a nightmare to debug. Finding a specific piece of logic feels like an archaeological dig.

The Solution: A structured, conventional directory layout. By separating your code based on its responsibility, you make it instantly easier to navigate, test, and maintain. Think of it as moving from a studio apartment where your bed, kitchen, and office are all the same thing, to a house with designated rooms for each activity.

A popular and effective structure for a Go web service looks something like this:

plaintext
/my-gin-app
β”œβ”€β”€ /cmd
β”‚   └── /web
β”‚       └── main.go         # Entry point of our application
β”œβ”€β”€ /internal
β”‚   β”œβ”€β”€ /config             # Configuration loading
β”‚   β”œβ”€β”€ /handler            # (or /controller) HTTP request handlers
β”‚   β”œβ”€β”€ /service            # Business logic
β”‚   └── /repository         # Data access and storage logic
β”œβ”€β”€ go.mod
β”œβ”€β”€ go.sum
└── .env                    # Environment variables file

This structure isn't rigid, but it's a fantastic starting point. The key idea is separation of concerns; each directory has a clear purpose.

2. The Controller Pattern: Separating Route Handlers

The Problem: In a simple app, your main.go might look like this, with handler logic directly inside the route definitions:

go
// main.go (The "Before" picture)
package main

import (
    "net/http"
    "github.com/gin-gonic/gin"
)

func main() {
    r := gin.Default()

    r.GET("/users/:id", func(c *gin.Context) {
        // ... logic to get user ID from path ...
        // ... logic to query the database ...
        // ... logic to handle database errors ...
        // ... logic to serialize user to JSON ...
        c.JSON(http.StatusOK, gin.H{"user": "found"})
    })

    r.POST("/users", func(c *gin.Context) {
        // ... logic to bind JSON from request body ...
        // ... logic to validate the user data ...
        // ... logic to insert into the database ...
        // ... logic to handle errors ...
        c.JSON(http.StatusCreated, gin.H{"user": "created"})
    })

    r.Run(":8080")
}

This gets messy, fast. Your main.go shouldn't be concerned with the nitty-gritty of how to fetch a user; its job is to wire up the application.

The Solution: Move the handler logic into its own package. This package is often called handler or controller. These handlers are functions that take a *gin.Context and are responsible for parsing the request and writing the response.

Let's refactor!

Step 1: Create the Handler File

go
// internal/handler/user.go
package handler

import (
    "net/http"
    "github.com/gin-gonic/gin"
)

// UserHandler might have dependencies, like a user service
type UserHandler struct {
    // userService service.UserService
}

func NewUserHandler(/* userService service.UserService */) *UserHandler {
    return &UserHandler{/* userService: userService */}
}

func (h *UserHandler) GetUser(c *gin.Context) {
    // Logic for getting a user now lives here
    userID := c.Param("id")
    c.JSON(http.StatusOK, gin.H{"message": "getting user " + userID})
}

func (h *UserHandler) CreateUser(c *gin.Context) {
    // Logic for creating a user now lives here
    c.JSON(http.StatusCreated, gin.H{"message": "user created"})
}

Step 2: Clean up main.go

Now, your main.go becomes a clean, readable setup file.

go
// cmd/web/main.go (The "After" picture ✨)
package main

import (
    "github.com/gin-gonic/gin"
    "my-gin-app/internal/handler" // Adjust import path
)

func main() {
    r := gin.Default()

    // Create an instance of our handler
    userHandler := handler.NewUserHandler()

    // Group user-related routes
    userRoutes := r.Group("/users")
    {
        userRoutes.GET("/:id", userHandler.GetUser)
        userRoutes.POST("", userHandler.CreateUser)
    }

    r.Run(":8080")
}

See how clean that is? The main.go file is now just responsible for routing and initialization. All the complex logic for handling user requests is neatly tucked away in internal/handler/user.go.

3. Services and Repositories: Isolating Business Logic

The Problem: Okay, our handlers are separate. But what if creating a user involves more than just a database insert? What if it needs to check for duplicates, send a welcome email, and log the event? If you put all that logic in the handler, the handler becomes bloated and hard to test. The handler's true job is to handle HTTP stuff, not business rules.

The Solution: Introduce two more layers: the Service and the Repository.

  • Service Layer πŸ§‘β€πŸ³: This is where your core business logic lives. It encapsulates the application's business rules and orchestrates tasks. It doesn't know anything about HTTP requests or responses. It just performs actions.
  • Repository Layer πŸ—„οΈ: This layer is responsible only for data access. Its job is to abstract away the database. This means your service layer doesn't care if you're using PostgreSQL, MongoDB, or a text file; it just asks the repository for data.

An Analogy: Imagine a fancy restaurant.

  • The Handler is the waiter. They take your order (the HTTP request), pass it to the kitchen, and bring you the food (the HTTP response).
  • The Service is the head chef. They take the order from the waiter, apply their culinary expertise (business logic), and tell the kitchen staff what to do.
  • The Repository is the pantry manager. The chef says, "I need tomatoes," and the pantry manager knows exactly where to get them (the database) without the chef needing to know the layout of the pantry.

Let's see it in code.

go
// internal/repository/user.go
package repository

// UserRepository defines the interface for user data access
type UserRepository interface {
    // In a real app, this would return a user object and an error
    FindByID(id string) (string, error)
}

// userRepo implements the UserRepository
type userRepo struct {
    // db *sql.DB // Your database connection would be here
}

func NewUserRepository(/* db *sql.DB */) UserRepository {
    return &userRepo{/* db: db */}
}

func (r *userRepo) FindByID(id string) (string, error) {
    // Database query logic goes here
    return "found user " + id + " in the database", nil
}

// internal/service/user.go
package service

import "my-gin-app/internal/repository"

type UserService interface {
    GetUser(id string) (string, error)
}

type userService struct {
    userRepo repository.UserRepository
}

// NewUserService uses Dependency Injection to get the repository
func NewUserService(repo repository.UserRepository) UserService {
    return &userService{userRepo: repo}
}

func (s *userService) GetUser(id string) (string, error) {
    // Business logic would go here (e.g., validation, etc.)
    return s.userRepo.FindByID(id)
}

Now, we inject the service into our handler:

go
// internal/handler/user.go
package handler

import (
    "net/http"
    "github.com/gin-gonic/gin"
    "my-gin-app/internal/service"
)

type UserHandler struct {
    userService service.UserService
}

func NewUserHandler(userService service.UserService) *UserHandler {
    return &UserHandler{userService: userService}
}

func (h *UserHandler) GetUser(c *gin.Context) {
    userID := c.Param("id")
    user, err := h.userService.GetUser(userID)
    if err != nil {
        c.JSON(http.StatusInternalServerError, gin.H{"error": "something went wrong"})
        return
    }
    c.JSON(http.StatusOK, gin.H{"user": user})
}

And finally, we wire it all together in main.go:

go
// cmd/web/main.go
package main

import (
    "github.com/gin-gonic/gin"
    "my-gin-app/internal/handler"
    "my-gin-app/internal/repository"
    "my-gin-app/internal/service"
)

func main() {
    // 1. Initialize Repository
    userRepo := repository.NewUserRepository()

    // 2. Initialize Service with Repository
    userService := service.NewUserService(userRepo)

    // 3. Initialize Handler with Service
    userHandler := handler.NewUserHandler(userService)

    // 4. Setup routes
    r := gin.Default()
    userRoutes := r.Group("/users")
    {
        userRoutes.GET("/:id", userHandler.GetUser)
    }

    r.Run(":8080")
}

This pattern, called Dependency Injection, makes your code incredibly modular, flexible, and easy to test.

4. Managing Configuration (Environment Variables & .env)

The Problem: Hardcoding values like your database password, API keys, or server port directly in your code is a cardinal sin of software development. It's insecure, and it makes it impossible to run your app in different environments (development, testing, production) without changing the code itself.

The Solution: Use environment variables. These are key-value pairs stored outside your application's code. For local development, it's convenient to manage these in a .env file.

Step 1: Install godotenv

This popular package helps load variables from a .env file into the environment.

sh
go get github.com/joho/godotenv

Step 2: Create a .env file

Create this file in the root of your project. Crucially, add .env to your .gitignore file to avoid committing secrets to version control!

env
# .env
SERVER_PORT=8080
DB_USER=myuser
DB_PASSWORD=supersecret

Step 3: Load and Use the Variables

We can create a simple config package to load and expose our configuration.

go
// internal/config/config.go
package config

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

type Config struct {
    ServerPort string
    DBUser     string
    DBPassword string
}

func Load() *Config {
    err := godotenv.Load()
    if err != nil {
        log.Println("No .env file found, using environment variables")
    }

    return &Config{
        ServerPort: getEnv("SERVER_PORT", "8081"), // Provide a default
        DBUser:     getEnv("DB_USER", ""),
        DBPassword: getEnv("DB_PASSWORD", ""),
    }
}

// Helper to get an environment variable or return a default
func getEnv(key string, defaultValue string) string {
    if value, exists := os.LookupEnv(key); exists {
        return value
    }
    return defaultValue
}

Now, in your main.go, you just need to load the config at the very beginning.

go
// cmd/web/main.go
package main

import (
    "fmt"
    "github.com/gin-gonic/gin"
    "my-gin-app/internal/config"
    // ... other imports
)

func main() {
    cfg := config.Load()
    // ... initialize repository, service, handler ...

    r := gin.Default()
    // ... setup routes ...

    // Use the port from your config!
    address := fmt.Sprintf(":%s", cfg.ServerPort)
    r.Run(address)
}

This approach keeps your code clean and your secrets safe, allowing for different configurations across different environments without a single code change.


Extra Reading πŸ“š

  • Official Gin Documentation: The source of truth for all things Gin.
  • Go's Official Tutorial: A great starting point for building a web service in Go.
  • Standard Go Project Layout: A comprehensive (and sometimes debated) guide to structuring Go projects.
  • Go by Example: Hands-on examples for learning Go syntax and features.

Challenge

Challenge: Refactor a Gin Application

You are tasked with restructuring a monolithic Go application into a clean, layered architecture using the Handler, Service, and Repository patterns. Your goal is to separate concerns and use dependency injection to wire the components together.

Requirements:

  1. Define Structs: Complete the struct definitions for UserRepository, UserService, and UserHandler.

    • UserRepository should depend on a mock database connection (*sql.DB).
    • UserService should depend on the UserRepository.
    • UserHandler should depend on the UserService.
  2. Implement Constructors: Create New... constructor functions for each of the three components. Each constructor must accept its dependencies as arguments and return a new instance of its respective struct.

  3. Implement CreateUser Methods: Fill in the logic for the CreateUser method in each layer.

    • Handler: The CreateUser method should accept a UserCreateRequest and pass the relevant data to the service layer. It should return the created User object and an error.
    • Service: The CreateUser method should perform business logic (e.g., validate the user data, although you can just add a comment for this) and then call the repository layer to persist the user. It should return the created User object and an error.
    • Repository: The CreateUser method should simulate interacting with the database. You can simply return a new User object with an ID assigned and nil for the error.
  4. Wire Dependencies: In the main function, instantiate and connect all the layers correctly using your constructor functions. The final userHandler variable should be a fully initialized component ready to handle requests.

Expected result

Your code should correctly define the structs, constructors, and methods for the Handler, Service, and Repository layers. The main function must demonstrate the dependency injection chain by initializing the repository first, passing it to the service's constructor, and then passing the created service to the handler's constructor. The final output should show a complete, wired-up application structure.

go
package main

import (
	"database/sql"
	"fmt"
	"time"
)

// --- MODELS ---

type User struct {
	ID        int
	Email     string
	CreatedAt time.Time
}

type UserCreateRequest struct {
	Email    string
	Password string
}

// --- REPOSITORY LAYER ---
// Simulates internal/repository/user_repository.go

type UserRepository struct {
	DB *sql.DB
}

func NewUserRepository(db *sql.DB) *UserRepository {
	return &UserRepository{DB: db}
}

func (r *UserRepository) CreateUser(email string) (*User, error) {
	fmt.Println("Repository: Creating user in the database...")
	// Simulate DB insertion
	user := &User{
		ID:        1,
		Email:     email,
		CreatedAt: time.Now(),
	}
	return user, nil
}

// --- SERVICE LAYER ---
// Simulates internal/service/user_service.go

type UserService struct {
	Repo *UserRepository
}

func NewUserService(repo *UserRepository) *UserService {
	return &UserService{Repo: repo}
}

func (s *UserService) CreateUser(req UserCreateRequest) (*User, error) {
	fmt.Println("Service: Applying business logic...")
	// Business logic like password hashing would go here
	return s.Repo.CreateUser(req.Email)
}

// --- HANDLER LAYER ---
// Simulates internal/handler/user_handler.go

type UserHandler struct {
	Service *UserService
}

func NewUserHandler(service *UserService) *UserHandler {
	return &UserHandler{Service: service}
}

func (h *UserHandler) CreateUser(req UserCreateRequest) (*User, error) {
	fmt.Println("Handler: Processing request...")
	return h.Service.CreateUser(req)
}

// --- MAIN APPLICATION ---
// Simulates cmd/web/main.go

func main() {
	// 1. Initialize dependencies (e.g., database connection)
	mockDB, _ := sql.Open("sqlite3", ":memory:") // Mock DB connection
	defer mockDB.Close()

	// 2. Wire the application layers together
	userRepo := NewUserRepository(mockDB)
	userService := NewUserService(userRepo)
	userHandler := NewUserHandler(userService)

	if userHandler != nil {
		fmt.Println("\n--- Running simulation ---")
		newUserReq := UserCreateRequest{Email: "[email protected]", Password: "password123"}
		createdUser, err := userHandler.CreateUser(newUserReq)
		if err != nil {
			fmt.Printf("Error creating user: %v\n", err)
			return
		}
		fmt.Printf("Successfully created user: ID=%d, Email=%s\n", createdUser.ID, createdUser.Email)
		fmt.Println("Application wired up correctly!")
	} else {
		fmt.Println("Application not wired up.")
	}
}
go

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.