Golang Hexagonal Architecture Tutorial and Project Structure

Author

Reads 713

Glass cabinets in white kitchen against modern hallway with fabric bench and wall with hexagonal ornament
Credit: pexels.com, Glass cabinets in white kitchen against modern hallway with fabric bench and wall with hexagonal ornament

Golang's hexagonal architecture is a design pattern that helps you write clean, maintainable, and scalable code. It's a port of the original hexagonal architecture pattern, popularized by Alistair Cockburn.

The core idea behind Golang's hexagonal architecture is to separate the business logic from the infrastructure and presentation layers. This is achieved by using adapters and interfaces.

The project structure for a Golang hexagonal architecture project typically includes a domain layer, an application layer, and an infrastructure layer. The domain layer contains the business logic, while the application layer acts as an interface between the domain and infrastructure layers.

Intriguing read: Golang Programs

Architecture

The Go microservice framework is built on top of Hexagonal Architecture, which divides the application into internal and external parts. This separation of concerns makes it easier to test and maintain the application.

Hexagonal Architecture is also known as Ports and Adapters Architecture, and it's based on the idea of separating the application's core business logic from external stuff like databases and user interfaces. This makes it easier to change the application without breaking it.

Credit: youtube.com, Hexagonal Architecture In Golang!? - Full Structure Example

The main idea behind Hexagonal Architecture is to separate the application's core business logic from external stuff, promoting a clean and modular structure that makes it easier to test, maintain, and scale the application.

Here are the key architectural elements that enforce the Hexagonal Architecture principles:

  • Interface-Implementation Separation:
  • Dependency Inversion:
  • Domain-Centric Design:
  • Clean Boundaries:

Implementation

In a hexagonal architecture, the core is a technology-agnostic component that contains all the business logic.

The core is designed to be independent of the infrastructure, allowing it to be tested in isolation and easily swapped out for different components.

This approach is made possible by structuring the application to adhere to hexagonal architecture principles.

The core is essentially a "box" that can resolve business logic independently of the infrastructure, giving it a high degree of flexibility.

To implement this architecture, you'll need to define the main component and its interactions with external systems.

Having a clear definition of the core component lets you talk about the interactions with external systems, which are referred to as Actors.

Core

Credit: youtube.com, CORE PROGRAM | CORE Architecture, WMC Revision

The core of any application is its business logic, and it's essential to keep it separate from external components. This is where the domain layer comes in, which is the core of the application, containing business logic and rules.

The domain layer is independent of other layers and does not depend on any external components. It's like a "box" that can resolve all business logic independently of the infrastructure.

A key aspect of the core is that it should be technology-agnostic, meaning it shouldn't be aware of how the application is served or where the data is stored. This allows for easier testing and infrastructure changes.

In a hexagonal architecture, everything surrounds the core of the application, which is the central component containing all business logic. This approach enables testing the core in isolation and makes it easier to change infrastructure components.

The core packages should contain main type definitions and functions that define actions that can take place. They can be split into separate packages based on clear domain separation, but ideally, they shouldn't be dependent on each other.

Broaden your view: T Golang

Close-up of JavaScript code on a laptop screen, showcasing programming in progress.
Credit: pexels.com, Close-up of JavaScript code on a laptop screen, showcasing programming in progress.

Here are some key characteristics of a core package:

  • Main type definitions
  • Functions defining actions
  • Can be split based on domain separation
  • Shouldn't be dependent on each other

In a commercial setting, it's unlikely that you'll need to swap out the database easily, so it's often better to write integration tests against the DB instead of mocking it. However, defining interfaces in the core package can be beneficial for testing and flexibility.

Project Structure

In a Go microservice framework based on Hexagonal Architecture and Domain-Driven Design, the project structure is crucial for building maintainable, testable, and scalable applications. The project structure is divided into several directories.

The `bin` directory stores the compiled executable binary. The `docs` directory holds the project's documentation, such as Swagger static files. The `cmd` directory contains the main entry points or commands of the application, with the `http` sub-directory holding the main HTTP server entry point.

The `internal` directory keeps application code that should not be exposed to external packages. The `core` directory contains the central business logic of the application, with four sub-directories: `adapters`, `domain`, `ports`, and `services`.

For your interest: Golang Test Main

Credit: youtube.com, Hexagonal Architecture: What You Need To Know - Simple Explanation

Here's a breakdown of the `core` directory structure:

  • adapters: for containing external services that will interact with the core of the application
  • domain: for containing the application's domain logic
  • ports: for defining the interfaces (ports) that the application will use
  • services: for containing the core components of the application

The `adapters` directory in the `core` directory is particularly important, as it contains the external services that will interact with the core of the application.

Getting Started

To get started with Go, you'll need to ensure you have Go 1.23 or higher installed on your machine. Run the command `go version` to check your Go version.

You'll also need to have Task installed, which you can check by running `task --version`.

Next, create a copy of the `.env.example` file and rename it to `.env` using the command `cp .env.example .env`. Update the configuration values as needed.

This will get you set up with the basic requirements for working with Go.

You might enjoy: Golang Test Command

Error Handling and Logging

Error handling is a crucial aspect of any software development project. With unified error handling, you can expect consistent error types and error wrapping functions.

This means that errors are handled in a standardized way, making it easier to catch and handle errors in your code. You can also use error comparison capabilities for more robust error checking.

Credit: youtube.com, Handling errors LIKE a 10x ENGINEER in Golang - Golang Service Pattern

Structured logging is another important feature that helps with debugging and troubleshooting. By logging contextual information such as request IDs, user IDs, and trace IDs, you can easily identify the source of issues.

This can be particularly useful when debugging complex systems or issues that span multiple components. With consistent log formatting and level management, you can quickly scan through logs to find relevant information.

Here are the key features of unified error handling and structured logging:

Unified Error Handling

Unified error handling is a game-changer for developers. It allows for consistent error types and error wrapping functions, making it easier to manage and troubleshoot issues.

With unified error handling, you can expect extended error handling capabilities. This means you'll have access to structured error details, which can be a huge time-saver when debugging.

One of the key benefits of unified error handling is its support for HTTP status code mapping. This ensures that errors are properly categorized and can be handled accordingly.

Credit: youtube.com, 13. Error handling and logging

Here are some key features of unified error handling:

  • Extended error handling with consistent error types and error wrapping functions
  • Support for structured error details and HTTP status code mapping
  • Error comparison capabilities for more robust error checking

By implementing unified error handling, you can significantly improve the robustness and reliability of your application. This is especially important in high-stakes environments where errors can have serious consequences.

Enhanced Structured Logging

Structured logging is a game-changer for debugging and troubleshooting. It provides context-aware logging with support for request IDs, user IDs, and trace IDs, making it easier to identify and fix issues.

This means that you'll get a clear picture of what's happening in your application, including specific requests and user interactions. Context-aware logging is a must-have for any serious developer.

Consistent log formatting and level management are also essential components of enhanced structured logging. This ensures that your logs are easy to read and understand, even when dealing with complex issues.

With contextual information, you'll be able to quickly pinpoint the root cause of a problem and take corrective action. Improved debugging capabilities are a direct result of structured logging.

Here are some key benefits of enhanced structured logging:

  • Context-aware logging with support for request IDs, user IDs, and trace IDs
  • Consistent log formatting and level management
  • Improved debugging capabilities with contextual information

HTTP Handlers

Credit: youtube.com, Hexgonal Architecture Design Pattern In Go

HTTP handlers in Go are a crucial part of the hexagonal architecture. They allow for flexible and direct service calls, making testing and development easier.

With dual-mode HTTP handlers, you can work with both application layer factories and direct domain services. This flexibility is a game-changer for complex systems.

Here are some key benefits of using dual-mode HTTP handlers:

  • Flexible HTTP handlers that can work with both application layer factories and direct domain services
  • Support for direct service calls in testing and simpler use cases
  • Improved testability with better converter integration for request/response transformations
  • Graceful fallback to application factory mode when direct service mode is not available
  • Enhanced testing capabilities with simplified mock setup

In practice, this means you can easily switch between different modes depending on your needs. For example, you can use direct service calls for testing and simpler use cases, and fall back to application factory mode when needed. This level of flexibility is a major advantage of using dual-mode HTTP handlers.

Explore further: Golang Use Cases

Dependency Management

Dependency Management is a crucial aspect of building a robust and maintainable GoLang Hexagonal architecture. This is achieved through the use of Google Wire for dependency injection.

Google Wire helps organize dependencies in a structured way, making it easier to manage and test different components. It allows us to decide which adapter to plug into each port, depending on our specific needs.

Credit: youtube.com, How To Structure Your Go App - Full Course [ Hex Arch + Tests ]

For instance, if we want to save data into a MySQL database, we can plug in an adapter for a MySQL database into the corresponding port. Conversely, if we want to save data in memory for testing, we can use an "in-memory database" adapter.

This approach enables us to easily switch between different adapters and ports, making our code more flexible and adaptable to changing requirements. By using dependency injection, we can write more modular and maintainable code that's easier to test and extend.

Suggestion: Golang Source

Shutdown and Serve

An application that doesn't handle shutdown gracefully can potentially cause data loss. This is a problem that needs to be addressed.

To avoid data loss, it's essential to implement a graceful shutdown in your application. This means handling shutdown requests in a way that allows your application to clean up and save any necessary data before shutting down.

A graceful shutdown can be achieved by using a solution like the one mentioned in the "5. Graceful Shutdown" section, which involves handling shutdown requests in a way that prevents data loss.

Graceful Shutdown

Credit: youtube.com, Stop Losing Requests! Learn Graceful Shutdown Techniques

A well-planned shutdown is crucial to prevent data loss and ensure a smooth transition.

The application didn't handle shutdown gracefully, potentially causing data loss. This can happen when the system is shut down suddenly, without giving the application a chance to save its data.

A graceful shutdown involves saving any unsaved data and closing any open connections. This is especially important for applications that handle sensitive data or have ongoing processes.

Here are some key considerations for a graceful shutdown:

  • Save any unsaved data to prevent loss
  • Closing any open connections to prevent data corruption

Serve The Application

The final step is to serve the application. We can provide one or several ways for serving this app, each implemented in its own package inside the ./internal/cmd directory.

To serve the application, we need to consider the architecture and structure of the project. The application follows Hexagonal Architecture, with a core containing business logic and ports that interact with adapters.

The adapters bridge the core and external world, including the HTTP adapter that handles incoming HTTP requests. On the right side, there are 2 adapters: the DB adapter connects to PostgreSQL and the Cache adapter works with Redis.

Two men working in a modern office setup, focused on technology and collaboration.
Credit: pexels.com, Two men working in a modern office setup, focused on technology and collaboration.

The directory structure is also important to note, with all core components (services, domain, and ports) placed in the ./internal/core directory. This structure helps keep the project organized and easy to navigate.

To serve the application, we need to consider the entry points for driver adapters and the gateways for the core to interact with driven adapters. This includes the driver port on the left side of the core and the driven ports on the right side.

In our project, the driver actor (Nginx) serves as an HTTP server, while the driven actors (PostgreSQL and Redis) respond to core requests. By understanding the architecture and structure of the project, we can effectively serve the application.

Advantages and Case Studies

The advantages of Golang hexagonal architecture are numerous. Separation of concerns is a key benefit, allowing each component to have a well-defined purpose and reducing confusion about their responsibilities.

Here are some of the key advantages:

  • Separation of concerns: each component (core, adapters, ports, etc) has a well-defined purpose and there is no doubt of their responsibilities.
  • Focus on the business logic: delaying the technical details allows you to focus on what matters at the end, the business logic.
  • Parallelization of work: once the ports are defined, it is easy to parallelize the work across mates.
  • Tests in isolation: each component can be tested in isolation, and more important is that the core is self-tested.
  • Easily change infrastructure: it is really easy to change the infrastructure.
  • Self-guided process: the architecture itself guides you on how the development process steps should be taken.

A case study in the article demonstrates how to implement these concepts in a real project. The project involves registering a new user and saving them to a database, and it uses a hexagonal architecture with a core, adapters, and ports. This approach allows for a clear separation of concerns and makes it easy to test and change the infrastructure.

Advantages

Laptop displaying code in a dark setting, highlighting programming concepts and digital work.
Credit: pexels.com, Laptop displaying code in a dark setting, highlighting programming concepts and digital work.

One of the most significant advantages of this architecture is the separation of concerns, where each component has a well-defined purpose and responsibilities.

This clarity of purpose makes it easy to focus on the business logic, delaying the technical details until later in the development process.

Parallelization of work is also a major benefit, as once the ports are defined, it's easy to divide tasks among team members, reducing development time.

Each component can be tested in isolation, and the core is self-tested, making it easier to catch bugs and errors early on.

Easily changing infrastructure is another advantage, as you can move from one database to another without affecting the business logic.

The architecture itself guides the development process, starting with the core, then the ports and adapters, and finally serving the application.

Here are some of the key advantages of this architecture:

  • Separation of concerns
  • Focus on business logic
  • Parallelization of work
  • Tests in isolation
  • Easily change infrastructure
  • Self-guided process

Minesweeper API Case Study

The Minesweeper API Case Study is a great example of how to implement a hexagonal architecture. This architecture is all about surrounding the core of the application with layers of functionality.

Abstract black and white hexagonal pattern with a 3D geometric design creating a futuristic feel.
Credit: pexels.com, Abstract black and white hexagonal pattern with a 3D geometric design creating a futuristic feel.

The case study focuses on building a simple API for the popular game Minesweeper, with just a few features. The functional requirements are straightforward and easy to understand.

The business logic is the core of the application, and it's where you should start building your API. In this case, the core is implemented using Go, and it's being tested with the help of GoMock.

The Minesweeper API has three main features: "Get a game", "Create a new game", and "Reveal a cell". The "Get a game" feature is the first one to be implemented, and it returns a game associated with a given id.

Here are the functional requirements for the Minesweeper API:

  • Get a game: given an id, it should return the game associated.
  • Create a new game: given a name, a size (N) and the number of bombs (B), it should create and return a new game where its board has NxN cells and B bombs in random positions.
  • Reveal a cell: given a game id and cell position, it should reveal the cell and return the resulted game. If a bomb is found or the last empty cell is revealed then the game is over.

The "Reveal a cell" feature is the last one to be implemented, and it's a bit more complex. You can check out the implementation in the GitHub repository.

The core of the Minesweeper API is being tested with the help of GoMock, which is a great tool for testing Go code.

Dany0814 Go on GitHub

Credit: youtube.com, 037: Hexagonal Architecture - Using Test Driven Development (TDD) to create a REST API (Golang)

Dany0814 Go on GitHub is an interesting project. It's a Go implementation of the hexagonal architecture, which is a design pattern that separates the application's business logic from its infrastructure.

The project is hosted on GitHub, and it's called go-hexagonal. We can see that it's a Go package that provides a basic structure for implementing the hexagonal architecture.

The project includes a MySQL engine setup with specific configuration details, such as using port 3306, DbUser "admin", DbPass "admin", and DbName "admin". This setup is done for didactic purposes, meaning it's an example to illustrate the concept.

The project also includes a dependency schema that shows how the components are connected. Specifically, the Echo Web Server depends on the Adapter, which in turn depends on the Application through a driver port with an interface and a SignInHandler() method.

This is a great example of how the hexagonal architecture can be implemented in Go. It's easy to see how the different components are connected and how they can be swapped out for different implementations, such as using Gin as a web server or PostgreSQL as a database engine.

Here's a summary of the configuration details:

  • MySQL engine setup with port 3306, DbUser "admin", DbPass "admin", and DbName "admin"
  • Dependency schema: Echo Web Server -> Adapter -> Application (Port)
  • Configurable dependencies pattern allows for easy swapping of elements, such as Gin web server or PostgreSQL database engine

Walter Brekke

Lead Writer

Walter Brekke is a seasoned writer with a passion for creating informative and engaging content. With a strong background in technology, Walter has established himself as a go-to expert in the field of cloud storage and collaboration. His articles have been widely read and respected, providing valuable insights and solutions to readers.

Love What You Read? Stay Updated!

Join our community for insights, tips, and more.