Skip to content

lucas54neves/api-in-go

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

api-in-go

A RESTful API built in Go using the Container Pattern (Dependency Injection) for clean architecture and maintainability.

Overview

This project demonstrates a well-structured Go API following clean architecture principles with a layered approach:

  • Handlers: HTTP request/response handling
  • Services: Business logic and validation
  • Repositories: Data access layer
  • Database: PostgreSQL using GORM

Architecture

The project uses the Container Pattern for dependency injection, ensuring loose coupling and testability.

graph TD
    Entrypoint[Entrypoint] --> Handlers[Handlers]
    Handlers --> Services[Services]
    Services --> Repositories[Repositories]
    Repositories --> DB[(DB)]
    
    Services --> ServicesDetail
    Repositories --> RepositoriesDetail
    
    subgraph ServicesDetail["Services"]
        direction LR
        S1[Installment Service<br/>Business Logic]
    end
    
    subgraph RepositoriesDetail["Repositories"]
        direction LR
        R1[Installment Repository<br/>Data Access]
    end
Loading

Architecture Layers

  1. Entrypoint (cmd/api/main.go): Application bootstrap, database connection, and server initialization
  2. Handlers: HTTP layer that receives requests, validates input, and returns responses
  3. Services: Business logic layer that contains validation rules and orchestrates operations
  4. Repositories: Data access layer that interacts with the database
  5. Interfaces: Contract definitions for services and repositories (enables dependency injection)

Project Structure

api-in-go/
├── cmd/
│   └── api/
│       └── main.go              # Application entrypoint
├── src/
│   ├── handlers/                # HTTP handlers
│   │   ├── handlers.go          # Handler container
│   │   └── installment/
│   │       └── installment.go   # Installment endpoints
│   ├── services/                # Business logic
│   │   ├── services.go          # Service container
│   │   └── installment/
│   │       └── service.go       # Installment business logic
│   ├── repositories/            # Data access
│   │   ├── repositories.go      # Repository container
│   │   └── installment/
│   │       └── repository.go    # Installment data access
│   ├── interfaces/              # Contract definitions
│   │   └── installment.go       # Installment interfaces
│   └── structs/                 # Data models
│       ├── installment.go       # Installment model
│       └── response.go          # API response model
├── go.mod                       # Go module definition
├── go.sum                       # Dependency checksums
└── README.md                    # This file

Prerequisites

  • Go 1.25.4 or higher
  • PostgreSQL database
  • Environment variables configured (see Environment Variables section)

Installation

1. Clone the repository

git clone <repository-url>
cd api-in-go

2. Initialize Go module (if not already done)

go mod init github.com/lucas54neves/api-in-go

3. Install dependencies

go mod download

4. Set up environment variables

Create a .env file in the root directory with the following variables:

DB_HOST=localhost
DB_PORT=5432
DB_USER=your_username
DB_PASSWORD=your_password
DB_NAME=your_database_name

Dependencies

The project uses the following main dependencies:

Running the Application

Development

go run cmd/api/main.go

The server will start on port 3001 by default.

Build

go build -o bin/api cmd/api/main.go
./bin/api

API Endpoints

Health Check

GET /health

Returns the API health status.

Response:

{
  "status": "ok",
  "message": "API is running"
}

Installments

Create Installment

POST /installments

Creates a new installment.

Request Body:

{
  "id": "uuid-string",
  "value": 100.50,
  "due_date": 15
}

Success Response (201 Created):

{
  "message": "Installment created successfully"
}

Error Responses:

  • 400 Bad Request: Invalid request body

    {
      "message": "Invalid request body",
      "tag": "BAD_REQUEST"
    }
  • 500 Internal Server Error: Error creating installment

    {
      "message": "Error creating installment",
      "tag": "INTERNAL_SERVER_ERROR"
    }

Business Rules:

  • The due_date must be a valid day of the month (1-31)
  • The due_date cannot be in the past (must be >= current day)

Database

The application uses PostgreSQL with GORM for database operations. The database connection is configured via environment variables.

Auto Migration

The application automatically migrates the Installment model on startup. The Installment struct includes:

  • ID (string): Unique identifier
  • Value (float64): Installment amount
  • DueDate (int): Day of the month when the installment is due

Development

Adding a New Feature

To add a new feature following the project's architecture:

  1. Create the struct in src/structs/
  2. Define interfaces in src/interfaces/
  3. Implement repository in src/repositories/{feature}/
  4. Implement service in src/services/{feature}/
  5. Implement handler in src/handlers/{feature}/
  6. Register in containers:
    • Add to RepositoryContainer in src/repositories/repositories.go
    • Add to ServiceContainer in src/services/services.go
    • Register handler in src/handlers/handlers.go
  7. Update main.go to run auto-migration for new models

Code Style

  • Follow Go naming conventions
  • Use interfaces for dependency injection
  • Keep business logic in services, not handlers
  • Keep data access logic in repositories, not services

License

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

The MIT License is a permissive open-source license that allows:

  • ✅ Commercial use
  • ✅ Modification
  • ✅ Distribution
  • ✅ Private use
  • ✅ Patent use

The only requirement is to include the original copyright notice and license text.

About

API in Go using Container Pattern

Topics

Resources

License

Stars

Watchers

Forks

Languages