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)
}
- Define your core business logic in a package that depends only on interfaces.
- Create separate packages for infrastructure (database, HTTP) that implement those interfaces.
- Wire the implementations to the core logic in your
main.gousing dependency injection. - Run your application with
go run main.goto execute the wired components.