How to Implement Hexagonal Architecture in Go

Complete Example

Implement Hexagonal Architecture in Go by defining domain interfaces and injecting concrete infrastructure implementations to decouple business logic from external dependencies.

Hexagonal Architecture in Go is implemented by defining interfaces for your domain logic and injecting concrete implementations via dependency injection, keeping your core business logic independent of external frameworks. Create a domain package with interfaces like UserRepository, then implement them in infrastructure packages (e.g., postgres, redis) and wire them together in your main or handler layer.

// domain/user.go
package domain

type UserRepository interface {
    GetByID(id string) (*User, error)
}

type UserService struct {
    repo UserRepository
}

func NewUserService(repo UserRepository) *UserService {
    return &UserService{repo: repo}
}

func (s *UserService) GetUser(id string) (*User, error) {
    return s.repo.GetByID(id)
}

// infrastructure/postgres/user_repo.go
package postgres

import "your/module/domain"

type PostgresUserRepo struct {
    db *sql.DB
}

func (r *PostgresUserRepo) GetByID(id string) (*domain.User, error) {
    // SQL implementation here
    return nil, nil
}

// main.go
func main() {
    repo := &postgres.PostgresUserRepo{db: db}
    service := domain.NewUserService(repo)
    // Use service
}