Hexagonal Architecture trong Go: Tách biệt Domain Logic, Storage và HTTP Handler để Unit Test siêu tốc

Programming tutorial - IT technology blog
Programming tutorial - IT technology blog

Bắt đầu nhanh: Tái cấu trúc sang Ports and Adapters trong 5 phút

Viết trực tiếp các câu truy vấn SQL bên trong callback http.HandlerFunc là lối tắt phổ biến khi làm prototype. Ban đầu thì nó chạy ổn. Nhưng ngay khi bạn muốn kiểm tra logic tính giá hay quy trình đăng ký mà không cần khởi chạy một instance PostgreSQL thực tế, việc viết test sẽ lập tức rơi vào bế tắc.

Alistair Cockburn đã chuẩn hóa kiến trúc Hexagonal Architecture (còn gọi là Ports and Adapters) để triệt tiêu sự phụ thuộc chặt chẽ này. Tương tự như mô hình Clean Architecture, nguyên tắc cốt lõi rất đơn giản: business logic trung tâm tuyệt đối không được phụ thuộc vào phương thức phân phối dữ liệu (delivery mechanism) hay hệ thống lưu trữ (storage engine). HTTP router, gRPC transport và cơ sở dữ liệu quan hệ chỉ là những chi tiết bên ngoài. Domain của bạn phải luôn thuần khiết.

Ba thành phần cốt lõi vận hành kiến trúc này:

  • Core Domain: Các business entity và domain service thuần túy.
  • Ports: Các Go interface định nghĩa những use case đầu vào (inbound) của ứng dụng và nhu cầu cơ sở hạ tầng đầu ra (outbound).
  • Adapters: Các implementation cụ thể như route handler của Chi/Gin, repository PostgreSQL, hoặc Kafka producer.
package main

import (
	"context"
	"errors"
	"fmt"
)

// Domain model: Hoàn toàn không phụ thuộc vào thư viện bên thứ ba
type User struct {
	ID    string
	Email string
}

// Driven port: Interface đầu ra phục vụ lưu trữ dữ liệu
type UserRepository interface {
	Save(ctx context.Context, user User) error
	FindByID(ctx context.Context, id string) (*User, error)
}

// Core domain service: Chứa business logic thuần túy
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 không được để trống")
	}
	if err := s.repo.Save(ctx, User{ID: id, Email: email}); err != nil {
		return fmt.Errorf("lưu người dùng %s thất bại: %w", id, err)
	}
	return nil
}

UserService không hề import net/http hay database/sql. Nó giao tiếp hoàn toàn thông qua các struct Go nguyên bản và interface do phía consumer làm chủ.

Đi sâu vào chi tiết: Tách rời Domain, Storage và Transport

Hãy tổ chức mã nguồn dự án dựa trên trách nhiệm chức năng thay vì các tầng kỹ thuật để tránh circular dependency trong Go, kết hợp cùng kỹ thuật Dependency Injection ở compile-time khi khởi tạo ứng dụng.

Cấu trúc thư mục dự án

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. Định nghĩa Domain Entity và Port

Cô lập các domain model bên trong internal/core/domain/order.go. Các struct này nắm giữ trạng thái và các sentinel error mà không chứa bất kỳ database tag nào:

package domain

import "errors"

var ErrOrderNotFound = errors.New("không tìm thấy đơn hàng")

type Order struct {
	ID     string
	Amount float64
	Status string
}

Định nghĩa các giao ước interface bên trong internal/core/ports/ports.go. Những interface này thiết lập ranh giới cho các command đi vào và việc truy xuất dữ liệu đi ra:

package ports

import (
	"context"
	"myapp/internal/core/domain"
)

// Driven Port: Lớp trừu tượng lưu trữ được triển khai bởi các database adapter
type OrderRepository interface {
	GetByID(ctx context.Context, id string) (*domain.Order, error)
	Create(ctx context.Context, order domain.Order) error
}

// Driving Port: Application API cung cấp cho các transport adapter (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. Triển khai Domain Service

Các validation nghiệp vụ được xử lý bên trong internal/core/services/order_service.go. Service này điều phối domain logic thông qua 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("giá trị đơn hàng phải lớn hơn 0")
	}

	order := domain.Order{
		ID:     id,
		Amount: amount,
		Status: "PENDING",
	}

	if err := s.repo.Create(ctx, order); err != nil {
		return fmt.Errorf("đặt đơn hàng %s thất bại: %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("lấy thông tin đơn hàng %s thất bại: %w", id, err)
	}
	return order, nil
}

3. Xây dựng Driving HTTP Adapter

Các HTTP request gửi đến sẽ đi vào internal/adapters/handlers/http_order.go. Handler này unmarshal payload, gọi driving port và ánh xạ kết quả domain sang HTTP status code tương ứng:

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":"payload json không hợp lệ"}`, 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. Xây dựng Driven Database Adapter

Các thao tác lưu trữ dữ liệu thuộc về internal/adapters/storage/postgres_order.go. Adapter này thực thi truy vấn và chuyển đổi lỗi từ SQL driver sang domain error:

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("thực thi insert đơn hàng thất bại: %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("quét dữ liệu dòng đơn hàng thất bại: %w", err)
	}
	return &o, nil
}

Testing: Vòng lặp phản hồi siêu nhanh với In-Memory Mock

Các bộ integration test phụ thuộc vào Testcontainers thường mất từ 25 đến 45 giây chỉ để khởi động PostgreSQL và chạy migration schema. Ngược lại, các bài test viết trên in-memory port mock chạy chưa tới 15 mili-giây cho một test suite gồm 500 ca kiểm thử.

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("lỗi không mong muốn: %v", err)
	}

	stored, err := repo.GetByID(context.Background(), "ord-101")
	if err != nil {
		t.Fatalf("không tìm thấy đơn hàng trong repository: %v", err)
	}
	if stored.Status != "PENDING" {
		t.Errorf("kỳ vọng trạng thái PENDING, nhận được %q", stored.Status)
	}
	if stored.Amount != 49.99 {
		t.Errorf("kỳ vọng số tiền 49.99, nhận được %.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("kỳ vọng nhận lỗi validation khi số tiền âm, nhưng nhận nil")
	}
}

Hãy chạy go test -race ./internal/core/... liên tục trong suốt quá trình code. Bạn sẽ loại bỏ hoàn toàn tình trạng rò rỉ Docker socket, độ trễ do dọn dẹp schema và nguy cơ nhiễm bẩn dữ liệu giữa các test case.

Kinh nghiệm thực chiến trong Production

  • Thiết kế interface xoay quanh consumer: Trong Go, các package nên nhận vào interface và trả về struct. Giữ cho domain interface chỉ tập trung đúng vào các method mà service thực sự gọi tới. Tránh tạo các repository interface cồng kềnh với 20 method.
  • Tránh rò rỉ tag vào domain model: Không nhúng các tag như gorm:"column:..." hay bson:"..." vào struct trong internal/core/domain. Các định nghĩa domain phải hoàn toàn độc lập với các ORM hay driver bên ngoài.
  • Tự kết nối dependency trong main.go: Tránh dùng các DI container nặng nề dựa trên reflection. Chỉ cần mười dòng code khởi tạo constructor rõ ràng bên trong cmd/api/main.go là đủ để tạo ra một call graph tường minh ngay lúc compile, giúp các linter chuẩn có thể dễ dàng kiểm tra.
  • Chuyển đổi lỗi tại ranh giới của driver: Ánh xạ sql.ErrNoRows hoặc Mongo ErrNoDocuments thành domain.ErrOrderNotFound ngay bên trong adapter. Nhờ đó, HTTP handler có thể trả về status code 404 mà không cần phải phân tích chuỗi lỗi riêng của từng database vendor.
Share: