recipes/hexagonal

Hexagonal Architecture

A Hexagonal Software Architecture in Golang and MongoDB.

A Hexagonal Software Architecture in Golang and MongoDB

Github StackBlitz

This project presents a simple product catalogue microservice to demonstrate the principles of a hexagonal software architecture. The microservice exposes a RESTful API that allows consuming applications to perform CRUD operations on a product catalogue. The microservice is developed in Golang, and the product catalogue data is persisted in a MongoDB repository.

Hexagonal Architecture

Prerequisites

  • Go 1.27 or higher
  • MongoDB
  • Go modules

Setup

  1. Clone the repository:

    git clone https://github.com/gofiber/recipes.git
    cd recipes/hexagonal
  2. Install dependencies:

    go mod tidy
  3. Configure the MongoDB connection in config/config.yaml. The server listens on server.port (default :8080, a bare number such as 8083 works too):

    database:
      url: "your_mongodb_uri"
      db: "your_db_name"
      timeout: 30
    server:
      port: ":8080"

Running the Application

  1. Run the application:

    go run main.go
  2. The server will start on http://localhost:8080.

Endpoints

A product has a code (its identifier), a name and a price.

MethodURLDescription
GET/productsRetrieves all products
GET/products/:codeRetrieves a product by code
POST/productsCreates a new product
PUT/productsUpdates the product with the same code
DELETE/products/:codeDeletes a product

Example Requests

Create a New Product

curl -X POST http://localhost:8080/products -d '{"code": "p-1", "name": "New Product", "price": 100}' -H "Content-Type: application/json"

Get All Products

curl -X GET http://localhost:8080/products

Get Product by Code

curl -X GET http://localhost:8080/products/p-1

Update a Product

curl -X PUT http://localhost:8080/products -d '{"code": "p-1", "name": "Updated Product", "price": 150}' -H "Content-Type: application/json"

Delete a Product

curl -X DELETE http://localhost:8080/products/p-1

Hexagonal Architecture

Hexagonal architecture, also known as ports and adapters architecture, is a design pattern used to create loosely coupled application components that can be easily connected to their software environment by means of ports and adapters. This architecture allows an application to be equally driven by users, programs, automated tests, or batch scripts, and to be developed and tested in isolation from its eventual runtime devices and databases.

Additional Information

For more information on hexagonal architecture, you can refer to the following resources: