DEV Community

Juma
Juma

Posted on

Clean Architecture in Go

Clean Architecture in Go: Why Your main.go Shouldn't Be 900 Lines

Every backend developer has a first project that looks like a crime scene. Mine certainly did. One file. Routes, database queries, validation, password checks, and a mysterious function called doStuff2 all living together like students in a rented room, with nobody washing the dishes.

It worked, too. That's the cruel part. The app ran, the demo went fine, and I felt like a genius until someone asked me to add one small feature. I opened the file, scrolled for ninety seconds, and felt the cold dread of a person who has realized they built a house of cards in a wind tunnel.

This article is about the fix: clean architecture, specifically the flavor many Go developers settle on, with three layers called handlers, services, and repositories. By the end you'll know what each layer does, why the boundaries matter, and how to set this up in a Gin and GORM project without needing a PhD in diagrams.

The restaurant analogy (Did you know "everything is a restaurant")

Picture a decent restaurant.

The waiter talks to the customer. He takes the order, writes it down, and brings the food. He does not cook. If he tried, you'd file a complaint and possibly call the fire department.

The chef knows the recipes and the rules. Fish isn't served with that sauce. A well-done steak takes twelve minutes. The chef decides what should happen, but she doesn't walk to the farm to pick tomatoes.

The pantry is where ingredients live. Someone knows how to fetch, store, and count them. The chef says "I need two onions" and doesn't care whether they came from a shelf, a fridge, or a truck.

Now map it:

  • Handler = waiter. Deals with HTTP: requests in, responses out.
  • Service = chef. Holds the business rules.
  • Repository = pantry. Talks to the database.

That's the whole idea. Everything else is detail and good manners.

What actually goes wrong in the single-file approach

Let's look at a typical "everything in one place" handler. You've probably written something like this (I have, and I'm not proud):

func CreateUser(c *gin.Context) {
    var input struct {
        Email    string `json:"email"`
        Password string `json:"password"`
    }
    if err := c.ShouldBindJSON(&input); err != nil {
        c.JSON(400, gin.H{"error": "bad input"})
        return
    }

    if !strings.Contains(input.Email, "@") {
        c.JSON(400, gin.H{"error": "invalid email"})
        return
    }

    var existing User
    if err := db.Where("email = ?", input.Email).First(&existing).Error; err == nil {
        c.JSON(409, gin.H{"error": "email taken"})
        return
    }

    hash, _ := bcrypt.GenerateFromPassword([]byte(input.Password), 12)
    user := User{Email: input.Email, PasswordHash: string(hash)}
    db.Create(&user)

    c.JSON(201, user)
}
Enter fullscreen mode Exit fullscreen mode

Look at everything this one function does: parses JSON, validates email, queries the database, checks for duplicates, hashes a password, writes to the database, and formats the response. That's seven jobs. A waiter, a chef, and a farmer, all in one overworked human.

Problems appear quickly:

You can't test it without a database. To check whether duplicate emails are rejected, you need a running Postgres. Your tests become slow, flaky, and tragic.

You can't reuse it. Suppose an admin panel also creates users, or a CLI import tool does. You'd copy-paste the logic, and now you have two chefs with slightly different recipes. One of them forgets to hash the password. Guess which one ends up in a security incident.

You can't change anything safely. Want to swap Gin for another framework? The business rules are tangled in c.JSON calls. Want to change databases? db.Where is sprinkled everywhere like glitter. Glitter is easy to spread and impossible to remove.

The three layers, one at a time

Layer 1: The repository (the pantry)

The repository's only job is to store and fetch data. It knows SQL, or GORM, or whatever you use. It knows nothing about HTTP and nothing about business rules.

First, define what the repository can do, as an interface:

package repository

import "yourapp/internal/domain"

type UserRepository interface {
    Create(user *domain.User) error
    FindByEmail(email string) (*domain.User, error)
    FindByID(id uint) (*domain.User, error)
}
Enter fullscreen mode Exit fullscreen mode

Notice this is just a list of promises. "I can create, I can find by email, I can find by ID." It says nothing about how.

Then the GORM implementation:

type userRepository struct {
    db *gorm.DB
}

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

func (r *userRepository) Create(user *domain.User) error {
    return r.db.Create(user).Error
}

func (r *userRepository) FindByEmail(email string) (*domain.User, error) {
    var user domain.User
    if err := r.db.Where("email = ?", email).First(&user).Error; err != nil {
        return nil, err
    }
    return &user, nil
}
Enter fullscreen mode Exit fullscreen mode

That's it. No hashing, no "is this email valid?", no JSON. The pantry doesn't have opinions about the menu.

Layer 2: The service (the chef)

The service is where the rules live. "Emails must be unique." "Passwords get hashed." "Users under 18 can't register." These rules are the reason your app exists. They're the valuable part. The rest is plumbing.

package service

type UserService interface {
    Register(email, password string) (*domain.User, error)
}

type userService struct {
    repo repository.UserRepository
}

func NewUserService(repo repository.UserRepository) UserService {
    return &userService{repo: repo}
}

var ErrEmailTaken = errors.New("email already registered")

func (s *userService) Register(email, password string) (*domain.User, error) {
    existing, err := s.repo.FindByEmail(email)
    if err == nil && existing != nil {
        return nil, ErrEmailTaken
    }

    hash, err := bcrypt.GenerateFromPassword([]byte(password), 12)
    if err != nil {
        return nil, fmt.Errorf("hashing password: %w", err)
    }

    user := &domain.User{Email: email, PasswordHash: string(hash)}
    if err := s.repo.Create(user); err != nil {
        return nil, fmt.Errorf("creating user: %w", err)
    }
    return user, nil
}
Enter fullscreen mode Exit fullscreen mode

Here's the beautiful part. Look at what's missing. There's no gin.Context. No status codes. No JSON. The service doesn't know the internet exists. It receives plain Go values, applies rules, and returns plain Go values or errors.

And look at how it gets its pantry: through the repo field, typed as the interface. The service doesn't know whether the repository is backed by Postgres, SQLite, or a very organized hamster. This is called dependency injection, which is a scary name for "pass in what you need instead of grabbing it yourself."

Layer 3: The handler (the waiter)

Finally, the handler. Its entire personality is: translate between HTTP and the service.

package handler

type UserHandler struct {
    service service.UserService
}

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

type registerRequest struct {
    Email    string `json:"email" binding:"required,email"`
    Password string `json:"password" binding:"required,min=8"`
}

func (h *UserHandler) Register(c *gin.Context) {
    var req registerRequest
    if err := c.ShouldBindJSON(&req); err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
        return
    }

    user, err := h.service.Register(req.Email, req.Password)
    if err != nil {
        if errors.Is(err, service.ErrEmailTaken) {
            c.JSON(http.StatusConflict, gin.H{"error": "email already registered"})
            return
        }
        c.JSON(http.StatusInternalServerError, gin.H{"error": "something went wrong"})
        return
    }

    c.JSON(http.StatusCreated, gin.H{"id": user.ID, "email": user.Email})
}
Enter fullscreen mode Exit fullscreen mode

Compare this to the monster from earlier. The handler is short and boring, and boring is a compliment in backend code. It parses the request, calls the service, and picks a status code. Notice the response returns only id and email, not the whole user struct, so the password hash never leaves the building. Small habit, big difference.

Wiring it together

Somewhere you have to connect these pieces. That somewhere is main.go, and this is the one job it should have:

func main() {
    db := database.Connect()

    userRepo := repository.NewUserRepository(db)
    userService := service.NewUserService(userRepo)
    userHandler := handler.NewUserHandler(userService)

    r := gin.Default()
    r.POST("/register", userHandler.Register)
    r.Run(":8080")
}
Enter fullscreen mode Exit fullscreen mode

Read it top to bottom like a recipe: connect the database, build the pantry, hand it to the chef, hand the chef to the waiter, open the doors. Your main.go is now twenty lines instead of nine hundred, and every line says what it means.

A folder structure that won't make you cry

A common layout:

yourapp/
├── cmd/
│   └── api/
│       └── main.go
├── internal/
│   ├── domain/        # structs like User, Order
│   ├── handler/       # HTTP layer
│   ├── service/       # business rules
│   └── repository/    # database layer
├── migrations/
├── web/               # your HTML, CSS, JS
├── Dockerfile
└── Makefile
Enter fullscreen mode Exit fullscreen mode

The internal folder is a Go feature: code inside it can't be imported by other modules. It's a built-in "staff only" sign. Use it.

The domain package holds your core structs. Everything else depends on it and it depends on nothing, which is the heart of the clean-architecture idea. Dependencies point inward. Handlers know about services, services know about repositories and domain, and the domain knows about nobody. If you ever catch your domain package importing Gin, stop, breathe, and gently close the laptop.

The payoff: testing without a database

Remember how the old code couldn't be tested without Postgres? Watch this. Because the service depends on an interface, we can hand it a fake:

type fakeUserRepo struct {
    users map[string]*domain.User
}

func (f *fakeUserRepo) Create(u *domain.User) error {
    f.users[u.Email] = u
    return nil
}

func (f *fakeUserRepo) FindByEmail(email string) (*domain.User, error) {
    if u, ok := f.users[email]; ok {
        return u, nil
    }
    return nil, errors.New("not found")
}

func (f *fakeUserRepo) FindByID(id uint) (*domain.User, error) {
    return nil, errors.New("not implemented")
}

func TestRegister_DuplicateEmail(t *testing.T) {
    repo := &fakeUserRepo{users: map[string]*domain.User{
        "a@b.com": {Email: "a@b.com"},
    }}
    svc := NewUserService(repo)

    _, err := svc.Register("a@b.com", "password123")

    if !errors.Is(err, ErrEmailTaken) {
        t.Fatalf("expected ErrEmailTaken, got %v", err)
    }
}
Enter fullscreen mode Exit fullscreen mode

This test runs in microseconds. No Docker, no database, no waiting. You can write fifty of them before your coffee gets cold. That is the real superpower of this structure: your business rules become cheap to verify, and cheap verification means you actually do it.

Common mistakes (a field guide to my own embarrassment)

Mistake 1: Putting business logic in handlers. The handler is tempting because it's right there. "Just one little if here." Then it's twelve ifs and you've rebuilt your single-file monster in a nicer folder. Rule of thumb: if a rule would still matter after you swapped HTTP for a command-line tool, it belongs in the service.

Mistake 2: Leaking GORM into services. If your service imports gorm.io/gorm and calls .Where(), you've got a pantry in the chef's pocket. Keep database details in the repository.

Mistake 3: Over-engineering a tiny app. Not every project needs three layers, ten interfaces, and a dependency injection framework. If you're building a weekend prototype, a flatter structure is fine. Clean architecture earns its keep when the project will grow, change, or be maintained by anyone, including future you, who will have forgotten everything.

Mistake 4: Giant interfaces. An interface with twenty methods is a sign the layer is doing too much. Go proverb: the bigger the interface, the weaker the abstraction. Keep them small and focused.

Mistake 5: Returning database models straight to the client. Your database struct and your API response are different things. Today they match. Next month you add a password_hash column and suddenly it's in the JSON. Map to a response shape explicitly.

"But this is so much more code!"

Yes. For the first hour, it is. You'll write an interface, a struct, a constructor, and wiring, just to save a user. It feels like hiring three people to change one lightbulb.

But think about month three. A new rule arrives: "Users must verify their email before logging in." In the old code, you hunt through scattered handlers hoping you found every place that matters. In the clean version, you open the service, change the rule, and every entry point picks it up. The code is longer, but the thinking is shorter, and thinking is the expensive part.

Structure is a loan you take out on day one and repay with interest-free convenience for the rest of the project's life.

Quick recap

  • Handlers speak HTTP. Parse, call the service, respond. Nothing more.
  • Services hold business rules. They don't know about Gin or GORM.
  • Repositories speak to the database behind interfaces.
  • Dependencies point inward, and main.go only wires things together.
  • Interfaces let you test the rules with fakes, no database required.
  • Don't over-engineer small projects, but do reach for this structure when a project is meant to grow.

Top comments (0)