Features β’ Architecture β’ Quick Start β’ API Documentation β’ Deployment
A production-ready RESTful API built with Go, following clean architecture principles and industry best practices. This project showcases professional-grade API development with comprehensive authentication, authorization, CRUD operations, and database management.
- Clean Architecture: Organized in layers (handler β service β repository) for maintainability
- JWT Authentication: Secure token-based authentication with middleware
- PostgreSQL Integration: Robust database operations with GORM
- Docker Ready: Complete containerization with Docker Compose
- API Documentation: Swagger/OpenAPI documentation
- Production Standards: Error handling, logging, CORS, validation
- Task Automation: Makefile and Taskfile for common operations
-
User Management
- User registration with password hashing (bcrypt)
- JWT-based authentication
- User profile management (CRUD operations)
- Soft delete support
-
Product Management
- Create, read, update, delete products
- Product categorization
- User-specific product listings
- Pagination support
-
Security
- JWT token authentication
- Password hashing with bcrypt
- CORS middleware
- Input validation
- SQL injection prevention (GORM)
-
Database
- PostgreSQL with GORM ORM
- Auto-migrations
- Relationship management
- Transaction support
-
Developer Experience
- Swagger API documentation
- Postman collection included
- Docker containerization
- Hot reload in development
- Comprehensive logging
go-rest-api-v2/
βββ main.go # Application entry point
βββ internal/
β βββ config/ # Configuration management
β β βββ config.go
β βββ database/ # Database connection & migrations
β β βββ database.go
β βββ models/ # Domain models
β β βββ user.go
β β βββ product.go
β βββ repository/ # Data access layer
β β βββ user_repository.go
β β βββ product_repository.go
β βββ service/ # Business logic layer
β β βββ auth_service.go
β β βββ user_service.go
β β βββ product_service.go
β βββ handler/ # HTTP handlers (controllers)
β β βββ auth_handler.go
β β βββ user_handler.go
β β βββ product_handler.go
β βββ middleware/ # HTTP middleware
β β βββ auth.go
β β βββ cors.go
β β βββ logger.go
β βββ utils/ # Utility functions
β βββ jwt.go
β βββ response.go
βββ api/ # API documentation & examples
β βββ postman_collection.json
β βββ examples.md
βββ docker-compose.yml # Docker services configuration
βββ Dockerfile # Application container
βββ Taskfile.yml # Task automation
βββ Makefile # Alternative task automation
βββ .env.example # Environment variables template
βββ LICENSE # MIT License
βββ CONTRIBUTING.md # Contribution guidelines
βββ README.md # This file
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β HTTP Clients β
β (Browser, Postman, Mobile App) β
ββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Middleware Layer β
β (CORS, Auth, Logging, Recovery) β
ββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Handler Layer β
β (AuthHandler, UserHandler, ProductHandler) β
ββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Service Layer β
β (Business Logic & Validation) β
ββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Repository Layer β
β (Data Access & ORM) β
ββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β PostgreSQL Database β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
- Dependency Injection: Services and repositories are injected
- Repository Pattern: Abstract data access logic
- Service Layer Pattern: Encapsulate business logic
- Middleware Pattern: Cross-cutting concerns (auth, logging)
- Factory Pattern: Create instances of repositories and services
Before you begin, ensure you have the following installed:
| Tool | Version | Purpose |
|---|---|---|
| Go | 1.23.5+ | Programming language |
| Docker | 20.10+ | Containerization |
| Docker Compose | 2.0+ | Multi-container orchestration |
| PostgreSQL | 16+ | Database (or use Docker) |
| Task | 3.0+ | Task automation (optional) |
| Make | 4.0+ | Build automation (optional) |
-
Clone the repository
git clone https://github.com/botsgalaxy/go-rest-api-v2.git cd go-rest-api-v2 -
Start the application
docker-compose up -d
-
Verify it's running
curl http://localhost:8080/health
You should see:
{ "status": "ok", "message": "Server is running" }
-
Clone the repository
git clone https://github.com/botsgalaxy/go-rest-api-v2.git cd go-rest-api-v2 -
Install dependencies
go mod download
-
Set up environment variables
cp .env.example .env # Edit .env with your database credentials -
Start PostgreSQL (if not using Docker)
# Using Docker for just the database docker run --name postgres -e POSTGRES_PASSWORD=postgres -e POSTGRES_DB=go_rest_api -p 5432:5432 -d postgres:16-alpine -
Run the application
go run main.go
Or using Task/Make:
task dev # or make dev
Create a .env file in the root directory (use .env.example as template):
# Server Configuration
SERVER_HOST=0.0.0.0
SERVER_PORT=8080
GIN_MODE=debug # Use 'release' in production
# Database Configuration
DB_HOST=localhost
DB_PORT=5432
DB_USER=postgres
DB_PASSWORD=postgres
DB_NAME=go_rest_api
DB_SSLMODE=disable
# JWT Configuration
JWT_SECRET=your-super-secret-jwt-key-change-this-in-production
JWT_EXPIRATION=24h
# CORS
CORS_ALLOWED_ORIGINS=http://localhost:3000,http://localhost:8080| Method | Endpoint | Description |
|---|---|---|
| GET | /health |
Health check |
| POST | /api/v1/auth/register |
Register new user |
| POST | /api/v1/auth/login |
Login user |
| GET | /api/v1/products |
Get all products |
| GET | /api/v1/products/:id |
Get product by ID |
| Method | Endpoint | Description |
|---|---|---|
| GET | /api/v1/users/profile |
Get current user profile |
| PUT | /api/v1/users/profile |
Update current user profile |
| GET | /api/v1/users |
Get all users |
| GET | /api/v1/users/:id |
Get user by ID |
| DELETE | /api/v1/users/:id |
Delete user |
| POST | /api/v1/products |
Create product |
| GET | /api/v1/products/my |
Get user's products |
| PUT | /api/v1/products/:id |
Update product |
| DELETE | /api/v1/products/:id |
Delete product |
curl -X POST http://localhost:8080/api/v1/auth/register \
-H "Content-Type: application/json" \
-d '{
"email": "john.doe@example.com",
"username": "johndoe",
"password": "password123",
"first_name": "John",
"last_name": "Doe"
}'curl -X POST http://localhost:8080/api/v1/auth/login \
-H "Content-Type: application/json" \
-d '{
"email": "john.doe@example.com",
"password": "password123"
}'Response:
{
"success": true,
"message": "Login successful",
"data": {
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"user": { ... }
}
}curl -X POST http://localhost:8080/api/v1/products \
-H "Authorization: Bearer YOUR_JWT_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"name": "Laptop",
"description": "High-performance laptop",
"price": 1299.99,
"stock": 50,
"category": "Electronics",
"sku": "LAP-001"
}'Import the Postman collection from api/postman_collection.json for a complete set of pre-configured requests.
For detailed examples, see api/examples.md
# View all available tasks
task --list
# Install dependencies
task install
# Run in development mode
task dev
# Build the application
task build
# Run tests
task test
# Docker operations
task docker-up
task docker-down
task docker-logs# View all available commands
make help
# Run in development mode
make dev
# Build the application
make build
# Run tests
make test
# Docker operations
make docker-up
make docker-down-
Build and start containers
docker-compose up -d
-
View logs
docker-compose logs -f
-
Stop containers
docker-compose down
- Change
JWT_SECRETto a strong random value - Set
GIN_MODE=release - Enable SSL/TLS for database connections
- Set up proper logging and monitoring
- Configure reverse proxy (Nginx/Traefik)
- Set up CI/CD pipeline
- Enable database backups
- Configure rate limiting
- Set up health checks and alerts
# Run all tests
go test -v ./...
# Run tests with coverage
go test -v -coverprofile=coverage.out ./...
go tool cover -html=coverage.out -o coverage.html- Start the server
- Import Postman collection from
api/postman_collection.json - Follow the request order: Register β Login β Use Token for other endpoints
| Column | Type | Constraints |
|---|---|---|
| id | SERIAL | PRIMARY KEY |
| VARCHAR | UNIQUE, NOT NULL | |
| username | VARCHAR | UNIQUE, NOT NULL |
| password | VARCHAR | NOT NULL (hashed) |
| first_name | VARCHAR | |
| last_name | VARCHAR | |
| role | VARCHAR | DEFAULT 'user' |
| is_active | BOOLEAN | DEFAULT true |
| created_at | TIMESTAMP | |
| updated_at | TIMESTAMP | |
| deleted_at | TIMESTAMP | Soft delete |
| Column | Type | Constraints |
|---|---|---|
| id | SERIAL | PRIMARY KEY |
| name | VARCHAR | NOT NULL |
| description | TEXT | |
| price | DECIMAL | NOT NULL |
| stock | INTEGER | DEFAULT 0 |
| category | VARCHAR | |
| sku | VARCHAR | UNIQUE |
| user_id | INTEGER | FOREIGN KEY β users(id) |
| created_at | TIMESTAMP | |
| updated_at | TIMESTAMP | |
| deleted_at | TIMESTAMP | Soft delete |
- Password Hashing: bcrypt with salt
- JWT Authentication: Secure token-based auth
- CORS Protection: Configurable origins
- SQL Injection Prevention: GORM parameterized queries
- Input Validation: Gin binding validation
- Error Handling: No sensitive data exposure
- Soft Delete: Data retention for auditing
Contributions are welcome! Please follow these steps:
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
# Check if PostgreSQL is running
docker ps | grep postgres
# View database logs
docker-compose logs postgres
# Connect to database
docker-compose exec postgres psql -U postgres -d go_rest_api# Find process using port 8080
lsof -i :8080 # macOS/Linux
netstat -ano | findstr :8080 # Windows
# Kill the process or change SERVER_PORT in .env- Database Indexing: Indexes on email, username, SKU for fast lookups
- Connection Pooling: GORM handles connection pooling
- Pagination: Implemented for list endpoints
- Lazy Loading: Relations loaded only when needed
- Add comprehensive unit tests
- Implement rate limiting middleware
- Add Redis caching layer
- Implement refresh tokens
- Add email verification
- Integrate with cloud storage for files
- Add GraphQL support
- Implement WebSocket support
- Add metrics and monitoring (Prometheus)
- CI/CD pipeline with GitHub Actions
This project is licensed under the MIT License - see the LICENSE file for details.
- π± Telegram: @primeakash
- πΌ LinkedIn: Nasir Hossain Akash
- π Website: BotsGalaxy.com
- π§ Email: admin@botsgalaxy.com
If you found this project helpful, please give it a β
Made with β€οΈ using Go by Nasir Hossain Akash