Quick Start: 5-Minute Refactor to Ports and Adapters
Dumping SQL queries directly into http.HandlerFunc callbacks is a common shortcut when prototyping. It works initially. But the moment you want to verify pricing calculations or registration flows without spinning up a live PostgreSQL instance, tests grind to a halt.
Alistair Cockburn formalized Hexagonal Architecture (also called Ports and Adapters) to eliminate this coupling. The guiding principle is simple: core business logic must never depend on delivery mechanisms or storage engines. HTTP routers, gRPC transports, and relational databases are external details. Your domain stays pure.
Three core components drive the architecture:
- Core Domain: Pure business entities and domain services.
- Ports: Go interfaces that define inbound application use cases and outbound infrastructure needs.
- Adapters: Concrete implementations such as Chi/Gin route handlers, PostgreSQL repositories, or Kafka producers.
package main
import (
"context"
"errors"
"fmt"
)
// Domain model: Zero third-party dependencies
type User struct {
ID string
Email string
}
// Driven port: Outgoing interface for persistence
type UserRepository interface {
Save(ctx context.Context, user User) error
FindByID(ctx context.Context, id string) (*User, error)
}
// Core domain service: Pure business logic
type UserService struct {
repo UserRepository
}
func NewUserService(repo UserRepository) *UserService {
return &UserService{repo: repo}
}
func (s *UserService) Register(ctx context.Context, id, email string) error {
if email == "" {
return errors.New("email cannot be empty")
}
if err := s.repo.Save(ctx, User{ID: id, Email: email}); err != nil {
return fmt.Errorf("saving user %s: %w", id, err)
}
return nil
}
UserService imports neither net/http nor database/sql. It communicates exclusively through native Go structs and consumer-owned interfaces.
Deep Dive: Decoupling Domain, Storage, and Transport
Organize your repository around functional responsibilities rather than technical layers to avoid circular dependencies in Go.
Project Layout
cmd/
api/
main.go
internal/
core/
domain/
order.go
ports/
ports.go
services/
order_service.go
adapters/
handlers/
http_order.go
storage/
postgres_order.go
1. Defining Domain Entities and Ports
Isolate your domain models inside internal/core/domain/order.go. These structs hold state and sentinel errors without database annotations:
package domain
import "errors"
var ErrOrderNotFound = errors.New("order not found")
type Order struct {
ID string
Amount float64
Status string
}
Define interface contracts inside internal/core/ports/ports.go. These establish boundaries for incoming commands and outbound data access:
package ports
import (
"context"
"myapp/internal/core/domain"
)
// Driven Port: Storage abstraction implemented by database adapters
type OrderRepository interface {
GetByID(ctx context.Context, id string) (*domain.Order, error)
Create(ctx context.Context, order domain.Order) error
}
// Driving Port: Application API exposed to transport adapters (HTTP, gRPC, CLI)
type OrderService interface {
PlaceOrder(ctx context.Context, id string, amount float64) error
FetchOrder(ctx context.Context, id string) (*domain.Order, error)
}
2. Implementing the Domain Service
Business validations run inside internal/core/services/order_service.go. The service coordinates domain logic against the repository port:
package services
import (
"context"
"errors"
"fmt"
"myapp/internal/core/domain"
"myapp/internal/core/ports"
)
type orderService struct {
repo ports.OrderRepository
}
func NewOrderService(repo ports.OrderRepository) ports.OrderService {
return &orderService{repo: repo}
}
func (s *orderService) PlaceOrder(ctx context.Context, id string, amount float64) error {
if amount <= 0 {
return errors.New("order amount must be greater than zero")
}
order := domain.Order{
ID: id,
Amount: amount,
Status: "PENDING",
}
if err := s.repo.Create(ctx, order); err != nil {
return fmt.Errorf("placing order %s: %w", id, err)
}
return nil
}
func (s *orderService) FetchOrder(ctx context.Context, id string) (*domain.Order, error) {
order, err := s.repo.GetByID(ctx, id)
if err != nil {
return nil, fmt.Errorf("fetching order %s: %w", id, err)
}
return order, nil
}
3. Building the Driving HTTP Adapter
Incoming HTTP requests hit internal/adapters/handlers/http_order.go. The handler unmarshals payloads, calls the driving port, and maps domain results to HTTP status codes:
package handlers
import (
"encoding/json"
"net/http"
"myapp/internal/core/ports"
)
type HTTPOrderHandler struct {
service ports.OrderService
}
func NewHTTPOrderHandler(service ports.OrderService) *HTTPOrderHandler {
return &HTTPOrderHandler{service: service}
}
type CreateOrderRequest struct {
ID string `json:"id"`
Amount float64 `json:"amount"`
}
func (h *HTTPOrderHandler) Create(w http.ResponseWriter, r *http.Request) {
var req CreateOrderRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, `{"error":"invalid json payload"}`, http.StatusBadRequest)
return
}
if err := h.service.PlaceOrder(r.Context(), req.ID, req.Amount); err != nil {
http.Error(w, err.Error(), http.StatusUnprocessableEntity)
return
}
w.WriteHeader(http.StatusCreated)
}
4. Constructing the Driven Database Adapter
Storage operations belong in internal/adapters/storage/postgres_order.go. This adapter executes queries and translates SQL driver errors into domain errors:
package storage
import (
"context"
"database/sql"
"errors"
"fmt"
"myapp/internal/core/domain"
"myapp/internal/core/ports"
)
var _ ports.OrderRepository = (*PostgresOrderRepo)(nil)
type PostgresOrderRepo struct {
db *sql.DB
}
func NewPostgresOrderRepo(db *sql.DB) *PostgresOrderRepo {
return &PostgresOrderRepo{db: db}
}
func (r *PostgresOrderRepo) Create(ctx context.Context, order domain.Order) error {
query := `INSERT INTO orders (id, amount, status) VALUES ($1, $2, $3)`
_, err := r.db.ExecContext(ctx, query, order.ID, order.Amount, order.Status)
if err != nil {
return fmt.Errorf("executing order insert: %w", err)
}
return nil
}
func (r *PostgresOrderRepo) GetByID(ctx context.Context, id string) (*domain.Order, error) {
query := `SELECT id, amount, status FROM orders WHERE id = $1`
row := r.db.QueryRowContext(ctx, query, id)
var o domain.Order
if err := row.Scan(&o.ID, &o.Amount, &o.Status); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return nil, domain.ErrOrderNotFound
}
return nil, fmt.Errorf("scanning order row: %w", err)
}
return &o, nil
}
Testing: Microsecond Feedback Loops with In-Memory Mocks
Integration suites relying on Testcontainers often take 25 to 45 seconds just to boot PostgreSQL and apply schema migrations. In contrast, tests written against in-memory port mocks run in under 15 milliseconds for a 500-case suite.
package services_test
import (
"context"
"sync"
"testing"
"myapp/internal/core/domain"
"myapp/internal/core/services"
)
type mockOrderRepo struct {
mu sync.RWMutex
orders map[string]domain.Order
}
func newMockOrderRepo() *mockOrderRepo {
return &mockOrderRepo{orders: make(map[string]domain.Order)}
}
func (m *mockOrderRepo) Create(ctx context.Context, order domain.Order) error {
m.mu.Lock()
defer m.mu.Unlock()
m.orders[order.ID] = order
return nil
}
func (m *mockOrderRepo) GetByID(ctx context.Context, id string) (*domain.Order, error) {
m.mu.RLock()
defer m.mu.RUnlock()
o, exists := m.orders[id]
if !exists {
return nil, domain.ErrOrderNotFound
}
return &o, nil
}
func TestPlaceOrder_ValidAmount(t *testing.T) {
repo := newMockOrderRepo()
svc := services.NewOrderService(repo)
err := svc.PlaceOrder(context.Background(), "ord-101", 49.99)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
stored, err := repo.GetByID(context.Background(), "ord-101")
if err != nil {
t.Fatalf("order not found in repository: %v", err)
}
if stored.Status != "PENDING" {
t.Errorf("want status PENDING, got %q", stored.Status)
}
if stored.Amount != 49.99 {
t.Errorf("want amount 49.99, got %.2f", stored.Amount)
}
}
func TestPlaceOrder_InvalidAmount(t *testing.T) {
repo := newMockOrderRepo()
svc := services.NewOrderService(repo)
err := svc.PlaceOrder(context.Background(), "ord-102", -5.00)
if err == nil {
t.Fatal("expected validation error for negative amount, got nil")
}
}
Run go test -race ./internal/core/... repeatedly during your editing session. You bypass Docker socket leaks, schema teardown delays, and state contamination between tests.
Production Guidelines
- Keep interfaces consumer-centric: In Go, packages should accept interfaces and return structs. Keep domain interfaces focused strictly on methods the service invokes. Avoid bloated 20-method repository interfaces.
- Prevent tag leakage into domain models: Avoid embedding
gorm:"column:..."orbson:"..."tags insideinternal/core/domainstructs. Domain definitions must remain independent of external ORMs or drivers. - Wire dependencies manually in main.go: Avoid heavy reflection-based DI containers. Ten lines of explicit constructor wiring inside
cmd/api/main.goproduce readable compile-time call graphs that standard linters can verify. - Translate errors at driver boundaries: Map
sql.ErrNoRowsor MongoErrNoDocumentstodomain.ErrOrderNotFoundinside the adapter. Your HTTP handler then returns a 404 response without parsing vendor error strings.
