Skip to content

mustaphalimar/carzone

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

27 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

CarZone πŸš—

A modern RESTful API for managing cars and engines built with Go, featuring distributed tracing, JWT authentication, and PostgreSQL database integration.

πŸ“‹ Table of Contents

✨ Features

  • RESTful API for car and engine management
  • JWT Authentication with middleware protection
  • PostgreSQL database integration
  • Distributed Tracing with OpenTelemetry and Jaeger
  • Docker containerization with Docker Compose
  • Clean Architecture with separation of concerns
  • CRUD operations for cars and engines
  • Foreign key relationships between cars and engines
  • Input validation and error handling
  • Automatic database schema initialization

πŸ›  Tech Stack

  • Backend: Go 1.24
  • Database: PostgreSQL
  • Authentication: JWT (JSON Web Tokens)
  • Tracing: OpenTelemetry + Jaeger
  • Containerization: Docker & Docker Compose
  • HTTP Router: Gorilla Mux
  • Database Driver: lib/pq (PostgreSQL driver)

πŸ“ Project Structure

carzone/
β”œβ”€β”€ main.go                 # Application entry point
β”œβ”€β”€ docker-compose.yml      # Docker services configuration
β”œβ”€β”€ Dockerfile             # Application container
β”œβ”€β”€ go.mod                 # Go module dependencies
β”œβ”€β”€ go.sum                 # Go module checksums
β”œβ”€β”€ driver/
β”‚   └── postgres.go        # Database connection
β”œβ”€β”€ handlers/
β”‚   β”œβ”€β”€ auth/
β”‚   β”‚   └── login.go       # Authentication handler
β”‚   β”œβ”€β”€ car/
β”‚   β”‚   └── car.go         # Car CRUD handlers
β”‚   └── engine/
β”‚       └── engine.go      # Engine CRUD handlers
β”œβ”€β”€ middlewares/
β”‚   └── auth.go            # JWT authentication middleware
β”œβ”€β”€ models/
β”‚   β”œβ”€β”€ car.go             # Car model and validation
β”‚   └── engine.go          # Engine model and validation
β”œβ”€β”€ services/
β”‚   β”œβ”€β”€ services.go        # Service interfaces
β”‚   β”œβ”€β”€ car/
β”‚   β”‚   └── car.go         # Car business logic
β”‚   └── engine/
β”‚       └── engine.go      # Engine business logic
└── store/
    β”œβ”€β”€ schema.sql         # Database schema and seed data
    β”œβ”€β”€ store.go           # Store interfaces
    β”œβ”€β”€ car/
    β”‚   └── car.go         # Car data access layer
    └── engine/
        └── engine.go      # Engine data access layer

πŸ“‹ Prerequisites

  • Go 1.24 or higher
  • Docker and Docker Compose
  • PostgreSQL (if running locally without Docker)

πŸš€ Installation

Using Docker (Recommended)

  1. Clone the repository

    git clone https://github.com/mustaphalimar/carzone.git
    cd carzone
  2. Start the services

    docker-compose up -d

    This will start:

    • PostgreSQL database on port 1021
    • CarZone API on port 8080
    • Jaeger tracing UI on port 16686

Local Development

  1. Clone and install dependencies

    git clone https://github.com/mustaphalimar/carzone.git
    cd carzone
    go mod download
  2. Set up environment variables

    cp .env.example .env
    # Edit .env with your configuration
  3. Start PostgreSQL (using Docker)

    docker run --name carzone_db -e POSTGRES_PASSWORD=root -e POSTGRES_DB=postgres -p 1021:5432 -d postgres
  4. Run the application

    go run main.go

βš™οΈ Configuration

Environment Variables

Create a .env file in the root directory:

# Database Configuration
DB_HOST=localhost
DB_PORT=1021
DB_USER=postgres
DB_PASSWORD=root
DB_NAME=postgres

# Application Configuration
PORT=8080

# JWT Configuration (optional)
JWT_SECRET=your-secret-key

# Jaeger Configuration
JAEGER_AGENT_HOST=localhost
JAEGER_AGENT_PORT=4318

Docker Environment

When using Docker Compose, the environment variables are already configured in docker-compose.yml.

πŸ“– Usage

The API will be available at http://localhost:8080

Quick Start

  1. Login to get JWT token

    curl -X POST http://localhost:8080/login \
      -H "Content-Type: application/json" \
      -d '{"username": "admin", "password": "admin123"}'
  2. Use the token for authenticated requests

    curl -X GET http://localhost:8080/cars \
      -H "Authorization: Bearer YOUR_JWT_TOKEN"

πŸ”— API Endpoints

Authentication

Method Endpoint Description Auth Required
POST /login User login ❌

Cars

Method Endpoint Description Auth Required
GET /cars/{id} Get car by ID βœ…
GET /cars Get cars by brand βœ…
POST /cars Create new car βœ…
PUT /cars/{id} Update car βœ…
DELETE /cars/{id} Delete car βœ…

Engines

Method Endpoint Description Auth Required
GET /engines/{id} Get engine by ID βœ…
POST /engines Create new engine βœ…
PUT /engines/{id} Update engine βœ…
DELETE /engines/{id} Delete engine βœ…

API Examples

Create a new engine:

curl -X POST http://localhost:8080/engines \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "displacement": 2000,
    "numOfCylinders": 4,
    "carRange": 600
  }'

Create a new car:

curl -X POST http://localhost:8080/cars \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Toyota Camry",
    "year": "2024",
    "brand": "Toyota",
    "fuelType": "Gasoline",
    "engine": {
      "id": "engine-uuid-here"
    },
    "price": 28000.00
  }'

πŸ” Authentication

The API uses JWT (JSON Web Tokens) for authentication:

  • Default credentials: username: admin, password: admin123
  • Token expiration: 24 hours
  • Header format: Authorization: Bearer <token>

All endpoints except /login require authentication.

πŸ—„οΈ Database Schema

Cars Table

CREATE TABLE cars (
    id UUID PRIMARY KEY,
    name VARCHAR(255) NOT NULL,
    year VARCHAR(4) NOT NULL,
    brand VARCHAR(255) NOT NULL,
    fuel_type VARCHAR(50) NOT NULL,
    engine_id UUID NOT NULL,
    price DECIMAL(10, 2) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (engine_id) REFERENCES engines(id) ON DELETE CASCADE
);

Engines Table

CREATE TABLE engines (
    id UUID PRIMARY KEY,
    displacement INT NOT NULL,
    num_of_cylinders INT NOT NULL,
    car_range INT NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

Sample Data

The application automatically creates sample data:

  • 4 sample engines with different specifications
  • 4 sample cars (Honda Civic, Toyota Corolla, Ford Mustang, BMW 3 Series)

πŸ“Š Monitoring & Tracing

Jaeger Tracing

CarZone includes distributed tracing with OpenTelemetry and Jaeger:

  • Jaeger UI: http://localhost:16686
  • Service name: carzone
  • Automatic instrumentation for HTTP requests and database operations

Traces Include:

  • HTTP request/response cycles
  • Database queries and operations
  • Business logic execution
  • Error tracking and performance metrics

🐳 Docker Deployment

Services

The docker-compose.yml includes:

  1. PostgreSQL Database

    • Image: postgres:latest
    • Port: 1021:5432
    • Volume: postgres_data
  2. CarZone Application

    • Built from Dockerfile
    • Port: 8080:8080
    • Depends on database
  3. Jaeger Tracing

    • Image: jaegertracing/all-in-one:latest
    • UI Port: 16686:16686
    • Agent Port: 4318:4318

Commands

# Start all services
docker-compose up -d

# View logs
docker-compose logs -f app

# Stop services
docker-compose down

# Rebuild and restart
docker-compose up --build -d

πŸ”§ Development

Project Architecture

The project follows Clean Architecture principles:

  1. Handlers - HTTP request/response handling
  2. Services - Business logic implementation
  3. Store - Data access layer
  4. Models - Domain entities and validation
  5. Driver - Database connection management
  6. Middlewares - Cross-cutting concerns (auth, logging)

Adding New Features

  1. Define model in models/
  2. Create store interface and implementation in store/
  3. Implement service logic in services/
  4. Add HTTP handlers in handlers/
  5. Register routes in main.go

Running Tests

# Run all tests
go test ./...

# Run tests with verbose output
go test -v ./...

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

πŸ‘€ Author

Mustapha Limar

πŸ™ Acknowledgments


Happy Coding! πŸš€

About

πŸš— Modern RESTful API for car and engine management with Go, PostgreSQL, JWT auth, OpenTelemetry tracing, and Prometheus metrics.

Topics

Resources

Stars

Watchers

Forks

Releases

Packages

Contributors

Languages