A concise, production-oriented starter for building RESTful APIs in Go using MongoDB. This repository demonstrates a clean project layout, layered architecture (handlers, services, repositories), simple middleware, and migration scripts for a MongoDB-backed service.
- Project structure
- Features
- Requirements
- Quick start (PowerShell)
- Configuration
- API endpoints
- Project conventions
- Tests
- Contributing
- License & Contact
Top-level layout (important folders):
cmd/
- application entrypoint (main.go
)internal/config/
- configuration loaderinternal/handler/
- HTTP handlersinternal/service/
- business logicinternal/repository/
- MongoDB data accessinternal/router/
- route registrationinternal/middleware/
- HTTP middlewareinternal/model/
- domain modelsinternal/util/
- helpers/utilitiesmigrations/
- SQL migration files (if needed for other DBs) and DB seed scriptsscripts/
- helper scripts (build, migrate, deploy)
- RESTful API with proper HTTP status codes
- MongoDB integration with connection pooling
- Layered architecture (handler → service → repository)
- API versioning (/api/v1)
- JWT-based authentication
- User registration and login
- Role-based access control (user/admin)
- Password hashing with bcrypt
- Protected routes with middleware
- Input validation with custom validator
- Pagination, sorting, and filtering
- Unique constraints for username and email
- Proper error handling with custom error types
- CORS middleware
- Rate limiting per IP
- Request logging
- Standardized API error responses
- Comprehensive configuration management
- Unit and integration tests
- Docker support
- Makefile for common tasks
- Go 1.20+ (check
go.mod
for exact version) - A running MongoDB instance (local or cloud)
- Clone the repo and change directory:
git clone https://github.com/jmrashed/rest-api-golang-mongodb.git .
cd d:\laragon\www\open-sources\html\go\rest-api-golang-mongodb
- Set required environment variable(s) and run the app (example uses local MongoDB):
# Set the MongoDB connection string (update with your credentials/host)
$env:MONGODB_URL = 'mongodb://localhost:27017'
# Run the server
go run cmd/main.go
Note: The app expects the MONGODB_URL
environment variable to be defined. See internal/config/config.go
for details.
If you prefer to build an executable first:
# Build
go build -o bin/app cmd/main.go
# Run
.\bin\app
If there are migration scripts to apply (check migrations/
), run the provided script (PowerShell example):
# Example migration script (provided by repo)
bash scripts/migrate-db.sh
On Windows you may need WSL or Git Bash to run bash scripts. The scripts/
folder also contains a deploy.sh
and build.sh
for Linux/macOS environments.
The application reads configuration from environment variables. Copy .env.example
to .env
and adjust values:
cp .env.example .env
MONGODB_URL
- MongoDB connection string (default: mongodb://localhost:27017)DB_NAME
- Database name (default: restapi)SERVER_PORT
- Server port (default: 8080)JWT_SECRET
- JWT signing secret (required for production)JWT_EXPIRY
- JWT token expiry duration (default: 24h)RATE_LIMIT
- Rate limit per IP (default: 100)RATE_DURATION
- Rate limit duration (default: 1h)
The API is versioned and uses /api/v1
as the base path. Default server runs on http://localhost:8080
.
POST /api/v1/auth/register
- Register a new userPOST /api/v1/auth/login
- Login user
GET /api/v1/users
- List users with pagination, sorting, and filteringGET /api/v1/users/{id}
- Get user by IDPUT /api/v1/users/{id}
- Update user (own profile or admin)DELETE /api/v1/users/{id}
- Delete user (own profile or admin)
POST /api/v1/users
- Create user (admin only)
page
- Page number (default: 1)limit
- Items per page (default: 10)sort
- Sort field (default: created_at)order
- Sort order: asc/desc (default: desc)username
- Filter by username (partial match)email
- Filter by email (partial match)role
- Filter by role (exact match)
- Keep business logic in
internal/service/
. - Data access and MongoDB queries belong in
internal/repository/
. - Keep models simple POJOs in
internal/model/
.
The project includes unit and integration tests:
# Run all tests
go test ./...
# Run tests with coverage
go test -coverprofile=coverage.out ./...
go tool cover -html=coverage.out
# Run specific test packages
go test ./tests/unit/...
go test ./tests/integration/...
tests/unit/
- Unit tests for individual componentstests/integration/
- Integration tests for API endpoints
Contributions are welcome. Please follow the contributor guidelines in CONTRIBUTING.md
and include tests for new behavior.
This project is available under the MIT License - see the LICENSE
file for details.
Contact / social links:
- LinkedIn: https://www.linkedin.com/in/jmrashed/
- LeetCode: https://leetcode.com/u/jmrashed/
- HackerRank: https://www.hackerrank.com/profile/jmrashed
- Email: jmrashed@gmail.com
- WhatsApp: https://wa.me/8801734446514