A modern e-commerce backend built with Go, following Clean Architecture principles and Domain-Driven Design patterns for scalability and maintainability.
π§ Active Development β Core authentication ,product management features, shopping cart functionalities are implemented with ongoing enhancements.
- 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 )
- Shopping cart functionality
- Order management system
- Payment processing
- Product reviews and ratings
- Input validation and sanitization
- Unit and integration tests
- Google Oauth2
- Rate limiting using redis
- Go 1.24.2 or higher
- PostgreSQL 12+
- Environment file (.env) with required configurations
git clone https://github.com/mazhar75/ecommerce.git
cd ecommerce
go mod download- Ensure PostgreSQL is running on your system
- Create the database:
CREATE DATABASE ecommerce;- 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.sqlCreate 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=0go run main.goThe server will start on the configured port (default: 9090).
| Method | Endpoint | Description | Status |
|---|---|---|---|
| POST | /auth/register |
Register new user with email/password | β Implemented |
| POST | /auth/login |
Authenticate user and get token | β Implemented |
| 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 |
| Method | Endpoint | Description | Status |
|---|---|---|---|
| POST | /category |
Create new category | β Implemented |
| 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 |
| Method | Endpoint | Description | Status |
|---|---|---|---|
| POST | /checkout |
Create checkout from cart with selected items | β Implemented with redis |
| Method | Endpoint | Description | Status |
|---|---|---|---|
| POST | /order/place |
Place the order | β Implemented |
| POST | /order/changestatus |
Change order status pending to accept to deliver | β Implemented |
| Method | Endpoint | Description | Status |
|---|---|---|---|
| GET | /health |
System health check | β Implemented |
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
}'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"
}'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
}'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
- 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
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
- 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
- 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
- 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
- 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
- Unit tests for all services
- Integration tests for handlers
- Repository tests
- Middleware tests
- Input validation and sanitization
- Error handling improvements
- Request/Response validation
- 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
- β Parameterized SQL queries (SQL injection protection)
- β Password hashing before storage
- β Custom error types to avoid exposing internals
- β CORS middleware configured
β οΈ Password Hashing: Using SHA-256, should upgrade to bcryptβ οΈ CORS: Currently allows all origins (*)β οΈ Rate Limiting: Not implementedβ οΈ HTTPS: No TLS/SSL configuration
Currently, the project has no test coverage. Testing implementation is planned for Phase 4.
- 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 ./...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
);CREATE TABLE category (
category_id SERIAL PRIMARY KEY,
name VARCHAR(100) NOT NULL
);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)
);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
);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
);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
);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.