A complete RESTful API for an e-commerce platform built with Go, Gin, and MongoDB. This API provides user authentication, product management, and order processing capabilities.
- User Authentication: Registration, login with JWT tokens
- Product Management: Full CRUD operations for products
- Order Management: Create and manage orders with product validation
- Security: Password hashing, JWT authentication, input validation
- Database: MongoDB integration with proper data models
- Error Handling: Comprehensive error messages and validation
- Go 1.21 or higher
- MongoDB (local or Atlas)
- Git
- A REST API client (Postman, Insomnia, or cURL)
- Docker Desktop installed and running
- Git
-
Clone and setup:
git clone <repository-url> cd EcomBackend
-
Run the Docker setup script:
.\scripts\docker-setup.ps1 -
Start the application:
docker-compose up -d
-
Check the services:
docker-compose ps
-
View logs:
docker-compose logs -f
- API:
http://localhost:8080- Main e-commerce API - MongoDB:
localhost:27017- Database - Mongo Express:
http://localhost:8081- MongoDB admin interface (admin/password123)
# Start services
docker-compose up -d
# Stop services
docker-compose down
# Rebuild and start
docker-compose up -d --build
# View logs
docker-compose logs -f api
# Access container shell
docker-compose exec api sh
# Production deployment
docker-compose -f docker-compose.prod.yml up -d- Go 1.21 or higher
- MongoDB (local or Atlas)
- Git
- Visit Go's official download page
- Download and install the appropriate version for your OS
- Verify installation:
go version
- Download MongoDB Community Server
- Run the installer with these specific settings:
- Choose "Complete" installation type
- In "Service Configuration":
- Check "Install MongoDB as a Service"
- Select "Run service as Network Service user" (recommended)
- Keep "Service Name" as "MongoDB"
- Check "Install MongoDB Compass" if you want a GUI tool
- After installation:
# Windows (PowerShell) - Verify service is running Get-Service MongoDB # If service is not running, start it Start-Service MongoDB # To ensure service starts automatically on boot Set-Service MongoDB -StartupType Automatic
Note: If you accidentally installed MongoDB with Local System account, you can change it:
- Open Services (services.msc)
- Find MongoDB service
- Right-click β Properties
- In "Log On" tab, select "Network Service"
- Click Apply and restart the service
-
Clone the repository:
git clone <repository-url> cd EcomBackend
-
Create
.envfile:MONGODB_URI=mongodb://localhost:27017 DB_NAME=ecommerce JWT_SECRET=<your-generated-secret> PORT=8080Generate JWT Secret (PowerShell):
$jwtSecret = -join ((65..90) + (97..122) + (48..57) | Get-Random -Count 32 | ForEach-Object {[char]$_}) echo $jwtSecret
-
Install dependencies:
go mod tidy
-
Run the application:
go run .
The project includes a PowerShell test script that tests all endpoints:
.\test_api.ps1This script will:
- Register a new user
- Login and get JWT token
- Create a product
- Get all products
- Create an order
- Get user orders
-
Register User:
curl -X POST http://localhost:8080/api/auth/register \ -H "Content-Type: application/json" \ -d '{"email":"test@example.com","password":"test123","name":"Test User","address":"123 Test St"}'
-
Login:
curl -X POST http://localhost:8080/api/auth/login \ -H "Content-Type: application/json" \ -d '{"email":"test@example.com","password":"test123"}'
-
Create Product (with JWT token):
curl -X POST http://localhost:8080/api/products \ -H "Authorization: Bearer <your-jwt-token>" \ -H "Content-Type: application/json" \ -d '{"name":"Test Product","description":"A test product","price":29.99,"stock":100,"category":"Electronics"}'
-
Get Products (public):
curl http://localhost:8080/api/products
-
Create Order (with JWT token):
curl -X POST http://localhost:8080/api/orders \ -H "Authorization: Bearer <your-jwt-token>" \ -H "Content-Type: application/json" \ -d '{"items":[{"product_id":"<product-id>","quantity":2,"price":29.99}]}'
- POST
/api/auth/register - Body:
{ "email": "user@example.com", "password": "password123", "name": "John Doe", "address": "123 Street, City" } - Response: User object (without password)
- Validation:
- Email must be valid format
- Password minimum 6 characters
- Name is required
- Email must be unique
- POST
/api/auth/login - Body:
{ "email": "user@example.com", "password": "password123" } - Response: JWT token
- Validation: Valid email/password combination
- GET
/api/products - Response: Array of product objects
- Authentication: Not required
- GET
/api/products/:id - Response: Single product object
- Authentication: Not required
- POST
/api/products - Headers:
Authorization: Bearer <jwt-token> - Body:
{ "name": "Product Name", "description": "Product Description", "price": 99.99, "stock": 100, "category": "Electronics" } - Validation:
- Name is required
- Price must be > 0
- Stock must be >= 0
- PUT
/api/products/:id - Headers:
Authorization: Bearer <jwt-token> - Body: Same as Create Product
- Validation: Same as Create Product
- DELETE
/api/products/:id - Headers:
Authorization: Bearer <jwt-token> - Response: Success message
- POST
/api/orders - Headers:
Authorization: Bearer <jwt-token> - Body:
{ "items": [ { "product_id": "product_id_here", "quantity": 2, "price": 99.99 } ] } - Validation:
- Product ID must be valid ObjectID
- Product must exist in database
- Quantity must be > 0
- Price must be > 0
- GET
/api/orders - Headers:
Authorization: Bearer <jwt-token> - Response: Array of user's orders
- GET
/api/orders/:id - Headers:
Authorization: Bearer <jwt-token> - Response: Single order object
- Validation: Order must belong to authenticated user
- PUT
/api/orders/:id/status - Headers:
Authorization: Bearer <jwt-token> - Body:
{ "status": "processing" } - Response: Success message
The project includes PowerShell scripts for easy server management:
# Kill any process using port 8080
.\scripts\kill_port.ps1 -Port 8080# Stop the server and clean up processes
.\scripts\stop_server.ps1These scripts are useful when:
- The server didn't shut down properly
- Port conflicts occur
- You need to quickly restart the server
- Multiple instances are running
To use these scripts:
- Open PowerShell
- Navigate to the project directory
- Run the desired script
Note: You might need to set PowerShell execution policy to run scripts:
# Run as administrator
Set-ExecutionPolicy RemoteSigned -Scope CurrentUserIf you see an error like:
server selection error: context deadline exceeded, current topology: { Type: Unknown, Servers: [{ Addr: localhost:27017, Type: Unknown, Last error: dial tcp [::1]:27017: connectex: No connection could be made because the target machine actively refused it. }
Follow these steps:
-
Verify MongoDB is installed and running:
# Windows (PowerShell) Get-Service MongoDB # Start MongoDB if it's not running Start-Service MongoDB
-
If MongoDB is not installed as a service:
- Navigate to MongoDB installation directory (typically
C:\Program Files\MongoDB\Server\[version]\bin) - Run
mongod.exeto start the MongoDB server - Keep this window open while running the application
- Navigate to MongoDB installation directory (typically
-
Alternative: Use MongoDB Atlas (Cloud hosted):
- Create a free account at MongoDB Atlas
- Create a new cluster
- Get your connection string and update MONGODB_URI in .env file
MONGODB_URI=mongodb+srv://<username>:<password>@<cluster-url>/<dbname>
If you see errors related to the .env file:
-
Make sure to create the .env file without BOM (Byte Order Mark):
# PowerShell (correct way to create .env) @' MONGODB_URI=mongodb://localhost:27017 DB_NAME=ecommerce JWT_SECRET=your_generated_secret PORT=8080 '@ | Out-File -Encoding ASCII .env
-
Verify file content:
- Use a text editor that shows hidden characters
- Ensure there are no extra spaces or special characters
- Each line should end with a regular line break
- File should be in ASCII or UTF-8 without BOM
-
Common .env mistakes to avoid:
- Don't use quotes around values
- Don't add spaces around the = sign
- Don't add trailing spaces
- Don't use Windows-style paths with backslashes
-
Port already in use:
listen tcp :8080: bind: address already in use- Change the PORT in .env file
- Or find and stop the process using port 8080
-
Go module issues:
# Clean go module cache go clean -modcache # Regenerate go.sum go mod tidy
-
Permission issues:
- Run your terminal/IDE as administrator
- Check file and directory permissions
- Ensure write access to the project directory
type User struct {
ID primitive.ObjectID `json:"id" bson:"_id,omitempty"`
Email string `json:"email" bson:"email"`
Password string `json:"-" bson:"password"`
Name string `json:"name" bson:"name"`
Address string `json:"address" bson:"address"`
CreatedAt time.Time `json:"created_at" bson:"created_at"`
UpdatedAt time.Time `json:"updated_at" bson:"updated_at"`
}type Product struct {
ID primitive.ObjectID `json:"id" bson:"_id,omitempty"`
Name string `json:"name" bson:"name"`
Description string `json:"description" bson:"description"`
Price float64 `json:"price" bson:"price"`
Stock int `json:"stock" bson:"stock"`
Category string `json:"category" bson:"category"`
CreatedAt time.Time `json:"created_at" bson:"created_at"`
UpdatedAt time.Time `json:"updated_at" bson:"updated_at"`
}type Order struct {
ID primitive.ObjectID `json:"id" bson:"_id,omitempty"`
UserID primitive.ObjectID `json:"user_id" bson:"user_id"`
Items []OrderItem `json:"items" bson:"items"`
Total float64 `json:"total" bson:"total"`
Status string `json:"status" bson:"status"`
CreatedAt time.Time `json:"created_at" bson:"created_at"`
UpdatedAt time.Time `json:"updated_at" bson:"updated_at"`
}For protected endpoints, include the JWT token in the Authorization header:
Authorization: Bearer your_jwt_token_here
The API returns appropriate HTTP status codes and error messages in JSON format:
{
"error": "Error message here"
}- 200: Success
- 201: Created
- 400: Bad Request
- 401: Unauthorized
- 404: Not Found
- 409: Conflict (e.g., duplicate email)
- 500: Internal Server Error
- Password Hashing: All passwords are hashed using bcrypt
- JWT Authentication: Secure token-based authentication
- Input Validation: Comprehensive validation for all inputs
- Protected Routes: Authentication required for sensitive operations
- Data Sanitization: Input trimming and validation
- Use the
.envfile to configure your environment - Keep your JWT token secure and include it in all protected requests
- Monitor MongoDB connection in the console logs
- Check response status codes and error messages for debugging
- Use the provided test script for quick API validation
- Use the server management scripts for easy deployment
The project includes comprehensive Docker support for easy deployment:
Dockerfile- Multi-stage build for the Go applicationdocker-compose.yml- Development environment with MongoDB and Mongo Expressdocker-compose.prod.yml- Production-ready configuration with nginx.dockerignore- Excludes unnecessary files from Docker build
# Development
docker-compose up -d
# Production
docker-compose -f docker-compose.prod.yml up -d
# View logs
docker-compose logs -f
# Stop services
docker-compose down
# Rebuild
docker-compose up -d --build- API:
http://localhost:8080- Main e-commerce API - MongoDB:
localhost:27017- Database with authentication - Mongo Express:
http://localhost:8081- MongoDB admin interface - Nginx (production): Reverse proxy with SSL termination
- Multi-stage Docker builds for smaller images
- Non-root user for security
- Health checks for all services
- Resource limits and reservations
- SSL/TLS termination with nginx
- Rate limiting and security headers
- Persistent MongoDB data storage
For Docker deployment, use the env.example file as a template:
# Copy and customize
cp env.example .env
# Or use environment variables directly
export JWT_SECRET=your_secure_secret
export MONGO_ROOT_PASSWORD=your_secure_passwordEcomBackend/
βββ main.go # Application entry point
βββ routes.go # Route definitions
βββ go.mod # Go module file
βββ .env # Environment variables
βββ env.example # Environment template
βββ .gitignore # Git ignore rules
βββ README.md # This documentation
βββ test_api.ps1 # API test script
βββ Dockerfile # Docker configuration
βββ docker-compose.yml # Development Docker setup
βββ docker-compose.prod.yml # Production Docker setup
βββ .dockerignore # Docker ignore rules
βββ models/ # Data models
β βββ user.go
β βββ product.go
β βββ order.go
βββ handlers/ # Request handlers
β βββ auth.go
β βββ product.go
β βββ order.go
βββ middleware/ # Middleware functions
β βββ auth.go
βββ db/ # Database connection
β βββ mongodb.go
βββ scripts/ # Management scripts
β βββ kill_port.ps1
β βββ stop_server.ps1
β βββ docker-setup.ps1
β βββ init-mongo.js
βββ nginx/ # Nginx configuration
βββ nginx.conf
- Fork the repository
- Create a feature branch
- Make your changes
- Test thoroughly
- Submit a pull request
This project is licensed under the MIT License.