Skip to content
Tutorials Center
My learning

Topics

Lesson 130 of 147 ยท Advanced Go

Layered and Hexagonal Architecture in Go

Structure Go programs with layers and hexagonal architecture - domain types, ports as small interfaces, adapters, a composition root and dependency injection without a framework.

Every program that survives a few years of changes ends up with the same problem: business rules, database calls, HTTP handlers and third-party clients are tangled together. You want to change the payment provider and find SQL strings in the handler. You want to test a discount rule and need a running database. The cure is not a framework. It is a way of drawing boundaries so that the important code does not know about the unimportant details.

Go is well suited to this because its interfaces are satisfied implicitly. The code that needs a capability declares a small interface, and anything with the right methods plugs in, without inheriting from anything. This lesson shows the two best-known shapes, layered and hexagonal (also called "ports and adapters") architecture, and how to do dependency injection with plain constructors. If interfaces still feel fuzzy, read interface design first.

The problem: dependencies that point the wrong way

In a naive layout the handler calls the service, the service calls the database package, and the database package imports the domain types. The business rules sit in the middle and depend on everything below them. Swap the database and the rules must change too.

The fix is to flip one arrow. The core of the program (the domain and the application services) defines what it needs, and the outer code implements it.

flowchart TB
    subgraph outer["Outside: details that change"]
        H["HTTP handlers / CLI"]
        DB["SQL repository"]
        N["Email / SMS client"]
    end
    subgraph core["Inside: rules that last"]
        S["Application service"]
        D["Domain types and rules"]
    end
    H -->|"calls"| S
    S --> D
    DB -.->|"implements port"| S
    N -.->|"implements port"| S

Solid arrows are calls; dotted arrows are implementations. Source-code dependencies all point toward the inside.

Notice what is not in the picture: no arrow from the service to the SQL repository. The service owns an interface, and the repository merely satisfies it.

Layered architecture

The classic arrangement has three layers, each allowed to talk only to the one beneath it:

Layer Contains Typical package
Transport HTTP handlers, CLI commands, gRPC servers. Decode input, call a service, encode output internal/httpapi
Service Use cases: "place an order", "pay an order". Coordinates the work internal/checkout
Storage Reads and writes data internal/store

Layers already help: handlers stay thin, and rules live in one place. Their weakness is that the service layer still imports the storage layer, so the arrow points down. Hexagonal architecture fixes this by making the service define the interface.

Hexagonal architecture: ports and adapters

Imagine the application as a hexagon. Its edge has ports, which are interfaces that describe how the outside world talks to it (driving ports) and how it talks to the outside world (driven ports). Outside the hexagon sit adapters that connect real technology to those ports.

flowchart LR
    CLI["CLI adapter"] --> P1(("driving<br/>port"))
    WEB["HTTP adapter"] --> P1
    P1 --> APP["Application<br/>+ domain"]
    APP --> P2(("driven<br/>port"))
    P2 --> MEM["In-memory adapter"]
    P2 --> SQL["SQL adapter"]
    APP --> P3(("driven<br/>port"))
    P3 --> MAIL["SMTP adapter"]
    P3 --> FAKE["Test fake"]

Driving adapters (left) call into the application; driven adapters (right) are called by it. Several adapters can fit one port.

In Go:

  • A driving port is usually just the public methods of your service struct. Handlers call them directly.
  • A driven port is an interface declared next to the code that uses it, with only the methods that code calls.
  • An adapter is any type that satisfies the interface: a SQL repository, an HTTP client wrapper, an in-memory map, a test fake.

Keep ports small. A Notifier with a single Notify method is better than a "NotificationService" with twelve methods, because small interfaces are easy to implement and easy to fake.

A complete example

The program below has all three pieces: domain rules, ports, a service, and two adapters wired together in main. Read it from the top, one section at a time.

Go Domain, ports, service and adapters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Three details deserve attention. First, the Order.Pay rule lives on the domain type and imports nothing. You can test it with no setup at all. Second, Checkout wraps errors with %w, so callers can still use errors.Is to check for ErrNotFound, as described in wrapping errors. Third, the lines var _ OrderRepository = (*memoryRepo)(nil) cost nothing at run time but turn a forgotten method into a compile error right next to the adapter instead of a surprise in main.

Dependency injection with constructors

"Dependency injection" sounds like a framework feature, but in Go it is just this: a type receives what it needs through its constructor instead of creating it. NewCheckout(orders, notify) is the whole mechanism. There is no container, no reflection and no annotations.

A few habits keep it healthy:

  • Accept interfaces, return structs. The constructor parameters are interfaces (ports); the constructor returns the concrete *Checkout. Callers get everything the type offers and you can still add methods later.
  • Wire everything in one place. The main function (or a function called from it) is the composition root: the only place that knows which concrete adapters exist. Everything else sees interfaces.
  • No globals. A package-level var db *sql.DB makes dependencies invisible. A struct field makes them visible and replaceable.
  • Pass context.Context as the first argument of every port method that might block, as covered in context.

When main grows long, split it into helper functions like buildStorage(cfg) and buildServer(cfg). Tools such as Wire generate this wiring code, but for most programs a hand-written main of 50 lines is clearer than a generator.

Swapping adapters and testing with fakes

The payoff of ports is that you can run the same service against different adapters. The next program uses a second repository, which keeps orders as text lines (a stand-in for a file or key-value store), and a notifier that fails on demand to check that the service reports the failure.

Go Two repositories, one failing notifier, same service

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The service code did not change between the first two runs; only the value passed to it did. The recorder is a fake: a tiny hand-written implementation that remembers what happened so a test can assert on it. Most Go teams prefer hand-written fakes over generated mocks because they are short, readable and never go stale. See table-driven tests for how to run many such cases compactly.

Laying out packages

A common layout for a service that follows these ideas:

TEXT
myapp/
  cmd/myapp/main.go        composition root
  internal/
    checkout/              domain types, rules, service, ports
    sqlstore/              SQL implementation of checkout's ports
    httpapi/               handlers that call checkout.Service
    mailer/                SMTP implementation of the Notifier port

The rule: checkout imports nothing from sqlstore, httpapi or mailer. They import checkout. If you ever see an import cycle, a port is usually declared on the wrong side. Read more about directory structure in project layout.

When not to bother

Architecture costs files and indirection. A 200-line CLI that reads a file and prints a report does not need ports. Add a boundary when you have a real reason: a second implementation, a slow or expensive dependency you want to fake in tests, or a part that changes at a different speed than the rest. Introducing an interface before a second implementation exists is a common over-engineering trap. In Go you can add the interface later, at the moment you need it, without touching the implementations.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In hexagonal architecture, where should the interface for a repository be declared in Go?

    Implicit interface satisfaction lets the consumer declare a small interface with only the methods it calls. The implementation package then does not need to import the consumer or know the interface exists.
  2. 2. What is a composition root?

    The composition root is the only code that knows which concrete types exist. Everything else depends on interfaces, which keeps the rest of the program easy to test and change.
  3. 3. What does the line var _ Notifier = printNotifier{} achieve?

    Assigning to the blank identifier still type-checks the assignment. If a method is missing or has the wrong signature, the build fails at that line instead of at a distant call site.
  4. 4. Which is the best reason to add a port in front of a dependency?

    Constructor injection works with concrete types too. An interface earns its place when a second implementation (a real one, or a test fake) exists or is clearly coming.

Summary

  • Layered architecture separates transport, service and storage; hexagonal architecture goes further and makes the core define the interfaces it needs.
  • A port is a small interface owned by the consumer. An adapter is any type that satisfies it.
  • Dependency injection in Go is passing dependencies to constructors; wire them in one composition root, usually main.
  • Accept interfaces, return structs, avoid package-level globals, and prove adapters satisfy ports with var _ Port = (*Adapter)(nil).
  • Hand-written fakes make tests short and fast. Add boundaries when you have a reason, not by default.

Next: Containerizing and Deploying Go Apps.