A robust inventory management system built with Go, featuring RESTful APIs, authentication, file uploads, and comprehensive middleware support.
- RESTful API: Clean API design following best practices
- Authentication & Authorization: JWT-based authentication with session management
- File Upload: Secure file upload and storage capabilities
- Middleware Stack: CORS, rate limiting, logging, and authentication middleware
- Database Integration: PostgreSQL with migrations support
- Repository Pattern: Clean architecture with separation of concerns
- Validation: Input validation using go-playground/validator
- Health Checks: Built-in health check endpoint for monitoring
- Go 1.25+: Modern Go with latest features
- Chi Router: Lightweight, fast HTTP router
- PostgreSQL: Primary database
- sqlx: SQL toolkit with enhanced features
- JWT: JSON Web Tokens for authentication
- Validator: go-playground/validator for input validation
- OAuth2: Google OAuth integration
.
├── cmd/
│ └── api/
│ ├── main.go # Application entry point
│ ├── routes.go # Route definitions
│ ├── healthcheck.go # Health check handler
│ ├── items.go # Item handlers
│ └── helpers.go # Helper functions
├── internal/
│ ├── config/ # Configuration management
│ ├── data/ # Data models
│ ├── database/ # Database connection
│ │ └── postgres.go
│ ├── domain/ # Domain models
│ │ ├── error.go
│ │ ├── item.go
│ │ └── user.go
│ ├── dto/ # Data Transfer Objects
│ │ ├── auth_dto.go
│ │ ├── item_dto.go
│ │ └── user_dto.go
│ ├── handler/ # HTTP handlers
│ │ ├── auth_handler.go
│ │ ├── item_handler.go
│ │ ├── upload_handler.go
│ │ └── user_handler.go
│ ├── middleware/ # HTTP middleware
│ │ ├── auth.go
│ │ ├── cors.go
│ │ ├── logger.go
│ │ └── rate_limit.go
│ ├── repository/ # Data access layer
│ │ ├── item_repository.go
│ │ ├── user_repository.go
│ │ └── session_repository.go
│ └── service/ # Business logic layer
│ ├── auth_service.go
│ ├── item_service.go
│ ├── user_service.go
│ └── storage_service.go
├── pkg/
│ ├── jwt/ # JWT utilities
│ ├── utils/ # Utility functions
│ │ └── response.go
│ └── validator/ # Custom validators
├── migrations/ # Database migrations
├── Makefile # Build automation
└── go.mod
- Go 1.25 or higher
- PostgreSQL 12+
- Make (optional, for using Makefile commands)
- Clone the repository:
git clone https://github.com/PaulBabatuyi/BMG-Go-Backend.git
cd BMG-Go-Backend- Install dependencies:
go mod download- Set up environment variables:
cp .env.example .env
# Edit .env with your configuration- Set up the database:
createdb bmginventory- Run migrations:
make migrate-upgo run cmd/api/main.gomake rungo run cmd/api/main.go -port=8080 -env=productionThe server will start on http://localhost:4000 by default.
# Start all services
make docker
# Stop all services
make docker-downGET /v1/healthcheckResponse:
{
"status": "available",
"environment": "development",
"version": "1.0.0"
}POST /v1/items
Content-Type: application/json
{
"name": "Item Name",
"description": "Item Description",
"quantity": 10,
"price": 99.99
}GET /v1/items/{id}(To be implemented)
POST /v1/auth/registerPOST /v1/auth/loginPOST /v1/auth/logout(To be implemented)
GET /v1/users/{id}PUT /v1/users/{id}(To be implemented)
POST /v1/upload
Content-Type: multipart/form-datamake help # Show available commands
make run # Run the application
make build # Build the application binary
make test # Run tests
make migrate-up # Run database migrations up
make migrate-down # Rollback database migrations
make docker # Start Docker services
make docker-down # Stop Docker services
make lint # Run linter
make swagger # Generate Swagger documentationBuild the application binary:
make build
# Output: bin/apiRun the binary:
./bin/api -port=8080Run all tests:
make testRun tests with coverage:
go test -cover ./...Run tests with verbose output:
go test -v ./...migrate create -ext sql -dir internal/database/migrations -seq migration_namemake migrate-upmake migrate-down-port: Server port (default: 4000)-env: Environment (development|staging|production) (default: development)
Create a .env file in the project root:
# Database
DATABASE_URL=postgresql://postgres:password@localhost:5432/bmginventory?sslmode=disable
# Server
PORT=4000
ENVIRONMENT=development
# JWT
JWT_SECRET=your-secret-key
JWT_EXPIRY=24h
# OAuth
GOOGLE_CLIENT_ID=your-client-id
GOOGLE_CLIENT_SECRET=your-client-secret
# Storage
UPLOAD_PATH=./uploads
MAX_UPLOAD_SIZE=10485760 # 10MB in bytesThis project follows a clean architecture pattern with clear separation of concerns:
- Handler Layer (
internal/handler/): HTTP request/response handling - Service Layer (
internal/service/): Business logic - Repository Layer (
internal/repository/): Data access - Domain Layer (
internal/domain/): Core business entities
- Repository Pattern: Abstracts data access logic
- DTO Pattern: Separates external API contracts from internal models
- Middleware Pattern: Reusable HTTP middleware components
- Dependency Injection: Services receive dependencies through constructors
- CORS: Cross-Origin Resource Sharing configuration
- Logger: HTTP request/response logging
- Auth: JWT authentication validation
- Rate Limit: Request rate limiting per IP/user
router := chi.NewRouter()
// Apply middleware
router.Use(middleware.Logger)
router.Use(middleware.RateLimit)
router.Use(middleware.CORS)
// Protected routes
router.Group(func(r chi.Router) {
r.Use(middleware.Auth)
r.Get("/protected", protectedHandler)
})The API uses standard HTTP status codes and returns errors in a consistent format:
{
"error": {
"message": "Error description",
"code": "ERROR_CODE",
"details": {}
}
}200 OK: Success201 Created: Resource created400 Bad Request: Invalid input401 Unauthorized: Authentication required403 Forbidden: Insufficient permissions404 Not Found: Resource not found429 Too Many Requests: Rate limit exceeded500 Internal Server Error: Server error
- JWT Authentication: Secure token-based authentication
- Password Hashing: bcrypt for password storage
- CORS Protection: Configurable CORS policies
- Rate Limiting: Protection against abuse
- Input Validation: Comprehensive validation on all inputs
- SQL Injection Prevention: Parameterized queries via sqlx
- Connection Pooling: Database connection pool management
- Middleware Ordering: Optimized middleware execution order
- Context Usage: Proper context propagation for cancellation
- Timeouts: Configured read/write timeouts
Monitor application health:
curl http://localhost:4000/v1/healthcheckThe application logs all HTTP requests with:
- Method and path
- Status code
- Response time
- Request ID
# Build optimized binary
go build -ldflags="-s -w" -o bin/api cmd/api/main.go
# Run in production
./bin/api -port=8080 -env=productionFROM golang:1.25-alpine AS builder
WORKDIR /app
COPY . .
RUN go build -o api cmd/api/main.go
FROM alpine:latest
COPY --from=builder /app/api /api
EXPOSE 4000
CMD ["/api"]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
- Follow Go best practices and idioms
- Write tests for new features
- Update documentation as needed
- Run
go fmtbefore committing - Run
make lintto check for issues
go test ./internal/...go test -tags=integration ./...- Complete authentication system
- User management endpoints
- File upload functionality
- Admin dashboard
- Email notifications
- Export functionality (CSV, PDF)
- Advanced search and filtering
- Real-time updates with WebSockets
- API documentation with Swagger
- Performance metrics and monitoring
- Caching layer (Redis)
- Background job processing
This project is licensed under the MIT License - see the LICENSE file for details.
For issues, questions, or contributions, please open an issue on GitHub.
- Chi Router for the excellent HTTP router
- sqlx for enhanced SQL capabilities
- validator for input validation
Paul Babatuyi - @PaulBabatuyi
Project Link: https://github.com/PaulBabatuyi/BMG-Go-Backend