{"id":19430708,"url":"https://github.com/jmrashed/golang-rest-api-with-mysql","last_synced_at":"2026-06-13T03:31:59.802Z","repository":{"id":238827341,"uuid":"634623017","full_name":"jmrashed/golang-rest-api-with-mysql","owner":"jmrashed","description":"golang-rest-api-with-mysql","archived":false,"fork":false,"pushed_at":"2025-10-06T04:35:37.000Z","size":386,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-10-06T06:28:02.112Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/jmrashed.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2023-04-30T18:14:32.000Z","updated_at":"2025-10-06T04:35:41.000Z","dependencies_parsed_at":"2024-05-08T11:31:28.899Z","dependency_job_id":"8c398ba5-df86-4460-a6f6-386e3fdb693c","html_url":"https://github.com/jmrashed/golang-rest-api-with-mysql","commit_stats":null,"previous_names":["jmrashed/golang-rest-api-with-mysql","mrzstack/golang-rest-api-with-mysql"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/jmrashed/golang-rest-api-with-mysql","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jmrashed%2Fgolang-rest-api-with-mysql","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jmrashed%2Fgolang-rest-api-with-mysql/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jmrashed%2Fgolang-rest-api-with-mysql/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jmrashed%2Fgolang-rest-api-with-mysql/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/jmrashed","download_url":"https://codeload.github.com/jmrashed/golang-rest-api-with-mysql/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jmrashed%2Fgolang-rest-api-with-mysql/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":34271500,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-26T15:22:16.424Z","status":"online","status_checked_at":"2026-06-13T02:00:06.617Z","response_time":62,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-11-10T14:26:14.968Z","updated_at":"2026-06-13T03:31:59.795Z","avatar_url":"https://github.com/jmrashed.png","language":"Go","funding_links":[],"categories":[],"sub_categories":[],"readme":"# RESTful API in GO with Enhanced Authentication \u0026 Authorization\n\nThis is an advanced Go project featuring a comprehensive authentication and authorization system with JWT tokens, role-based access control (RBAC), and permission-based access control. The API is designed with clean architecture principles and includes extensive testing.\n\n\n\u003c!-- Repository Stats --\u003e\n![GitHub repo size](https://img.shields.io/github/repo-size/jmrashed/golang-rest-api-with-mysql)\n![GitHub stars](https://img.shields.io/github/stars/jmrashed/golang-rest-api-with-mysql?style=social)\n![GitHub forks](https://img.shields.io/github/forks/jmrashed/golang-rest-api-with-mysql?style=social)\n![GitHub issues](https://img.shields.io/github/issues/jmrashed/golang-rest-api-with-mysql)\n![GitHub contributors](https://img.shields.io/github/contributors/jmrashed/golang-rest-api-with-mysql)\n![GitHub last commit](https://img.shields.io/github/last-commit/jmrashed/golang-rest-api-with-mysql)\n![GitHub license](https://img.shields.io/github/license/jmrashed/golang-rest-api-with-mysql)\n\n\u003c!-- Language \u0026 Build --\u003e\n![Go version](https://img.shields.io/github/go-mod/go-version/jmrashed/golang-rest-api-with-mysql)\n![Go Report Card](https://goreportcard.com/badge/github.com/jmrashed/golang-rest-api-with-mysql)\n\n\u003c!-- CI/CD --\u003e\n![GitHub Workflow Status](https://img.shields.io/github/actions/workflow/status/jmrashed/golang-rest-api-with-mysql/go.yml?branch=main)\n![Docker Pulls](https://img.shields.io/docker/pulls/jmrashed/golang-rest-api-with-mysql)\n\n\u003c!-- Code Quality --\u003e\n![Code Coverage](https://img.shields.io/badge/coverage-90%25-brightgreen) \u003c!-- adjust % as per real coverage --\u003e\n![Static Analysis](https://img.shields.io/badge/static%20analysis-passed-brightgreen)\n\n\n## 🚀 Features\n\n### Authentication \u0026 Authorization\n- **JWT-based Authentication**: Stateless authentication with access and refresh tokens\n- **Role-Based Access Control (RBAC)**: Users have roles that determine access levels\n- **Permission-Based Access Control**: Fine-grained permissions for specific actions\n- **Secure Password Hashing**: bcrypt for password security\n- **Token Refresh**: Automatic token renewal without re-authentication\n- **Multi-device Logout**: Support for logging out from all devices\n\n### Security Features\n- **Password Validation**: Strong password requirements\n- **Token Expiration**: Access tokens (15 min), refresh tokens (7 days)\n- **Secure Token Storage**: Hashed refresh tokens in database\n- **Input Validation**: Comprehensive request validation\n- **Error Handling**: Structured error responses\n- **CORS Support**: Cross-origin resource sharing\n\n### Architecture \u0026 Testing\n- **Clean Architecture**: Separation of concerns with layers\n- **Comprehensive Testing**: Unit and integration tests\n- **Database Migrations**: Automated schema initialization\n- **Environment Configuration**: Flexible configuration management\n- **API Documentation**: Complete endpoint documentation\n\n### Performance \u0026 Scalability\n- **Rate Limiting**: Protection against API abuse (60 req/min)\n- **Caching**: In-memory caching for improved performance\n- **Pagination**: Efficient data retrieval with filtering and sorting\n- **Database Indexing**: Optimized database queries\n- **Connection Pooling**: Efficient database connection management\n\n### Development \u0026 Deployment\n- **Docker Support**: Containerized deployment\n- **CI/CD Pipeline**: Automated testing and deployment\n- **Health Monitoring**: Comprehensive health checks\n- **Logging**: Structured request/response logging\n- **OpenAPI Documentation**: Swagger/OpenAPI 3.0 specification\n\n### Technology Stack\n- **Routing**: [Gorilla Mux](https://github.com/gorilla/mux)\n- **Database**: [MySQL Driver](https://github.com/go-sql-driver/mysql)\n- **JWT**: [jwt-go](https://github.com/dgrijalva/jwt-go)\n- **Password Hashing**: [bcrypt](https://golang.org/x/crypto/bcrypt)\n- **Validation**: [validator/v10](https://github.com/go-playground/validator)\n- **Testing**: [Testify](https://github.com/stretchr/testify)\n- **UUID**: [Google UUID](https://github.com/google/uuid)\n\n## 🛠️ Getting Started\n\n### Prerequisites\n- [Go 1.16+](https://golang.org/doc/install)\n- [MySQL 5.7+](https://dev.mysql.com/downloads/mysql/)\n- [Git](https://git-scm.com/downloads)\n\n### Installation\n\n1. **Clone the repository**\n```bash\ngit clone https://github.com/jmrashed/golang-rest-api-with-mysql.git\ncd golang-rest-api-with-mysql\n```\n\n2. **Install dependencies**\n```bash\ngo mod tidy\n```\n\n3. **Set up environment variables**\n```bash\ncp .env.example .env\n# Edit .env with your database credentials and JWT secrets\n```\n\n4. **Set up MySQL database**\n```sql\nCREATE DATABASE goblog;\n```\n\n5. **Run the application**\n```bash\n# Development\ngo run main.go\n\n# Or using Make\nmake run\n\n# Or using Docker\ndocker-compose up -d\n```\n\nThe server will start on `http://localhost:8080`\n\n### Quick Start with Docker\n\n```bash\n# Clone and start with Docker\ngit clone https://github.com/jmrashed/golang-rest-api-with-mysql.git\ncd golang-rest-api-with-mysql\ncp .env.example .env\ndocker-compose up -d\n```\n\n## 📚 API Endpoints\n\n### Public Endpoints\n- `POST /api/v1/register` - User registration\n- `POST /api/v1/login` - User authentication\n- `POST /api/v1/refresh` - Token refresh\n- `GET /health` - Health check\n\n### Protected Endpoints (Authentication Required)\n- `GET /api/v1/profile` - Get user profile\n- `PUT /api/v1/profile` - Update user profile\n- `POST /api/v1/change-password` - Change password\n- `POST /api/v1/logout` - Logout from current session\n- `POST /api/v1/logout-all` - Logout from all sessions\n\n### Role-Based Endpoints\n- `/api/v1/admin/*` - Admin only endpoints\n- `/api/v1/moderator/*` - Moderator and admin endpoints\n- `/api/v1/todos/*` - Permission-based todo endpoints\n\nFor detailed API documentation, see [API_DOCUMENTATION.md](API_DOCUMENTATION.md)\n\n## 🧪 Testing with Postman\n\n### Environment Setup\n1. Create a new Postman environment\n2. Add variables:\n   - `baseUrl`: `http://localhost:8080/api/v1`\n   - `accessToken`: (will be set automatically)\n   - `refreshToken`: (will be set automatically)\n\n### Auto-Token Management\nAdd this script to the **Tests** tab of login and register requests:\n\n```javascript\nif (pm.response.code === 200 || pm.response.code === 201) {\n    const response = pm.response.json();\n    if (response.data \u0026\u0026 response.data.access_token) {\n        pm.environment.set('accessToken', response.data.access_token);\n        pm.environment.set('refreshToken', response.data.refresh_token);\n    }\n}\n```\n\n### Authorization Header\nFor protected endpoints, set Authorization header to:\n```\nBearer {{accessToken}}\n```\n\n## 🔧 cURL Examples\n\n### User Registration\n```bash\ncurl -X POST http://localhost:8080/api/v1/register \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"username\": \"testuser\",\n    \"email\": \"test@example.com\",\n    \"password\": \"password123\"\n  }'\n```\n\n### User Login\n```bash\ncurl -X POST http://localhost:8080/api/v1/login \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"username\": \"testuser\",\n    \"password\": \"password123\"\n  }'\n```\n\n### Get User Profile (Protected)\n```bash\ncurl -X GET http://localhost:8080/api/v1/profile \\\n  -H \"Authorization: Bearer YOUR_ACCESS_TOKEN\"\n```\n\n### Refresh Token\n```bash\ncurl -X POST http://localhost:8080/api/v1/refresh \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"refresh_token\": \"YOUR_REFRESH_TOKEN\"\n  }'\n```\n\n## 📁 Project Structure\n\n```\n.\n├── auth/                 # Authentication utilities\n├── database/             # Database connection and configuration\n├── handlers/             # HTTP request handlers\n├── middleware/           # Authentication and authorization middleware\n├── model/                # Data models and DTOs\n├── repository/           # Data access layer\n├── route/                # Route definitions and setup\n├── schema/               # Database schema and migrations\n├── service/              # Business logic layer\n├── static/               # Static files\n├── .env.example          # Environment variables template\n├── API_DOCUMENTATION.md  # Detailed API documentation\n└── main.go               # Application entry point\n```\n\n## 🔐 Authentication \u0026 Authorization System\n\n### JWT Token Structure\nThe system uses two types of tokens:\n\n**Access Token** (15 minutes):\n```json\n{\n  \"user_id\": 1,\n  \"username\": \"testuser\",\n  \"email\": \"test@example.com\",\n  \"roles\": [\"user\"],\n  \"permissions\": [\"read_todos\", \"write_todos\"],\n  \"exp\": 1640995200\n}\n```\n\n**Refresh Token** (7 days):\n```json\n{\n  \"user_id\": 1,\n  \"jti\": \"unique-token-id\",\n  \"exp\": 1641600000\n}\n```\n\n### Middleware Chain\n1. **CORS Middleware**: Handles cross-origin requests\n2. **Auth Middleware**: Validates JWT tokens\n3. **Role Middleware**: Checks user roles\n4. **Permission Middleware**: Validates specific permissions\n\n### Role-Based Access Control\n- **Admin**: Full system access\n- **Moderator**: Content management access\n- **User**: Basic user operations\n\n### Permission System\nFine-grained permissions for specific actions:\n- `read_users`, `write_users`, `delete_users`\n- `read_todos`, `write_todos`, `delete_todos`\n- `manage_roles`\n\n## 🗄️ Database Schema\n\nThe system uses a comprehensive database schema with the following tables:\n\n- **users**: User account information\n- **roles**: System roles (admin, user, moderator)\n- **permissions**: Granular permissions\n- **user_roles**: User-role assignments\n- **role_permissions**: Role-permission assignments\n- **refresh_tokens**: Secure token storage\n\nFor detailed schema, see [schema/schema.sql](schema/schema.sql)\n\n## 🧪 Testing\n\n### Run Unit Tests\n```bash\n# Individual packages\ngo test ./auth -v\ngo test ./middleware -v\ngo test ./handlers -v\n\n# Or using Make\nmake test\n```\n\n### Run All Tests\n```bash\n# All tests with race detection\ngo test ./... -v -race\n\n# With coverage\nmake test-coverage\n```\n\n### Test Coverage\n```bash\n# Generate coverage report\ngo test ./... -coverprofile=coverage.out\ngo tool cover -html=coverage.out -o coverage.html\n\n# Or using Make\nmake test\n```\n\n### End-to-End Tests\n```bash\n# Run E2E tests\ngo test ./tests -v\n```\n\n### Performance Testing\n```bash\n# Load testing with Apache Bench\nab -n 1000 -c 10 http://localhost:8080/health\n\n# Or with curl for rate limiting\nfor i in {1..70}; do curl http://localhost:8080/health; done\n```\n\n## 🚀 Deployment\n\n### Environment Variables\nCopy `.env.example` to `.env` and configure:\n- Database credentials\n- JWT secrets (use strong, random keys)\n- Server configuration\n\n### Docker Deployment\n\n```bash\n# Build and run with Docker Compose\ndocker-compose up -d\n\n# Or build manually\ndocker build -t golang-rest-api .\ndocker run -p 8080:8080 golang-rest-api\n```\n\n### Production Deployment\n\n```bash\n# Build for production\nmake prod-build\n\n# Run database migration\nmake migrate\n\n# Start the application\n./build/golang-rest-api\n```\n\n### Production Considerations\n- Use environment-specific JWT secrets\n- Enable HTTPS with reverse proxy (nginx/traefik)\n- Configure proper CORS origins\n- Set up database connection pooling\n- Implement monitoring and alerting\n- Use container orchestration (Kubernetes/Docker Swarm)\n- Set up log aggregation (ELK stack)\n- Configure backup strategies\n\n### Monitoring\n\n- **Health Check**: `GET /health`\n- **Metrics**: Application logs and performance metrics\n- **Database**: Connection pool monitoring\n- **Rate Limiting**: Request rate monitoring\n\n## 🛠️ Development\n\n### Available Make Commands\n\n```bash\nmake help          # Show all available commands\nmake dev-setup     # Setup development environment\nmake build         # Build the application\nmake run           # Run the application\nmake test          # Run tests with coverage\nmake lint          # Run code linter\nmake security      # Run security scan\nmake docker-build  # Build Docker image\nmake docker-run    # Run with Docker Compose\nmake clean         # Clean build artifacts\n```\n\n### Code Quality\n\n```bash\n# Run linter\ngolangci-lint run\n\n# Security scan\ngosec ./...\n\n# Format code\ngo fmt ./...\n```\n\n## 🤝 Contributing\n\n1. Fork the repository\n2. Create a feature branch (`git checkout -b feature/amazing-feature`)\n3. Make your changes\n4. Add tests for new functionality\n5. Run tests and linting (`make test \u0026\u0026 make lint`)\n6. Commit your changes (`git commit -m 'Add amazing feature'`)\n7. Push to the branch (`git push origin feature/amazing-feature`)\n8. Submit a pull request\n\n### Development Guidelines\n\n- Follow Go best practices and idioms\n- Write comprehensive tests for new features\n- Update documentation for API changes\n- Use meaningful commit messages\n- Ensure all CI checks pass\n\n## 📄 License\n\nThis project is licensed under the MIT License - see the LICENSE file for details.\n\n## 📊 Performance Metrics\n\n- **Response Time**: \u003c 100ms for most endpoints\n- **Throughput**: 1000+ requests/second\n- **Rate Limiting**: 60 requests/minute per IP\n- **Cache Hit Rate**: 80%+ for cached endpoints\n- **Database Connections**: Pool of 25 connections\n\n## 🔍 API Documentation\n\n- **Swagger UI**: Available at `/docs` (when implemented)\n- **OpenAPI Spec**: [docs/swagger.yaml](docs/swagger.yaml)\n- **Postman Collection**: Import the API endpoints\n- **cURL Examples**: See README sections above\n\n## 🆘 Support\n\nFor questions and support:\n- Create an issue on GitHub\n- Check the [API Documentation](API_DOCUMENTATION.md)\n- Review the [OpenAPI Specification](docs/swagger.yaml)\n- Review the test files for usage examples\n- Check the [Makefile](Makefile) for development commands\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjmrashed%2Fgolang-rest-api-with-mysql","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fjmrashed%2Fgolang-rest-api-with-mysql","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjmrashed%2Fgolang-rest-api-with-mysql/lists"}