[
β βββ π models/
β β βββ π user.go # π User data models & validation
β β βββ π extended_models.go # π Additional models (posts, comments, files)
β βββ π services/
β β βββ π user_service.go # π€ User business logic
β β βββ π post_service.go # π Post management service
β β βββ π notification_service.go # π Multi-channel notifications
β β βββ π audit_service.go # π Audit logging service
β β βββ π file_service.go # π File management service
β β βββ π email_service.go # π§ Email service
β β βββ π cache_service.go # π Caching service
β β βββ π security_service.go # π Security utilities
β βββ π utils/
β βββ π jwt.go # π« JWT token utilities & validation
β βββ π validation.go # β
Request validation helpers
βββ π pkg/ # π¦ Reusable packages
β βββ π logger/
β βββ π logger.go # π Structured logging utilities
βββ π tests/ # π§ͺ Test files
β βββ π api_test.go # π API integration tests
β βββ π fixtures/ # π Test data
βββ π docs/ # π Documentation
β βββ π swagger.go # π API documentation
βββ π .env # π§ Environment variables (local)
βββ π .env.example # π Environment variables template
βββ π go.mod # π Go module definition & dependencies
βββ π go.sum # π Dependency lock file
βββ π Dockerfile # π³ Docker container definition
βββ π Makefile # π¨ Build automation & development tasks
βββ π .gitignore # π« Git ignore rules
βββ π README.md # π Project documentation (this file)
```greSQL-blue.svg)](https://sqlite.org)
A **production-ready**, enterprise-grade Go backend API with comprehensive authentication, authorization, file management, and audit logging. Built with modern Go technologies including Gin, GORM, Redis, and JWT for maximum performance and security.
## β¨ Features
### π Authentication & Security
- **JWT-based authentication** with secure token generation and validation
- **Role-based access control** (Admin, Moderator, User) with granular permissions
- **Two-factor authentication (2FA)** for enhanced security
- **Password hashing** with bcrypt for maximum security
- **Session management** with Redis backend
- **Account lockout protection** against brute force attacks
- **Security middleware** with rate limiting and CORS protection
- **Audit logging** for all user activities and system events
### ποΈ Database & Storage
- **Multi-database support** (SQLite with pure Go driver, PostgreSQL)
- **GORM ORM** with automatic migrations and relationships
- **Soft deletes** for data integrity and recovery
- **Database seeding** with default admin account
- **Connection pooling** and timeout management
- **Transaction support** for data consistency
- **Cache layer** with Redis for improved performance
### π File Management
- **File upload/download** with validation and security checks
- **Multiple storage backends** (local filesystem, cloud storage ready)
- **File type validation** and size limits
- **Organized file categorization** and metadata tracking
- **Secure file serving** with access control
### π API Features
- **RESTful API design** following OpenAPI/Swagger standards
- **Request validation** with comprehensive error messages
- **Structured logging** with Logrus (JSON/Text formats)
- **Global error handling** middleware with detailed responses
- **CORS support** with configurable origins
- **Rate limiting** to prevent API abuse
- **Health checks** for monitoring and deployment readiness
- **API documentation** with Swagger/OpenAPI
### π§ Advanced Services
- **Notification system** with multiple channels (email, SMS, push)
- **Template engine** for dynamic content generation
- **CRUD service layer** for rapid development
- **User management** with profile customization
- **Post and comment system** with moderation capabilities
- **Email service** with SMTP configuration
- **Background job processing** ready for integration
### ποΈ Architecture & Code Quality
- **Clean architecture** with clear separation of concerns
- **Dependency injection** for testability and maintainability
- **Service layer pattern** for business logic separation
- **Repository pattern** for data access abstraction
- **Middleware pipeline** for request processing
- **Environment-based configuration** management
- **Graceful shutdown** handling for production deployments
- **Comprehensive error handling** with context propagation
- **Binary compilation** for different platforms
## π Project Structure
go_temp/ βββ π cmd/ β βββ π server/ β βββ π main.go # π Application entry point & server setup βββ π internal/ # π Private application code β βββ π config/ β β βββ π config.go # βοΈ Configuration management & env variables β βββ π database/ β β βββ π database.go # ποΈ Database connection, migrations & seeding β βββ π handlers/ β β βββ π router.go # π Route definitions & middleware setup β β βββ π user_handler.go # π€ User HTTP handlers & endpoints β β βββ π health_handler.go # β€οΈ Health check endpoints β βββ π middleware/ β β βββ π auth.go # π Authentication & authorization middleware β β βββ π common.go # π οΈ Common middleware (CORS, logging, security) β βββ π models/ β β βββ π user.go # π Data models, validation & relationships β βββ π services/ β β βββ π user_service.go # πΌ Business logic & data operations β βββ π utils/ β βββ π jwt.go # π« JWT token utilities & validation β βββ π validation.go # β Request validation helpers βββ π pkg/ # π¦ Reusable packages β βββ π logger/ β βββ π logger.go # π Structured logging utilities βββ π configs/ # π Configuration files directory βββ π .env # π§ Environment variables (local) βββ π .env.example # π Environment variables template βββ π go.mod # π Go module definition & dependencies βββ π go.sum # π Dependency lock file βββ π Dockerfile # π³ Docker container definition βββ π Makefile # π¨ Build automation & development tasks βββ π .gitignore # π« Git ignore rules βββ π README.md # π Project documentation (this file)
## π οΈ Technology Stack
| Technology | Purpose | Version |
|------------|---------|---------|
| **Go** | Backend Language | 1.23+ |
| **Gin** | HTTP Web Framework | v1.9.1 |
| **GORM** | ORM Library | v1.30.0 |
| **JWT** | Authentication | v4.5.0 |
| **SQLite** | Database (Pure Go) | v1.11.0 |
| **PostgreSQL** | Production Database | v1.5.4 |
| **Redis** | Caching & Sessions | v9.14.0 |
| **Logrus** | Structured Logging | v1.9.3 |
| **Bcrypt** | Password Hashing | Built-in |
| **Docker** | Containerization | Multi-stage |
| **Swagger** | API Documentation | Built-in |
| **Docker** | Containerization | Any |
## π Getting Started
### π Prerequisites
Before you begin, ensure you have the following installed:
- **Go 1.23 or higher** - [Download here](https://golang.org/dl/)
- **Git** - For cloning the repository
- **PostgreSQL** (optional) - SQLite is used by default
- **Redis** (optional) - For caching and sessions
- **Docker** (optional) - For containerized deployment
### β‘ Quick Start
1. **Clone the repository:**
```bash
git clone https://github.com/chmuhammadasim/Go_Temp.git
cd Go_Temp
- Install dependencies:
go mod download
go mod tidy
- Set up environment:
# Copy the example environment file
cp .env.example .env
# Edit the .env file with your configuration
# The default configuration uses SQLite and works out of the box
- Run the application:
# Using Go directly
go run cmd/server/main.go
# Or using Makefile
make run
# Or build and run
make build
./bin/server
- Verify installation:
# Health check
curl http://localhost:8080/health
# API documentation (if available)
curl http://localhost:8080/api/docs
Create a .env
file based on .env.example
:
# Server Configuration
SERVER_PORT=8080
SERVER_HOST=localhost
# Database Configuration
DB_TYPE=sqlite # or "postgres"
SQLITE_PATH=./app.db # SQLite file path
# JWT Configuration
JWT_SECRET=your-super-secret-jwt-key-change-this-in-production
JWT_EXPIRY=24h
# Logging Configuration
LOG_LEVEL=info # debug, info, warn, error
LOG_FORMAT=json # json or text
# CORS Configuration
CORS_ORIGINS=http://localhost:3000,http://localhost:8080
After the first run, a default admin account is automatically created:
- Email: admin@example.com
- Password: admin123
- Role: admin
http://localhost:8080
Method | Endpoint | Description | Authentication |
---|---|---|---|
GET | /health |
Basic health check | No |
GET | /ready |
Readiness probe | No |
Method | Endpoint | Description | Authentication |
---|---|---|---|
POST | /api/auth/register |
User registration | No |
POST | /api/auth/login |
User login | No |
POST | /api/auth/refresh |
Refresh JWT token | JWT |
POST | /api/auth/logout |
User logout | JWT |
Method | Endpoint | Description | Authentication | Permission |
---|---|---|---|---|
GET | /api/users/profile |
Get current user profile | JWT | User |
PUT | /api/users/profile |
Update current user profile | JWT | User |
GET | /api/users |
List all users | JWT | Admin |
GET | /api/users/:id |
Get user by ID | JWT | Admin/Owner |
PUT | /api/users/:id |
Update user | JWT | Admin/Owner |
DELETE | /api/users/:id |
Delete user | JWT | Admin |
POST | /api/users/:id/change-password |
Change password | JWT | Admin/Owner |
Method | Endpoint | Description | Authentication | Permission |
---|---|---|---|---|
GET | /api/posts |
List all posts | JWT | User |
POST | /api/posts |
Create new post | JWT | User |
GET | /api/posts/:id |
Get post by ID | JWT | User |
PUT | /api/posts/:id |
Update post | JWT | Admin/Owner |
DELETE | /api/posts/:id |
Delete post | JWT | Admin/Owner |
Method | Endpoint | Description | Authentication | Permission |
---|---|---|---|---|
GET | /api/posts/:post_id/comments |
Get post comments | JWT | User |
POST | /api/posts/:post_id/comments |
Create comment | JWT | User |
PUT | /api/comments/:id |
Update comment | JWT | Admin/Owner |
DELETE | /api/comments/:id |
Delete comment | JWT | Admin/Owner |
curl -X POST http://localhost:8080/api/auth/register \
-H "Content-Type: application/json" \
-d '{
"email": "user@example.com",
"username": "newuser",
"password": "securepassword123",
"first_name": "John",
"last_name": "Doe"
}'
curl -X POST http://localhost:8080/api/auth/login \
-H "Content-Type: application/json" \
-d '{
"email": "admin@example.com",
"password": "admin123"
}'
curl -X GET http://localhost:8080/api/users/profile \
-H "Authorization: Bearer YOUR_JWT_TOKEN"
curl -X POST http://localhost:8080/api/posts \
-H "Authorization: Bearer YOUR_JWT_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"title": "My First Post",
"content": "This is the content of my first post",
"published": true
}'
### π§ Configuration Options
The application uses environment variables for configuration. Here are the key settings:
```env
# π Server Configuration
SERVER_PORT=8080 # Port to run the server on
SERVER_HOST=localhost # Host to bind the server to
NODE_ENV=development # Environment (development/production)
## οΏ½ Docker Deployment
### π Quick Docker Setup
1. **Build the Docker image:**
```bash
docker build -t go-backend .
- Run with Docker:
docker run -p 8080:8080 --env-file .env go-backend
- Using Docker Compose (recommended):
# docker-compose.yml
version: '3.8'
services:
api:
build: .
ports:
- "8080:8080"
environment:
- DB_TYPE=postgres
- DB_HOST=db
- DB_NAME=go_backend
- DB_USER=postgres
- DB_PASSWORD=password
depends_on:
- db
- redis
db:
image: postgres:15-alpine
environment:
POSTGRES_DB: go_backend
POSTGRES_USER: postgres
POSTGRES_PASSWORD: password
volumes:
- postgres_data:/var/lib/postgresql/data
ports:
- "5432:5432"
redis:
image: redis:7-alpine
ports:
- "6379:6379"
volumes:
postgres_data:
- Run with Docker Compose:
docker-compose up -d
The project includes a comprehensive Makefile for common tasks:
# Build the application
make build
# Run the application
make run
# Clean build artifacts
make clean
# Install dependencies
make deps
# Run tests
make test
# Run tests with coverage
make test-coverage
# Format code
make fmt
# Run linter
make lint
# Build Docker image
make docker-build
# Run with Docker
make docker-run
The application uses SQLite by default with a pure Go driver (no CGO required):
DB_TYPE=sqlite
SQLITE_PATH=./app.db
For production use with PostgreSQL:
DB_TYPE=postgres
DB_HOST=localhost
DB_PORT=5432
DB_NAME=go_backend
DB_USER=your_user
DB_PASSWORD=your_password
DB_SSL_MODE=disable
Database migrations run automatically on startup. The system creates:
- User tables with roles and permissions
- Post and comment tables with relationships
- Audit logging tables
- File management tables
- Session management tables DB_HOST=localhost DB_PORT=5432 DB_NAME=go_backend DB_USER=your_username DB_PASSWORD=your_password DB_SSL_MODE=disable
3. **Run the application** - it will automatically create tables
## π API Documentation
### π Base URL
### π Public Endpoints
| Method | Endpoint | Description |
|--------|----------|-------------|
| `GET` | `/health` | Health check |
| `GET` | `/ready` | Readiness check |
| `POST` | `/api/v1/auth/register` | Register new user |
## π§ Troubleshooting
### β Common Issues
#### CGO/SQLite Issues
If you encounter CGO-related errors:
```bash
# Error: Binary was compiled with 'CGO_ENABLED=0', go-sqlite3 requires cgo to work
# Solution: The project uses pure Go SQLite driver, ensure you have latest dependencies
go mod tidy
# Error: bind: address already in use
# Solution: Change the port or kill the process using the port
lsof -ti:8080 | xargs kill -9 # Kill process on port 8080
# Or change SERVER_PORT in .env file
# Check database configuration
cat .env | grep DB_
# For SQLite: Ensure write permissions
chmod 755 .
touch app.db
chmod 644 app.db
# For PostgreSQL: Test connection
psql -h localhost -U your_user -d go_backend
# Ensure JWT_SECRET is set and sufficiently long
echo $JWT_SECRET
# Should be at least 32 characters for security
# Health check endpoint
curl http://localhost:8080/health
# Readiness check (for Kubernetes)
curl http://localhost:8080/ready
# Check database connectivity
curl http://localhost:8080/health/db
Enable debug logging in .env
:
LOG_LEVEL=debug
LOG_FORMAT=text
View detailed logs:
go run cmd/server/main.go 2>&1 | tee app.log
- Connection Pooling: Database connection management
- Redis Caching: Session and data caching
- Middleware Optimization: Efficient request processing
- Graceful Shutdown: Clean resource disposal
- Memory Management: Optimized Go garbage collection
- Use Prometheus for metrics collection
- Implement Health checks for load balancers
- Monitor Database performance and query optimization
- Track API response times and error rates
- Set up Log aggregation with ELK stack or similar
We welcome contributions! Please follow these guidelines:
- Fork the repository
- Create a feature branch:
git checkout -b feature/amazing-feature
- Make your changes and add tests
- Run tests and linting:
make test make lint make fmt
- Commit your changes:
git commit -m "Add amazing feature"
- Push to the branch:
git push origin feature/amazing-feature
- Open a Pull Request
- Follow Go best practices and effective Go guidelines
- Write comprehensive tests for new features
- Update documentation for API changes
- Use conventional commits for clear history
- Ensure security best practices in code
When reporting bugs, please include:
- Go version and OS
- Steps to reproduce
- Expected vs actual behavior
- Relevant logs and error messages
- Configuration details (without secrets)
This project is licensed under the MIT License - see the LICENSE file for details.
- Gin Framework - Fast HTTP web framework
- GORM - Fantastic ORM library for Go
- JWT-Go - Go implementation of JSON Web Tokens
- Logrus - Structured logging for Go
- Go Community - For excellent tools and libraries
- GitHub Issues: Create an issue
- Email: chmuhammadasim@gmail.com
- Repository: https://github.com/chmuhammadasim/Go_Temp
β Star this repository if you find it helpful!
Built with β€οΈ by Muhammad Asim
Method | Endpoint | Description |
---|---|---|
GET |
/api/v1/mod/users |
Get all users (view only) |
curl -X POST http://localhost:8080/api/v1/auth/register \
-H "Content-Type: application/json" \
-d '{
"email": "john.doe@example.com",
"username": "johndoe",
"password": "securepassword123",
"first_name": "John",
"last_name": "Doe"
}'
Response:
{
"message": "User registered successfully",
"data": {
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"user": {
"id": 1,
"email": "john.doe@example.com",
"username": "johndoe",
"first_name": "John",
"last_name": "Doe",
"role": "user",
"is_active": true,
"created_at": "2024-01-01T12:00:00Z",
"updated_at": "2024-01-01T12:00:00Z"
}
}
}
curl -X POST http://localhost:8080/api/v1/auth/login \
-H "Content-Type: application/json" \
-d '{
"email": "john.doe@example.com",
"password": "securepassword123"
}'
curl -X GET http://localhost:8080/api/v1/user/profile \
-H "Authorization: Bearer YOUR_JWT_TOKEN"
curl -X GET "http://localhost:8080/api/v1/admin/users?page=1&limit=10" \
-H "Authorization: Bearer ADMIN_JWT_TOKEN"
π Admin
βββ Full system access
βββ User management (CRUD)
βββ System configuration
βββ All moderator permissions
π‘οΈ Moderator
βββ View all users
βββ Content moderation
βββ All user permissions
π€ User
βββ Profile management
βββ Password change
βββ Basic API access
The application automatically creates a default admin account:
- Email:
admin@example.com
- Password:
admin123
- Role:
admin
# Install dependencies
make deps
# Run in development mode
### π§ͺ Testing
```bash
# Run all tests
go test ./...
# Run tests with verbose output
go test -v ./...
# Run tests with coverage
go test -cover ./...
# Generate coverage report
go test -coverprofile=coverage.out ./...
go tool cover -html=coverage.out -o coverage.html
# Build optimized binary
go build -ldflags="-w -s" -o bin/server cmd/server/main.go
# Cross-compile for different platforms
GOOS=linux GOARCH=amd64 go build -o bin/server-linux cmd/server/main.go
GOOS=windows GOARCH=amd64 go build -o bin/server.exe cmd/server/main.go
GOOS=darwin GOARCH=amd64 go build -o bin/server-mac cmd/server/main.go
# Build the Docker image
docker build -t go_temp:latest .
# Run with Docker
docker run -p 8080:8080 --env-file .env go_temp:latest
Create a docker-compose.yml
file:
version: '3.8'
services:
app:
build: .
ports:
- "8080:8080"
environment:
- DB_TYPE=postgres
- DB_HOST=db
- DB_PORT=5432
- DB_NAME=go_backend
- DB_USER=postgres
- DB_PASSWORD=password
depends_on:
- db
db:
image: postgres:15
environment:
- POSTGRES_DB=go_backend
- POSTGRES_USER=postgres
- POSTGRES_PASSWORD=password
ports:
- "5432:5432"
volumes:
- postgres_data:/var/lib/postgresql/data
volumes:
postgres_data:
# Run with Docker Compose
docker-compose up -d
-
π Password Security
- Bcrypt hashing with salt
- Minimum password requirements
- Password change functionality
-
π« JWT Security
- Secure token generation
- Token expiration handling
- Token validation middleware
-
π HTTP Security
- CORS protection with configurable origins
- Security headers (XSS, CSRF, etc.)
- Rate limiting to prevent abuse
- Request size limiting
-
ποΈ Database Security
- SQL injection prevention (GORM)
- Parameterized queries
- Connection security
-
π Input Validation
- Request payload validation
- Data sanitization
- Error message standardization
- Change default credentials in production
- Use strong JWT secrets (minimum 32 characters)
- Enable HTTPS in production
- Configure proper CORS origins
- Monitor and log security events
- Regular dependency updates
- Environment variable protection
# Basic health check
curl http://localhost:8080/health
# Readiness check (includes database)
curl http://localhost:8080/ready
The application provides structured logging with different levels:
{
"level": "info",
"msg": "HTTP Request",
"time": "2024-01-01T12:00:00Z",
"method": "GET",
"path": "/api/v1/user/profile",
"status": 200,
"latency": "2.5ms",
"ip": "127.0.0.1",
"user_agent": "curl/7.68.0"
}
Consider adding:
- Prometheus metrics
- Performance monitoring
- Error rate tracking
- Database connection monitoring
All API endpoints return consistent error responses:
{
"error": "Validation failed",
"errors": {
"email": "Must be a valid email address",
"password": "Must be at least 6 characters long"
}
}
Status Code | Description |
---|---|
200 |
Success |
201 |
Created |
400 |
Bad Request (validation errors) |
401 |
Unauthorized (authentication required) |
403 |
Forbidden (insufficient permissions) |
404 |
Not Found |
429 |
Too Many Requests (rate limited) |
500 |
Internal Server Error |
# ========================================
# π SERVER CONFIGURATION
# ========================================
SERVER_PORT=8080 # HTTP server port
SERVER_HOST=localhost # Server host binding
NODE_ENV=development # Environment mode
# ========================================
# ποΈ DATABASE CONFIGURATION
# ========================================
DB_TYPE=sqlite # Database type (sqlite/postgres)
DB_HOST=localhost # Database host
DB_PORT=5432 # Database port
DB_NAME=go_backend # Database name
DB_USER=your_username # Database username
DB_PASSWORD=your_password # Database password
DB_SSL_MODE=disable # SSL mode (disable/require/verify-full)
SQLITE_PATH=./app.db # SQLite file path
# ========================================
# π JWT CONFIGURATION
# ========================================
JWT_SECRET=your-super-secret-jwt-key-min-32-chars # JWT signing secret
JWT_EXPIRY=24h # Token expiration
# ========================================
# π LOGGING CONFIGURATION
# ========================================
LOG_LEVEL=info # Log level (debug/info/warn/error)
LOG_FORMAT=json # Log format (json/text)
# ========================================
# π CORS CONFIGURATION
# ========================================
CORS_ORIGINS=http://localhost:3000,http://localhost:8080 # Allowed origins
We welcome contributions! Please follow these guidelines:
- Fork the repository
- Clone your fork:
git clone https://github.com/chmuhammadasim/go_temp.git
- Create a feature branch:
git checkout -b feature/amazing-feature
- Code Style: Follow Go conventions and use
gofmt
- Testing: Write tests for new features
- Documentation: Update README and code comments
- Commits: Use conventional commit messages
- Update documentation if needed
- Add tests for new functionality
- Ensure all tests pass
- Create a detailed pull request description
Please include:
- Go version
- Operating system
- Steps to reproduce
- Expected vs actual behavior
- Error logs (if any)
This project is licensed under the MIT License - see the LICENSE file for details.
MIT License
Copyright (c) 2024 Go Backend API
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
- Gin Web Framework - Fast HTTP web framework
- GORM - Fantastic ORM library for Go
- JWT-Go - Go implementation of JSON Web Tokens
- Logrus - Structured logger for Go
- Go Community - For excellent documentation and support
- Documentation: This README and inline code comments
- Issues: GitHub Issues
- Discussions: GitHub Discussions
β Star this repository if you find it helpful! β
Built with β€οΈ using Go