Lab 09: Microservice Hexagonal

Time: 45 minutes | Level: Advanced | Docker: docker run -it --rm golang:1.22-alpine sh

Overview

Build a production-ready microservice using hexagonal architecture (ports & adapters): pure domain layer, port interfaces, in-memory and SQLite adapters, structured logging with slog, health/readiness endpoints, and graceful shutdown.


Step 1: Hexagonal Architecture Overview

                    ┌─────────────────────────────┐
  HTTP Adapter  ──► │                             │ ──► Repository Port ──► SQLite Adapter
  gRPC Adapter  ──► │     Domain / Application    │                     └── InMemory Adapter
  CLI Adapter   ──► │         (Pure Go)           │ ──► EventPub Port   ──► Kafka Adapter
                    │                             │                     └── NoOp Adapter
                    └─────────────────────────────┘

Port = interface (defined in domain)
Adapter = implementation (in infrastructure)
Domain = zero external dependencies

Step 2: Domain Layer


Step 3: Application Service


Step 4: Adapters


Step 5: HTTP Adapter


Step 6: Graceful Shutdown


Step 7: Structured Logging with slog


Step 8: Capstone — Runnable Service

📸 Verified Output:


Summary

Layer
Responsibility
Dependencies

Domain

Entities, rules, ports

None (pure Go)

Application

Use cases, orchestration

Domain only

Adapters

I/O, DB, HTTP, gRPC

Domain + frameworks

Main

Wire everything

All layers

Key Takeaways:

  • Domain layer has zero external imports — maximally testable

  • Ports (interfaces) are defined in domain, implemented in adapters

  • Dependency injection via constructors (not global state)

  • slog (Go 1.21+) is the standard structured logging package

  • Graceful shutdown: signal.Notifyserver.Shutdown(ctx) with timeout

Last updated