Skip to content

mazhar75/ecommerce

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

134 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸ›’ Ecommerce Platform

A modern e-commerce backend built with Go, following Clean Architecture principles and Domain-Driven Design patterns for scalability and maintainability.

πŸ“Œ Project Status

🚧 Active Development β€” Core authentication ,product management features, shopping cart functionalities are implemented with ongoing enhancements.

✨ Current Features

Implemented βœ…

  • Authentication System: User registration and login with email/password
  • Custom JWT Implementation: From-scratch JWT token generation and validation
  • Product Management: Full CRUD operations for product catalog with PostgreSQL persistence
  • Domain Models: Product, Cart, Order, Payment, Review, and User entities
  • RESTful API: HTTP endpoints with proper routing
  • Middleware Stack: CORS, logging, and custom middleware chain
  • PostgreSQL Storage: Database-backed repositories with migrations
  • Clean Architecture: Separation of concerns across layers
  • Error Handling: Custom AppError type with HTTP status mapping
  • JWT AUTH: JWT token integration in authentication flow, Protected route middleware
  • Shopping Cart: Shopping cart functionalities ( add,edit and delete from cart )

In Progress 🚧

  • Shopping cart functionality
  • Order management system

Planned πŸ“‹

  • Payment processing
  • Product reviews and ratings
  • Input validation and sanitization
  • Unit and integration tests
  • Google Oauth2
  • Rate limiting using redis

πŸš€ Getting Started

Prerequisites

  • Go 1.24.2 or higher
  • PostgreSQL 12+
  • Environment file (.env) with required configurations

Installation

git clone https://github.com/mazhar75/ecommerce.git
cd ecommerce
go mod download

Database Setup

  1. Ensure PostgreSQL is running on your system
  2. Create the database:
CREATE DATABASE ecommerce;
  1. Run migrations to create tables:
# Create tables
psql -U postgres -d ecommerce -f migrations/001_init_schema.up.sql
psql -U postgres -d ecommerce -f migrations/002_init_schema.up.sql

# To rollback (if needed)
psql -U postgres -d ecommerce -f migrations/001_init_schema.down.sql

Configuration

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

SERVICE_NAME=ecommerce
VERSION=1.0.0
PORT=9090
DB_HOST=localhost
DB_PORT=5432
DB_NAME=ecommerce
DB_USER=postgres
DB_PASSWORD=your_password
JWT_SECRET=your jwt secret
//default
REDIS_IP=localhost
REDIS_PORT=6380
REDIS_PASSWORD=""
REDIS_DB=0

Running the Application

go run main.go

The server will start on the configured port (default: 9090).

πŸ”Œ API Endpoints

Authentication Endpoints

Method Endpoint Description Status
POST /auth/register Register new user with email/password βœ… Implemented
POST /auth/login Authenticate user and get token βœ… Implemented

Product Management Endpoints

Method Endpoint Description Status
GET /products Get all products βœ… Implemented
GET /products/{productId} Get product by ID βœ… Implemented
POST /products Create new product βœ… Implemented
PUT /products/{productId} Update existing product βœ… Implemented
DELETE /products/{productId} Delete product βœ… Implemented

Category Management Endpoints

Method Endpoint Description Status
POST /category Create new category βœ… Implemented

Shopping Cart Endpoints

Method Endpoint Description Status
GET /cart/{userId} Get cart with all cart items
POST /cart/{user_id}/add Add a product to the user's cart βœ… Implemented
PATCH /cart/{user_id}/update Update product quantity in the user's cart βœ… Implemented
PATCH /cart/{user_id}/toggle/{product_id} Update product selections in the user's cart βœ… Implemented
DELETE /cart/{user_id}/remove/{product_id} Remove a product from the user's cart βœ… Implemented

Checkout

Method Endpoint Description Status
POST /checkout Create checkout from cart with selected items βœ… Implemented with redis

Order

Method Endpoint Description Status
POST /order/place Place the order βœ… Implemented
POST /order/changestatus Change order status pending to accept to deliver βœ… Implemented

Health Check

Method Endpoint Description Status
GET /health System health check βœ… Implemented

Example API Requests

Register User

curl -X POST http://localhost:9090/auth/register \
  -H "Content-Type: application/json" \
  -d '{
    "name": "John Doe",
    "email": "john@example.com",
    "password": "securepassword",
    "is_varified":false,
    "is_shop_owner":true
  }'

Login User

curl -X POST http://localhost:9090/auth/login \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer <access_token>" \
  -d '{
    "email": "john@example.com",
    "password": "securepassword"
  }'

Create Product

curl -X POST http://localhost:9090/products \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Laptop",
    "description": "High-performance laptop",
    "type": "Electronics",
    "price": 999.99,
    "img_url": "https://example.com/laptop.jpg",
    "category_id": 1
  }'

πŸ—οΈ Architecture

The project follows Clean Architecture with clear separation of concerns:

  • Domain Layer: Core business entities and rules (Product, User, Cart, Order, Payment, Review)
  • Use Case Layer: Application-specific business logic (services and use cases)
  • Adapter Layer: Interface adapters for HTTP handlers and route registration
  • Infrastructure Layer: External frameworks, database implementations, and drivers

Key Architectural Patterns

  • Repository Pattern: Clear interfaces with PostgreSQL implementations
  • Dependency Injection: Constructor-based DI for loose coupling
  • Middleware Chain: Composable middleware with manager pattern
  • Custom Error Handling: AppError type with HTTP status mapping
  • Interface Segregation: Domain interfaces separate from implementations

πŸ“‚ Project Structure

ecommerce/
β”œβ”€β”€ adapter/                      # Interface adapters
β”‚   β”œβ”€β”€ handlers/
β”‚   β”‚   β”œβ”€β”€ auth/                # Authentication handlers
β”‚   β”‚   β”‚   β”œβ”€β”€ handler.go      # Auth handler interface
β”‚   β”‚   β”‚   β”œβ”€β”€ login.go        # Login endpoint
β”‚   β”‚   β”‚   └── register.go     # Registration endpoint
β”‚   β”‚   β”œβ”€β”€ health_handler/      # Health check handler
β”‚   β”‚   β”‚   └── health.go
β”‚   β”‚   └── product_handlers/    # Product HTTP handlers
β”‚   β”‚       β”œβ”€β”€ create_product.go
β”‚   β”‚       β”œβ”€β”€ delete_product.go
β”‚   β”‚       β”œβ”€β”€ get_product.go
β”‚   β”‚       β”œβ”€β”€ get_product_by_id.go
β”‚   β”‚       β”œβ”€β”€ handler.go
β”‚   β”‚       └── update_product.go
β”‚   └── routes/                  # Route interfaces
β”‚       └── global_routes.go     # Route registration interface
β”œβ”€β”€ cmd/                         # Application commands
β”‚   β”œβ”€β”€ router.go                # HTTP route registration
β”‚   └── serve.go                 # Server initialization with DB
β”œβ”€β”€ config/                      # Configuration management
β”‚   β”œβ”€β”€ config.go                # Configuration structure
β”‚   └── loadenv.go               # Environment loader
β”œβ”€β”€ domain/                      # Business entities & interfaces
β”‚   β”œβ”€β”€ cart/
β”‚   β”‚   └── cart.go              # Cart entity (model only)
β”‚   β”œβ”€β”€ health/
β”‚   β”‚   └── health.go            # Health entity
β”‚   β”œβ”€β”€ order/
β”‚   β”‚   └── order.go             # Order entity (model only)
β”‚   β”œβ”€β”€ payment/
β”‚   β”‚   └── payment.go           # Payment entity (model only)
β”‚   β”œβ”€β”€ product/
β”‚   β”‚   └── product.go           # Product & Category entities
β”‚   β”œβ”€β”€ review/
β”‚   β”‚   └── review.go            # Review entity (model only)
β”‚   └── user/
β”‚       └── user.go              # User entity & interfaces
β”œβ”€β”€ drivers/                     # External drivers & utilities
β”‚   β”œβ”€β”€ hash.go                  # SHA-256 password hashing
β”‚   └── jwt.go                   # Custom JWT implementation
β”œβ”€β”€ infra/                       # Infrastructure layer
β”‚   β”œβ”€β”€ memory/                  # In-memory repositories
β”‚   β”‚   └── health_repo.go      # Health repository
β”‚   └── postgresql/              # PostgreSQL integration
β”‚       β”œβ”€β”€ db.go                # Database connection (singleton)
β”‚       β”œβ”€β”€ product_repo.go     # Product repository
β”‚       └── user_repo.go        # User repository
β”œβ”€β”€ middlewares/                 # HTTP middlewares
β”‚   β”œβ”€β”€ cors.go                  # CORS middleware
β”‚   β”œβ”€β”€ logger.go                # Request logging middleware
β”‚   β”œβ”€β”€ manager.go               # Middleware chain manager
β”‚   β”œβ”€β”€ test1.go                 # Test middleware 1
β”‚   └── test2.go                 # Test middleware 2
β”œβ”€β”€ migrations/                  # Database migrations
β”‚   β”œβ”€β”€ 001_init_schema.down.sql # Initial schema rollback
β”‚   └── 001_init_schema.up.sql   # Initial schema setup
β”œβ”€β”€ usecase/                     # Business logic services
β”‚   β”œβ”€β”€ auth_service.go         # Authentication service
β”‚   β”œβ”€β”€ health_service.go       # Health service
β”‚   β”œβ”€β”€ product_service.go      # Product service
β”‚   └── user_service.go         # User service
β”œβ”€β”€ utils/                       # Utility functions
β”‚   └── error.go                 # Custom error types
β”œβ”€β”€ .env                         # Environment variables (not in repo)
β”œβ”€β”€ go.mod                       # Go module file
β”œβ”€β”€ go.sum                       # Go dependencies lock file
β”œβ”€β”€ main.go                      # Application entry point
└── README.md                    # This file

πŸ› οΈ Tech Stack

  • Language: Go 1.24.2
  • Architecture: Clean Architecture / Hexagonal Architecture
  • HTTP Server: net/http (standard library)
  • Database: PostgreSQL 12+
  • Database Driver: lib/pq v1.10.9
  • Authentication: Custom JWT implementation
  • Password Hashing: SHA-256 (to be upgraded to bcrypt)
  • Configuration: Environment-based with godotenv v1.5.1
  • Middleware: Custom middleware chain manager

πŸ”„ Development Roadmap

Phase 1: Foundation βœ… Complete

  • Project structure setup with Clean Architecture
  • Domain models definition (User, Product, Cart, Order, Payment, Review)
  • Full product CRUD operations
  • Middleware implementation (CORS, Logger, Chain Manager)
  • Health check endpoint
  • Route registration interface
  • PostgreSQL database integration
  • Environment configuration
  • Database migrations

Phase 2: Authentication & Authorization (90% Done)

  • User registration with email/password
  • User login endpoint
  • Custom JWT implementation
  • Password hashing (SHA-256)
  • JWT token return in login response
  • Protected route middleware
  • Role-based access control (RBAC)
  • Password reset functionality
  • Email verification

Phase 3: Core E-commerce Features 🚧 In Progress

  • Shopping cart functionality
    • Add/remove items
    • Update quantities
    • Cart persistence
  • Order management system
    • Create orders from cart
    • Order status tracking
    • Order history
  • Payment integration
    • Payment gateway integration
    • Transaction handling
    • Invoice generation
  • Product features
    • Categories management
    • Product search and filtering
    • Inventory tracking
    • Product images handling
  • Reviews and ratings system

Phase 4: Quality & Testing πŸ“‹ Planned

  • Unit tests for all services
  • Integration tests for handlers
  • Repository tests
  • Middleware tests
  • Input validation and sanitization
  • Error handling improvements
  • Request/Response validation

Phase 5: Production Ready πŸ“‹ Planned

  • API documentation (OpenAPI/Swagger)
  • Docker containerization
  • CI/CD pipeline (GitHub Actions)
  • Performance optimization
    • Database query optimization
    • Caching layer (Redis)
    • Rate limiting
  • Security hardening
    • Upgrade to bcrypt for passwords
    • JWT secret from environment
    • HTTPS support
    • Security headers
  • Monitoring and logging
    • Structured logging
    • Metrics collection
    • Health monitoring dashboard

πŸ”’ Security Considerations

Current Security Measures

  • βœ… Parameterized SQL queries (SQL injection protection)
  • βœ… Password hashing before storage
  • βœ… Custom error types to avoid exposing internals
  • βœ… CORS middleware configured

Security Improvements Needed

  • ⚠️ Password Hashing: Using SHA-256, should upgrade to bcrypt
  • ⚠️ CORS: Currently allows all origins (*)
  • ⚠️ Rate Limiting: Not implemented
  • ⚠️ HTTPS: No TLS/SSL configuration

πŸ§ͺ Testing

Currently, the project has no test coverage. Testing implementation is planned for Phase 4.

Planned Test Coverage

  • Unit tests for all business logic services
  • Integration tests for HTTP handlers
  • Repository layer tests
  • Middleware tests
  • End-to-end API tests

To run tests (once implemented):

go test ./...

πŸ“Š Database Schema

Current Tables

Users Table

CREATE TABLE users (
    user_id SERIAL PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    email VARCHAR(255) UNIQUE NOT NULL,
    password VARCHAR(255) NOT NULL,
    is_verified BOOLEAN DEFAULT FALSE,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

Category Table

CREATE TABLE category (
    category_id SERIAL PRIMARY KEY,
    name VARCHAR(100) NOT NULL
);

Product Table

CREATE TABLE product (
    product_id SERIAL PRIMARY KEY,
    category_id INT REFERENCES category(category_id),
    name VARCHAR(100) NOT NULL,
    description VARCHAR(255),
    type VARCHAR(100),
    price FLOAT NOT NULL,
    img_url VARCHAR(255)
);

Cart Table

create TABLE cart(
    cart_id SERIAL PRIMARY KEY,
    user_id INT,
    created_at timestamp DEFAULT NOW(),
    FOREIGN KEY (user_id) REFERENCES users(user_id)
       ON DELETE CASCADE
);

Cart_Items table

create table cart_item(
    cart_item_id SERIAL PRIMARY KEY,
    cart_id INT,
    product_id INT,
    quantity INT,
    created_at timestamp DEFAULT NOW(),
    FOREIGN KEY(cart_id) REFERENCES cart(cart_id)
       ON DELETE CASCADE,
    FOREIGN KEY(product_id) REFERENCES product(product_id)
       ON DELETE CASCADE
);

Inventory table

CREATE TABLE inventory (
    inventory_id SERIAL PRIMARY KEY,
    product_id INT,
    category_id INT,
    quantity INT NOT NULL DEFAULT 0,
    reserved INT NOT NULL DEFAULT 0,
    updated TIMESTAMP DEFAULT NOW(),
    FOREIGN KEY (category_id) REFERENCES category(category_id) ON DELETE CASCADE,
    FOREIGN KEY (product_id) REFERENCES product(product_id) ON DELETE CASCADE
);

Indexes

create index users_mail on users(email);
create index category_id on category(category_id);
create index categoryId_productId on product(product_id,category_id);
create index cart_user on cart(cart_id,user_id);
create index cart_items on cart_item(cart_item_id,cart_id);
create index inventory_query_product_id on inventory(product_id,quantity); 

## πŸ‘₯ Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

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

### Development Guidelines
- Follow Go best practices and conventions
- Maintain Clean Architecture principles
- Add appropriate error handling
- Consider adding tests for new functionality

## πŸ“„ License

This project is currently under development. License will be added upon first release.

## πŸ“ž Contact

For questions or support, please open an issue in the GitHub repository.

About

Fully ecmmorce website. I am using Software Engineering Best Practices to implement this project.

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages