How to Implement Hexagonal Architecture (Ports and Adapters) in Go

Implement Hexagonal Architecture in Go by defining domain interfaces and injecting concrete infrastructure implementations at the application boundary.

Implement Hexagonal Architecture in Go by defining interfaces (Ports) for your domain logic and creating concrete implementations (Adapters) for external systems like databases or HTTP handlers.

// Port: Domain interface
type UserRepository interface {
    Save(user User) error
    FindByID(id string) (User, error)
}

// Adapter: Concrete implementation
type PostgresUserRepository struct {
    db *sql.DB
}

func (r *PostgresUserRepository) Save(user User) error {
    // SQL logic here
    return nil
}

// Application uses the Port, not the Adapter
func (s *UserService) CreateUser(user User) error {
    return s.repo.Save(user)
}
  1. Define your core business logic in a package that depends only on interfaces.
  2. Create separate packages for infrastructure (database, HTTP) that implement those interfaces.
  3. Wire the implementations to the core logic in your main.go using dependency injection.
  4. Run your application with go run main.go to execute the wired components.