https://github.com/jmrashed/rest-api-golang-mongodb
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.
https://github.com/jmrashed/rest-api-golang-mongodb
golang graphql mongodb rest-api
Last synced: about 1 month ago
JSON representation
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.
- Host: GitHub
- URL: https://github.com/jmrashed/rest-api-golang-mongodb
- Owner: jmrashed
- License: mit
- Created: 2023-08-18T10:58:25.000Z (almost 3 years ago)
- Default Branch: main
- Last Pushed: 2025-10-06T03:47:39.000Z (9 months ago)
- Last Synced: 2025-12-11T06:57:44.227Z (6 months ago)
- Topics: golang, graphql, mongodb, rest-api
- Language: Go
- Homepage:
- Size: 40 KB
- Stars: 3
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- Contributing: CONTRIBUTING.md
- Code of conduct: CODE_OF_CONDUCT.md
Awesome Lists containing this project
README
# RESTful API with Go and MongoDB
[](https://www.linkedin.com/in/jmrashed/)
[](https://leetcode.com/u/jmrashed/)
[](https://www.hackerrank.com/profile/jmrashed)
[](mailto:jmrashed@gmail.com)
[](https://wa.me/8801734446514)
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.
## Table of contents
- Project structure
- Features
- Requirements
- Quick start (PowerShell)
- Configuration
- API endpoints
- Project conventions
- Tests
- Contributing
- License & Contact
## Project structure
Top-level layout (important folders):
- `cmd/` - application entrypoint (`main.go`)
- `internal/config/` - configuration loader
- `internal/handler/` - HTTP handlers
- `internal/service/` - business logic
- `internal/repository/` - MongoDB data access
- `internal/router/` - route registration
- `internal/middleware/` - HTTP middleware
- `internal/model/` - domain models
- `internal/util/` - helpers/utilities
- `migrations/` - SQL migration files (if needed for other DBs) and DB seed scripts
- `scripts/` - helper scripts (build, migrate, deploy)
## Features
### Core Features
- RESTful API with proper HTTP status codes
- MongoDB integration with connection pooling
- Layered architecture (handler → service → repository)
- API versioning (/api/v1)
### Authentication & Authorization
- JWT-based authentication
- User registration and login
- Role-based access control (user/admin)
- Password hashing with bcrypt
- Protected routes with middleware
### Data Management
- Input validation with custom validator
- Pagination, sorting, and filtering
- Unique constraints for username and email
- Proper error handling with custom error types
### Security & Performance
- CORS middleware
- Rate limiting per IP
- Request logging
- Standardized API error responses
### Development
- Comprehensive configuration management
- Unit and integration tests
- Docker support
- Makefile for common tasks
## Requirements
- Go 1.20+ (check `go.mod` for exact version)
- A running MongoDB instance (local or cloud)
## Quick start (PowerShell)
1. Clone the repo and change directory:
```powershell
git clone https://github.com/jmrashed/rest-api-golang-mongodb.git .
cd d:\laragon\www\open-sources\html\go\rest-api-golang-mongodb
```
2. Set required environment variable(s) and run the app (example uses local MongoDB):
```powershell
# 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:
```powershell
# 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):
```powershell
# 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.
## Configuration
The application reads configuration from environment variables. Copy `.env.example` to `.env` and adjust values:
```bash
cp .env.example .env
```
### Environment Variables
- `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)
## API Endpoints
The API is versioned and uses `/api/v1` as the base path. Default server runs on `http://localhost:8080`.
### Authentication Endpoints
- `POST /api/v1/auth/register` - Register a new user
- `POST /api/v1/auth/login` - Login user
### User Endpoints (Protected)
- `GET /api/v1/users` - List users with pagination, sorting, and filtering
- `GET /api/v1/users/{id}` - Get user by ID
- `PUT /api/v1/users/{id}` - Update user (own profile or admin)
- `DELETE /api/v1/users/{id}` - Delete user (own profile or admin)
### Admin Only Endpoints
- `POST /api/v1/users` - Create user (admin only)
### Query Parameters for User Listing
- `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)
## Project conventions
- Keep business logic in `internal/service/`.
- Data access and MongoDB queries belong in `internal/repository/`.
- Keep models simple POJOs in `internal/model/`.
## Tests
The project includes unit and integration tests:
```powershell
# 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/...
```
### Test Structure
- `tests/unit/` - Unit tests for individual components
- `tests/integration/` - Integration tests for API endpoints
## Contributing
Contributions are welcome. Please follow the contributor guidelines in `CONTRIBUTING.md` and include tests for new behavior.
## License & Contact
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