Go clean architecture is a way to organise your code. It keeps business rules free from databases, web frameworks and other tools. In this post, you will learn the layers, the dependency rule and a simple folder layout. Then we will build a small book service, where you can swap the storage without touching the business code.
This lesson builds on Go interfaces with examples and Go modules and packages. We also reuse ideas from Go mocking interfaces for testing and Go REST API for beginners. Because interfaces are the key tool here, read that post first if needed. Also, a quick look at the structs lesson helps.
What Is Go Clean Architecture?
In short, Go clean architecture splits a program into layers. The inner layer holds your business rules, such as “a book needs a title and an author”. Meanwhile, the outer layers hold details, such as HTTP handlers and database code. The most important rule is simple. Outer layers may depend on inner layers, but never the other way round.
Think of a power plug. Your laptop does not care whether the electricity comes from solar panels or a coal plant. It only needs a standard socket. Similarly, your business code should only need a standard interface. It should not care if the data lives in memory, PostgreSQL or a file.
Go suits Go clean architecture well, because interfaces are small and satisfied implicitly. As a result, you can define an interface in the inner layer. Then an outer package can implement it without importing anything special.
Why Go Clean Architecture Matters
Small programs can live in one file, and that is fine. However, real services grow, and tangled code becomes slow to change. For example, a new storage engine could force edits in twenty places. So here is what Go clean architecture gives you.
- Easy testing: the business layer needs no database or server in its tests.
- Swappable tools: you can change the database or the web layer without a rewrite.
- Clear ownership: every package has one job, so new teammates find code quickly.
- Safer changes: a change in the HTTP layer cannot break business rules.
- Longer life: the core of the app outlives any single library.
Because of this, teams adopt clean architecture when a project passes a few thousand lines. In fact, many Go teams use it as a shared language for code reviews. Therefore, new teammates understand the layout on day one.
How Go Clean Architecture Works
In Go clean architecture, you can think of three rings. First, in the centre sits the domain and service code, which holds entities and use cases. Next, around it sit the adapters, which turn the outside world into calls the service understands. Finally, at the edge sit the frameworks and drivers, such as net/http and PostgreSQL. Calls flow inward, and the dependency arrows point inward too.

Notice the clever part. The service needs to save books, but it does not know how. So it defines a Repository interface, and the database package implements it. As a result, the usual dependency flips. In other words, the database depends on the business code, not the reverse.
The Layers and Their Jobs
Each package has one clear job, so the table below lists the layers used in this lesson.
| Layer | Package | Job |
|---|---|---|
| Domain and service | internal/book | Entities, rules and the Repository interface |
| Storage adapter | internal/memory | Implements Repository with a map |
| HTTP adapter | internal/httpapi | Turns requests into service calls |
| Entry point | cmd/api | Wires every part together |
Also, the internal folder is special in Go. Only code in the same module can import it. As a result, outsiders cannot depend on your private parts.
The Folder Layout
Here is the layout that we build. Every file has a single purpose.
bookstore/
go.mod
cmd/api/main.go
internal/book/book.go
internal/book/service_test.go
internal/memory/repo.go
internal/httpapi/handler.go
Go Clean Architecture vs a Flat Layout
Many beginners put everything in main.go. That works for small tools, but it gets hard later. So the table below compares it with a layered design.
| Feature | Flat layout | Clean layout |
|---|---|---|
| Files | One or two | Several small packages |
| Testing the rules | Needs HTTP and storage | Needs only a fake repository |
| Changing the database | Edits spread everywhere | One new adapter |
| Time to start | Minutes | A little longer |
| Best for | Scripts and prototypes | Services that will grow |

So when should you use which? Use a flat layout for scripts and early prototypes. On the other hand, move to the clean layout when a second developer joins. You should also move when the service needs real tests.
Go Clean Architecture Hands-On: A Book Service
Now let’s build the service. Because we use only the standard library, you can run it anywhere. Also, every output below comes from a real run on Go 1.24.
Step 1: The Domain and Service
First, internal/book/book.go holds the entity, the errors, the interface and the use cases. It imports nothing from outside the standard library.
package book
import (
"context"
"errors"
"strings"
)
var (
ErrNotFound = errors.New("book not found")
ErrInvalid = errors.New("invalid book")
)
type Book struct {
ID int
Title string
Author string
}
// Repository is the port. The service only knows this interface.
type Repository interface {
Save(ctx context.Context, b Book) (Book, error)
Find(ctx context.Context, id int) (Book, error)
}
type Service struct {
repo Repository
}
func NewService(repo Repository) *Service { return &Service{repo: repo} }
func (s *Service) Add(ctx context.Context, title, author string) (Book, error) {
title, author = strings.TrimSpace(title), strings.TrimSpace(author)
if title == "" || author == "" {
return Book{}, ErrInvalid
}
return s.repo.Save(ctx, Book{Title: title, Author: author})
}
func (s *Service) Get(ctx context.Context, id int) (Book, error) {
return s.repo.Find(ctx, id)
}
Notice that the service takes the interface in its constructor. This is called dependency injection. However, it is only a fancy name for passing what you need as an argument.
Step 2: The Storage Adapter
Next, internal/memory/repo.go implements the interface with a map and a mutex. Later, you can write a PostgreSQL version with the same methods.
package memory
import (
"context"
"sync"
"bookstore/internal/book"
)
type Repo struct {
mu sync.Mutex
nextID int
books map[int]book.Book
}
func New() *Repo { return &Repo{nextID: 1, books: map[int]book.Book{}} }
func (r *Repo) Save(_ context.Context, b book.Book) (book.Book, error) {
r.mu.Lock()
defer r.mu.Unlock()
b.ID = r.nextID
r.nextID++
r.books[b.ID] = b
return b, nil
}
func (r *Repo) Find(_ context.Context, id int) (book.Book, error) {
r.mu.Lock()
defer r.mu.Unlock()
b, ok := r.books[id]
if !ok {
return book.Book{}, book.ErrNotFound
}
return b, nil
}
Step 3: The HTTP Adapter
Then internal/httpapi/handler.go turns requests into service calls. It also maps business errors to status codes in one place. First, here is the top of the file, with the constructor and the create route.
package httpapi
import (
"encoding/json"
"errors"
"net/http"
"strconv"
"bookstore/internal/book"
)
type Handler struct {
svc *book.Service
}
func New(svc *book.Service) http.Handler {
h := &Handler{svc: svc}
mux := http.NewServeMux()
mux.HandleFunc("POST /books", h.create)
mux.HandleFunc("GET /books/{id}", h.get)
return mux
}
func (h *Handler) create(w http.ResponseWriter, r *http.Request) {
var in struct {
Title string `json:"title"`
Author string `json:"author"`
}
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
http.Error(w, "invalid JSON", http.StatusBadRequest)
return
}
b, err := h.svc.Add(r.Context(), in.Title, in.Author)
if err != nil {
writeError(w, err)
return
}
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(b)
}
Next, here is the read route and the error mapping.
func (h *Handler) get(w http.ResponseWriter, r *http.Request) {
id, err := strconv.Atoi(r.PathValue("id"))
if err != nil {
http.Error(w, "invalid id", http.StatusBadRequest)
return
}
b, err := h.svc.Get(r.Context(), id)
if err != nil {
writeError(w, err)
return
}
json.NewEncoder(w).Encode(b)
}
// writeError maps business errors to HTTP status codes.
func writeError(w http.ResponseWriter, err error) {
switch {
case errors.Is(err, book.ErrNotFound):
http.Error(w, err.Error(), http.StatusNotFound)
case errors.Is(err, book.ErrInvalid):
http.Error(w, err.Error(), http.StatusUnprocessableEntity)
default:
http.Error(w, "internal error", http.StatusInternalServerError)
}
}
The handler knows about HTTP and about the service. However, it knows nothing about how books are stored. That separation is the whole point of Go clean architecture.
Step 4: Wire Everything in main
Finally, cmd/api/main.go creates each part and connects them. It is the only place that knows every package.
package main
import (
"fmt"
"net/http/httptest"
"strings"
"bookstore/internal/book"
"bookstore/internal/httpapi"
"bookstore/internal/memory"
)
func main() {
repo := memory.New()
svc := book.NewService(repo)
handler := httpapi.New(svc)
// In a real app: http.ListenAndServe(":8080", handler)
do := func(method, path, body string) {
req := httptest.NewRequest(method, path, strings.NewReader(body))
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
fmt.Printf("%s %s -> %d %s", method, path, rec.Code, rec.Body.String())
}
do("POST", "/books", `{"title":"Go in Action","author":"William Kennedy"}`)
do("GET", "/books/1", "")
do("GET", "/books/9", "")
do("POST", "/books", `{"title":"","author":"Nobody"}`)
}
Now run go run ./cmd/api. As a result, you see the real output below. The business rules work, and each error maps to the right status code.
POST /books -> 201 {"ID":1,"Title":"Go in Action","Author":"William Kennedy"}
GET /books/1 -> 200 {"ID":1,"Title":"Go in Action","Author":"William Kennedy"}
GET /books/9 -> 404 book not found
POST /books -> 422 invalid book
Step 5: Test the Rules with a Fake
Because the service depends on an interface, a test can pass a tiny fake. Therefore, no database or server is needed.
package book
import (
"context"
"errors"
"testing"
)
type fakeRepo struct{ saved []Book }
func (f *fakeRepo) Save(_ context.Context, b Book) (Book, error) {
b.ID = len(f.saved) + 1
f.saved = append(f.saved, b)
return b, nil
}
func (f *fakeRepo) Find(_ context.Context, id int) (Book, error) {
return Book{}, ErrNotFound
}
func TestAddRejectsEmptyTitle(t *testing.T) {
repo := &fakeRepo{}
svc := NewService(repo)
_, err := svc.Add(context.Background(), " ", "Someone")
if !errors.Is(err, ErrInvalid) {
t.Fatalf("err = %v, want ErrInvalid", err)
}
if len(repo.saved) != 0 {
t.Errorf("saved %d books, want 0", len(repo.saved))
}
}
Running go test ./... gives ok bookstore/internal/book. The test proves that an empty title is rejected. It also proves that nothing reaches storage. Also, it runs in milliseconds, because no real database is involved.
Common Mistakes with Go Clean Architecture
- Too many layers too early: tiny apps do not need five packages. So start small, and split when it hurts.
- Interfaces on the wrong side: if the storage package defines the interface, the service must import it. Instead, define it where it is used.
- Leaking HTTP types inward: passing
*http.Requestinto the service ties it to the web. So pass plain values and a context. - One giant interface: big interfaces are hard to fake. Therefore, keep them small.
- Business rules in handlers: rules then repeat in every adapter. Instead, keep them in the service, so every adapter gets the same behaviour for free.
Best Practices for Go Clean Architecture
- Define interfaces in the package that uses them, because it keeps dependencies pointing inward.
- Return domain errors, such as
ErrNotFound, and let adapters map them to status codes. - **Use the
internalfolder**, since it blocks outside imports. As a result, other modules cannot depend on your private code by accident. - **Wire everything in
main**, which keeps the rest of the code free from setup. Therefore, the other packages stay easy to reuse. - **Pass
context.Contextfirst**, because it supports timeouts and cancellation. - Test the service with fakes, and test adapters with
httptestor a real database. This split keeps the fast tests fast.
Practice Task
To practise Go clean architecture, add a Delete method to the service. First, add it to the Repository interface. Then implement it in the memory adapter, add a DELETE /books/{id} route and write a test with a fake.
Hint: return ErrNotFound when the id is missing. After that, map it to 404 in writeError. Finally, try writing a second adapter that stores books in a JSON file, and swap it in main.
Official Resources
These pages cover the language features and the project layout advice used here.
Quick Recap
- Go clean architecture keeps business rules free from databases and web code.
- Outer layers depend on inner layers, never the other way round.
- The service defines the interface, and the adapter implements it.
- Dependency injection means passing what you need as an argument.
- The
internalfolder andmainwiring keep the design tidy. - Fakes make business tests fast, because they need no real storage.
What’s Next?
By now, you can structure a service cleanly. However, many libraries rely on a hidden Go feature to read your structs. So in the next lesson, we will look under the hood at the reflect package and see how libraries read struct tags.
Next up: Go reflection basics


