Skip to content

About Simple RESTful Service API written in Go using Gin web framework, PostgreSQ, Redis. Proof of concept of implementing Hexagonal Architecture in Go

License

Notifications You must be signed in to change notification settings

TienMinh25/go-hexagonal-architecture

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

19 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Go Hexagonal Architecture

A Simple RESTful Service API written in Go implementing Hexagonal Architecture (Ports and Adapters pattern) using modern Go technologies and best practices.

Architecture Diagram

πŸ—οΈ Architecture Overview

This project demonstrates the implementation of Hexagonal Architecture in Go, also known as the Ports and Adapters pattern. The architecture provides a clear separation of concerns and makes the application highly testable and maintainable.

Key Principles

  • Domain-Driven Design (DDD): Business logic is isolated in the appliation layer
  • Dependency Inversion: High-level modules don't depend on low-level modules
  • Testability: Each layer can be tested in isolation
  • Flexibility: Easy to swap implementations (e.g., database, web framework)

πŸ› οΈ Tech Stack

  • Language: Go 1.21+
  • Web Framework: Gin - Fast HTTP web framework
  • Database: PostgreSQL with native driver
  • Cache: Redis for caching and session management
  • Authentication: PASETO - Secure token-based authentication
  • Configuration: Environment variables with structured config
  • Logging: Structured logging with slog
  • API Documentation: Swagger with gin-swagger
  • Validation: Request validation with go-playground/validator

πŸ“ Project Structure

go-hexagonal-architecture/
β”œβ”€β”€ cmd/
β”‚   └── http/
β”‚       └── main.go              # Application entry point
β”œβ”€β”€ config/                      # Config for application
β”œβ”€β”€ docs/
β”‚   β”œβ”€β”€ architecture.webp       # Architecture diagram
β”‚   └── db.webp                 # Database schema
β”œβ”€β”€ infrastructure/
β”‚   β”‚   β”œβ”€β”€ storage/            # Infrastructure storage
β”‚   β”‚   β”‚   β”œβ”€β”€ postgres/       # Infrastructure postgres
β”‚   β”‚   β”‚   └── redis/          # Infrastructure redis
β”œβ”€β”€ internal/
β”‚   β”œβ”€β”€ application/
β”‚   β”‚   β”œβ”€β”€ domain/              # Domain entities and business rules
β”‚   β”‚   β”‚   β”œβ”€β”€ auth/            # Domain auth
β”‚   β”‚   β”‚   β”œβ”€β”€ category/        # Domain category
β”‚   β”‚   β”‚   β”œβ”€β”€ order/           # Domain order
β”‚   β”‚   β”‚   β”œβ”€β”€ payment/         # Domain payment
β”‚   β”‚   β”‚   β”œβ”€β”€ product/         # Domain product
β”‚   β”‚   β”‚   β”œβ”€β”€ user/            # Domain user
β”‚   β”‚   β”‚   └── error.go         # Domain error
β”‚   β”‚   β”œβ”€β”€ mock/                # Application mock ports/interfaces
β”‚   β”‚   β”œβ”€β”€ port/                # Application ports/interfaces
β”‚   β”‚   β”œβ”€β”€ util/                # Application util
β”‚   β”‚   └── usecase/             # Application services (use cases)
β”‚   β”œβ”€β”€ adapter/
β”‚   β”‚   β”œβ”€β”€ auth/paseto/         # Auth (primary adapter)
β”‚   β”‚   β”œβ”€β”€ handler/http/        # HTTP handlers (primary adapter)
β”‚   β”‚   β”œβ”€β”€ logger/              # Logger util for application
β”‚   β”‚   β”œβ”€β”€ redis/               # Secondary adapater for redis
β”‚   β”‚   └── repository/          # Secondary adapater for postgres
β”‚   β”‚   β”‚   β”œβ”€β”€ model/           # Model in repository
β”‚   β”‚   β”‚   β”œβ”€β”€ *.go             # Repository implementation 
β”œβ”€β”€ docker-compose.yml           # Local development setup
β”œβ”€β”€ Dockerfile                   # Container image
β”œβ”€β”€ .env.example                 # Environment variables template
β”œβ”€β”€ go.mod                       # Go modules
β”œβ”€β”€ go.sum                       # Go modules checksums
β”œβ”€β”€ LICENSE                      
β”œβ”€β”€ Makefile                      
└── README.md                    # This file

πŸš€ Getting Started

Prerequisites

  • Go 1.21 or higher
  • Docker and Docker Compose (for local development)
  • PostgreSQL (if running without Docker)
  • Redis (if running without Docker)

Local Development with Docker

  1. Clone the repository

    git clone https://github.com/TienMinh25/go-hexagonal-architecture.git
    cd go-hexagonal-architecture
  2. Set up environment variables

    cp .env.example .env
    # Edit .env with your configuration
  3. Start services with Docker Compose

    docker-compose up -d
  4. Run the application

    go run cmd/server/main.go

πŸ“Š Database Schema

Database Schema

The database schema includes the core entities and their relationships, designed following DDD principles.

πŸ”Œ API Endpoints

Users

GET    /api/v1/users          # Get all users
GET    /api/v1/users/:id      # Get user by ID
POST   /api/v1/users          # Create new user
PUT    /api/v1/users/:id      # Update user
DELETE /api/v1/users/:id      # Delete user

Example Request

# Create a new user
curl -X POST http://localhost:8080/api/v1/users \
  -H "Content-Type: application/json" \
  -d '{"name": "John Doe", "email": "john@example.com"}'

πŸ§ͺ Testing

The hexagonal architecture makes testing straightforward by allowing each layer to be tested independently.

# Run all tests
go test ./...

# Run tests with coverage
go test -cover ./...

Test Structure

  • Unit Tests: Test individual components in isolation

πŸ›οΈ Architecture Layers

1. Domain Layer (Core)

Contains the business entities and rules. This layer has no dependencies on external frameworks or libraries.

  • Entities: Core business objects
  • Value Objects: Immutable objects that represent concepts
  • Domain Services: Business logic that doesn't belong to a single entity

2. Application Layer (Core)

Contains application-specific business logic and use cases.

  • Services: Application services that orchestrate domain operations
  • Ports: Interfaces that define contracts with the outside world

3. Adapter Layer

Implements the ports defined in the application layer.

  • Primary Adapters: Handle incoming requests (HTTP handlers)
  • Secondary Adapters: Handle outgoing requests (database, external APIs)

4. Infrastructure Layer

Provides technical capabilities that support the higher layers.

  • Configuration: Application configuration management
  • Database: Database connection and setup
  • Logging: Application logging setup

🐳 Docker Support

Build Docker Image

docker build -t go-hexagonal-architecture .

Run with Docker Compose

docker-compose up --build

The docker-compose.yml includes:

  • Application container
  • PostgreSQL database
  • Redis cache
  • pgAdmin (database management)

βš™οΈ Configuration

Environment variables can be set in .env file or as system environment variables:

# Server Configuration
PORT=8080
GIN_MODE=release

# Database Configuration
DATABASE_URL=postgres://username:password@localhost:5432/dbname?sslmode=disable
DB_MAX_OPEN_CONNS=25
DB_MAX_IDLE_CONNS=25
DB_MAX_IDLE_TIME=15m

# Redis Configuration
REDIS_URL=redis://localhost:6379
REDIS_PASSWORD=
REDIS_DB=0

# Logging
LOG_LEVEL=info
LOG_FORMAT=json

πŸš€ Deployment

Production Build

# Build optimized binary
CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o app cmd/server/main.go

# Or use Docker
docker build -t go-hexagonal-architecture:latest .

Deployment Options

  • Container Orchestration: Kubernetes, Docker Swarm
  • Cloud Platforms: AWS ECS, Google Cloud Run, Azure Container Instances
  • Traditional Servers: Linux VPS with reverse proxy (nginx)

🀝 Contributing

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

Code Style

  • Follow Go conventions and best practices
  • Use gofmt for formatting
  • Run golint and go vet before committing
  • Write tests for new features

πŸ“ License

This project is licensed under the Apache License - see the LICENSE file for details.

πŸ™ Acknowledgments

πŸ“š Additional Resources


Built with ❀️ using Go and Hexagonal Architecture principles

About

About Simple RESTful Service API written in Go using Gin web framework, PostgreSQ, Redis. Proof of concept of implementing Hexagonal Architecture in Go

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages