{"id":31561006,"url":"https://github.com/liiijz/gin-boilerplate","last_synced_at":"2026-05-02T17:33:46.604Z","repository":{"id":317975625,"uuid":"1069535582","full_name":"liiijz/gin-boilerplate","owner":"liiijz","description":"⚡Fast-start scaffold for Gin Framework APIs. Includes MySQL, Redis-powered JWT auth, and a well-structured architecture to launch your Go projects quickly.","archived":false,"fork":false,"pushed_at":"2025-10-15T15:18:22.000Z","size":63,"stargazers_count":34,"open_issues_count":0,"forks_count":1,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-10-16T04:20:01.802Z","etag":null,"topics":["authentication","boilerplate","gin","gin-gonic","golang","jwt","middleware","mvc","mysql","redis","restful-api","template"],"latest_commit_sha":null,"homepage":"","language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/liiijz.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,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2025-10-04T05:50:29.000Z","updated_at":"2025-10-15T15:18:26.000Z","dependencies_parsed_at":"2025-10-04T09:21:03.708Z","dependency_job_id":"9b6297ba-2a3c-4302-8320-ccd0aa97a866","html_url":"https://github.com/liiijz/gin-boilerplate","commit_stats":null,"previous_names":["liiijz/gin-boilerplate"],"tags_count":0,"template":true,"template_full_name":null,"purl":"pkg:github/liiijz/gin-boilerplate","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/liiijz%2Fgin-boilerplate","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/liiijz%2Fgin-boilerplate/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/liiijz%2Fgin-boilerplate/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/liiijz%2Fgin-boilerplate/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/liiijz","download_url":"https://codeload.github.com/liiijz/gin-boilerplate/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/liiijz%2Fgin-boilerplate/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":32543959,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-02T12:25:33.646Z","status":"ssl_error","status_checked_at":"2026-05-02T12:24:51.733Z","response_time":132,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"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":["authentication","boilerplate","gin","gin-gonic","golang","jwt","middleware","mvc","mysql","redis","restful-api","template"],"created_at":"2025-10-05T02:46:32.449Z","updated_at":"2026-05-02T17:33:46.598Z","avatar_url":"https://github.com/liiijz.png","language":"Go","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Gin Boilerplate\n\nEnglish | [简体中文](./README_CN.md)\n\nA production-ready Go web application boilerplate built with Gin + GORM, featuring best practices and clean architecture.\n\n## ✨ Features\n\n- 🚀 **Complete Project Structure** - Clean layered architecture (Controller, Service, Model, Router)\n- 🔐 **JWT Authentication** - Complete user authentication system\n- ⚙️ **Multi-Environment Config** - Support for development, production, and more (Viper-based)\n- 🗄️ **Database ORM** - GORM with auto-migration support\n- 🔒 **Password Encryption** - Bcrypt password hashing\n- 📝 **Logging Middleware** - Request logging\n- 🌐 **CORS Support** - Cross-Origin Resource Sharing middleware\n- 📦 **Unified Response Format** - Standardized API response structure\n- 🎨 **Startup Banner** - Spring Boot-style startup banner\n- 🧪 **API Test Scripts** - Multiple testing script options\n- 🧩 **Plugin System** - Modular plugin architecture for extensibility\n\n## 📁 Project Structure\n\n```\ngin-boilerplate/\n├── config/                 # Configuration files\n│   ├── banner.txt         # Startup banner\n│   ├── config.go          # Configuration loading logic\n│   ├── default.yaml       # Default configuration\n│   ├── development.yaml   # Development environment config\n│   └── production.yaml    # Production environment config\n├── controllers/           # Controller layer\n│   ├── auth_controller.go # Authentication controller\n│   └── user_controller.go # User controller\n├── database/              # Database connection\n│   └── database.go\n├── middleware/            # Middlewares\n│   ├── auth.go           # JWT authentication middleware\n│   ├── cors.go           # CORS middleware\n│   └── logger.go         # Logging middleware\n├── models/                # Data models\n│   ├── base.go           # Base model\n│   └── user.go           # User model\n├── plugins/               # Plugin system and implementations\n│   ├── environment.go    # Plugin runtime environment\n│   ├── plugin.go         # Plugin interface definition\n│   ├── registry.go       # Plugin registry\n│   └── guest/            # Guest plugin example\n│       ├── controllers/\n│       ├── models/\n│       ├── services/\n│       └── guest_plugin.go\n├── router/                # Router layer\n│   └── router.go\n├── scripts/               # Scripts\n│   ├── api-test.http     # HTTP test file\n│   ├── api-test.sh       # Bash test script\n│   └── init.sql          # Database initialization script\n├── services/              # Business logic layer\n│   ├── auth_service.go   # Authentication service\n│   └── user_service.go   # User service\n├── utils/                 # Utilities\n│   ├── banner.go         # Banner utility\n│   ├── jwt.go            # JWT utility\n│   └── response.go       # Response utility\n├── .gitignore\n├── go.mod\n├── main.go               # Application entry point\n└── README.md\n```\n\n## 🚀 Quick Start\n\n### Option 1: Docker Deployment (Recommended)\n\n#### Requirements\n\n- Docker\n- MySQL (external or separate container)\n\n#### Steps\n\n1. **Clone the project**\n\n```bash\ngit clone \u003crepository-url\u003e\ncd gin-boilerplate\n```\n\n2. **Configure production settings**\n\nEdit `config/production.yaml` to match your database configuration:\n\n```yaml\ndatabase:\n  host: \"your-mysql-host\"\n  port: \"3306\"\n  user: \"your-db-user\"\n  password: \"your-db-password\"\n  dbname: \"gin_boilerplate_prod\"\n```\n\n3. **Build Docker image**\n\n```bash\ndocker build -t gin-boilerplate:latest .\n```\n\n4. **Run container**\n\n```bash\ndocker run -d \\\n  --name gin-boilerplate \\\n  -p 8080:8080 \\\n  -v $(pwd)/config:/root/config \\\n  gin-boilerplate:latest\n```\n\n5. **Check logs**\n\n```bash\ndocker logs -f gin-boilerplate\n```\n\n6. **Stop container**\n\n```bash\ndocker stop gin-boilerplate\ndocker rm gin-boilerplate\n```\n\nThe service runs on `http://localhost:8080` by default.\n\n### Option 2: Local Development\n\n#### Requirements\n\n- Go 1.19+\n- MySQL 5.7+\n\n#### Steps\n\n1. **Clone the Project**\n\n```bash\ngit clone \u003crepository-url\u003e\ncd gin-boilerplate\n```\n\n2. **Install Dependencies**\n\n```bash\ngo mod tidy\n```\n\n3. **Database Setup**\n\n**Initialize Database**\n\n```bash\nmysql -u root -p \u003c scripts/init.sql\n```\n\n**Configure Database Connection**\n\nEdit `config/development.yaml`:\n\n```yaml\ndatabase:\n  host: \"localhost\"\n  port: \"3306\"\n  user: \"root\"\n  password: \"your_password\"\n  dbname: \"gin_boilerplate_dev\"\n\njwt:\n  secret: \"your-secret-key\"\n  expire_time: 72\n```\n\n4. **Run the Application**\n\n**Development Environment**\n\n```bash\ngo run main.go\n# Or specify environment\ngo run main.go -e development\n```\n\n**Production Environment**\n\n```bash\ngo run main.go -e production\n```\n\nThe service runs on `http://localhost:8080` by default.\n\n## 🐳 Docker Deployment Details\n\n### Dockerfile Features\n\n- **Multi-stage build**: Minimizes final image size\n- **Alpine-based**: Lightweight and secure\n- **Production optimized**: CGO disabled for static binary\n\n### Using with Reverse Proxy\n\nThis application is designed to run behind a reverse proxy (Nginx, Traefik, etc.). The reverse proxy should handle:\n\n- SSL/TLS termination\n- Load balancing\n- Rate limiting\n- Static file serving (if needed)\n\nExample Nginx configuration:\n\n```nginx\nupstream gin_backend {\n    server localhost:8080;\n}\n\nserver {\n    listen 80;\n    server_name your-domain.com;\n\n    location / {\n        proxy_pass http://gin_backend;\n        proxy_set_header Host $host;\n        proxy_set_header X-Real-IP $remote_addr;\n        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n        proxy_set_header X-Forwarded-Proto $scheme;\n    }\n}\n```\n\n### Production Considerations\n\nBefore deploying to production:\n\n1. Change the JWT secret in `config/production.yaml`\n2. Configure external MySQL database\n3. Set up proper logging and monitoring\n4. Configure firewall rules\n5. Use reverse proxy for SSL/TLS\n6. Set up automated backups for database\n\n## 📚 API Documentation\n\n### Authentication\n\n#### User Registration\n\n```http\nPOST /api/v1/auth/register\nContent-Type: application/json\n\n{\n  \"username\": \"testuser\",\n  \"email\": \"test@example.com\",\n  \"password\": \"password123\",\n  \"full_name\": \"Test User\"\n}\n```\n\n**Response:**\n\n```json\n{\n  \"success\": true,\n  \"code\": 200,\n  \"message\": \"Success\",\n  \"data\": {\n    \"user\": {\n      \"id\": 1,\n      \"username\": \"testuser\",\n      \"email\": \"test@example.com\",\n      \"full_name\": \"Test User\",\n      \"created_at\": \"2024-01-01T00:00:00Z\"\n    }\n  }\n}\n```\n\n#### User Login\n\n```http\nPOST /api/v1/auth/login\nContent-Type: application/json\n\n{\n  \"username\": \"testuser\",\n  \"password\": \"password123\"\n}\n```\n\n**Response:**\n\n```json\n{\n  \"success\": true,\n  \"code\": 200,\n  \"message\": \"Success\",\n  \"data\": {\n    \"token\": \"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...\",\n    \"user\": {\n      \"id\": 1,\n      \"username\": \"testuser\",\n      \"email\": \"test@example.com\",\n      \"full_name\": \"Test User\"\n    }\n  }\n}\n```\n\n### User Endpoints (Authentication Required)\n\nAll user-related endpoints require a token in the header:\n\n```http\nAuthorization: Bearer {your_token}\n```\n\n#### Get Current User Info\n\n```http\nGET /api/v1/me\nAuthorization: Bearer {token}\n```\n\n#### Update Current User Info\n\n```http\nPUT /api/v1/me\nAuthorization: Bearer {token}\nContent-Type: application/json\n\n{\n  \"full_name\": \"Updated Name\",\n  \"email\": \"newemail@example.com\"\n}\n```\n\n#### Update Password\n\n```http\nPUT /api/v1/me\nAuthorization: Bearer {token}\nContent-Type: application/json\n\n{\n  \"password\": \"newpassword123\"\n}\n```\n\n### Health Check\n\n```http\nGET /api/v1/health\n```\n\n**Response:**\n\n```json\n{\n  \"status\": \"ok\",\n  \"message\": \"Service is running\"\n}\n```\n\n## 🧪 API Testing\n\nThe project provides multiple API testing scripts:\n\n### 1. HTTP File Testing (Recommended)\n\nUse VS Code REST Client extension or IntelliJ IDEA HTTP Client:\n\n```bash\n# Open scripts/api-test.http file\n# Click \"Send Request\" to execute tests\n```\n\n### 2. Bash Script Testing\n\nFor Linux/Mac users:\n\n```bash\nchmod +x scripts/api-test.sh\n./scripts/api-test.sh\n```\n\nFor Windows users (Git Bash):\n\n```bash\nbash scripts/api-test.sh\n```\n\n## ⚙️ Configuration\n\n### Configuration Hierarchy\n\n1. `config/default.yaml` - Base configuration (shared across all environments)\n2. `config/{env}.yaml` - Environment-specific configuration (overrides defaults)\n\n### Configuration Options\n\n```yaml\n# Server configuration\nserver:\n  port: \"8080\"              # Server port\n  mode: \"debug\"             # Running mode: debug, release, test\n\n# Database configuration\ndatabase:\n  host: \"localhost\"         # Database host\n  port: \"3306\"              # Database port\n  user: \"root\"              # Database username\n  password: \"\"              # Database password\n  dbname: \"gin_boilerplate\" # Database name\n\n# JWT configuration\njwt:\n  secret: \"your-secret-key\" # JWT secret key (MUST change in production)\n  expire_time: 24           # Token validity period (hours)\n```\n\n### Custom Startup Banner\n\nEdit the `config/banner.txt` file to customize your startup banner.\n\n## 🔧 Development Guide\n\n### Adding New APIs\n\n1. **Create Model** (`models/`)\n\n```go\ntype Product struct {\n    BaseModel\n    Name  string `gorm:\"not null\" json:\"name\"`\n    Price float64 `json:\"price\"`\n}\n```\n\n2. **Create Service** (`services/`)\n\n```go\ntype ProductService struct{}\n\nfunc (s *ProductService) CreateProduct(product *models.Product) error {\n    return database.GetDB().Create(product).Error\n}\n```\n\n3. **Create Controller** (`controllers/`)\n\n```go\ntype ProductController struct {\n    productService *services.ProductService\n}\n\nfunc (c *ProductController) CreateProduct(ctx *gin.Context) {\n    // Handle request\n}\n```\n\n4. **Register Routes** (`router/router.go`)\n\n```go\nproductController := controllers.NewProductController()\nproductRoutes := authenticated.Group(\"/products\")\n{\n    productRoutes.POST(\"\", productController.CreateProduct)\n    productRoutes.GET(\"\", productController.GetAllProducts)\n}\n```\n\n### Using Middleware\n\n```go\n// Global middleware\nr.Use(middleware.Logger())\n\n// Route group middleware\nauthenticated := v1.Group(\"\")\nauthenticated.Use(middleware.JWTAuth())\n```\n\n### Database Migration\n\nAdd auto-migration for new models in `main.go`:\n\n```go\ndatabase.GetDB().AutoMigrate(\n    \u0026models.User{},\n    \u0026models.Product{}, // New model\n)\n```\n\n## 🧩 Plugin System\n\nThe plugin system allows you to extend the application with modular features without modifying the core codebase.\n\n### Plugin Architecture\n\nThe plugin system provides:\n\n- **Plugin Interface**: Define plugin contract with `Register()` and `RouterPath()` methods\n- **Plugin Registry**: Auto-register plugins at startup using `init()` functions\n- **Plugin Environment**: Share dependencies (database, etc.) with plugins\n- **Isolated Routes**: Each plugin gets its own route group under `/api/v1/plugin/{plugin-name}`\n\n### Creating a Plugin\n\n**1. Create Plugin Structure**\n\n```\nplugins/\n└── myplugin/\n    ├── controllers/\n    │   └── myplugin_controller.go\n    ├── models/\n    │   └── myplugin_model.go\n    ├── services/\n    │   └── myplugin_service.go\n    └── myplugin_plugin.go\n```\n\n**2. Define Plugin Model** (`models/myplugin_model.go`)\n\n```go\npackage models\n\nimport \"gin-boilerplate/models\"\n\ntype MyPluginData struct {\n    models.BaseModel\n    Name string `gorm:\"not null\" json:\"name\"`\n}\n```\n\n**3. Create Plugin Controller** (`controllers/myplugin_controller.go`)\n\n```go\npackage controllers\n\nimport \"github.com/gin-gonic/gin\"\n\ntype MyPluginController struct{}\n\nfunc NewMyPluginController() *MyPluginController {\n    return \u0026MyPluginController{}\n}\n\nfunc (c *MyPluginController) Hello(ctx *gin.Context) {\n    ctx.JSON(200, gin.H{\"message\": \"Hello from MyPlugin\"})\n}\n```\n\n**4. Implement Plugin Interface** (`myplugin_plugin.go`)\n\n```go\npackage myplugin\n\nimport (\n    \"gin-boilerplate/plugins\"\n    \"gin-boilerplate/plugins/myplugin/controllers\"\n    \"gin-boilerplate/plugins/myplugin/models\"\n    \"github.com/gin-gonic/gin\"\n    \"gorm.io/gorm\"\n)\n\n// Auto-register plugin on import\nfunc init() {\n    plugins.Register(\"myplugin\", NewMyPlugin)\n}\n\ntype MyPlugin struct {\n    db *gorm.DB\n}\n\nfunc NewMyPlugin(env *plugins.PluginEnvironment) plugins.Plugin {\n    return \u0026MyPlugin{db: env.DB}\n}\n\nfunc (p *MyPlugin) RouterPath() string {\n    return \"/myplugin\"\n}\n\nfunc (p *MyPlugin) Register(group *gin.RouterGroup) error {\n    // Auto-migrate plugin tables\n    if err := p.db.AutoMigrate(\u0026models.MyPluginData{}); err != nil {\n        return err\n    }\n\n    // Register routes\n    controller := controllers.NewMyPluginController()\n    group.GET(\"/hello\", controller.Hello)\n\n    return nil\n}\n```\n\n**5. Import Plugin in main.go**\n\n```go\nimport (\n    _ \"gin-boilerplate/plugins/myplugin\" // Auto-register plugin\n)\n```\n\n### Plugin Routes\n\nAll plugins are automatically mounted under `/api/v1/plugin/`:\n\n- Guest plugin: `http://localhost:8080/api/v1/plugin/guest/*`\n- Your plugin: `http://localhost:8080/api/v1/plugin/myplugin/*`\n\n### Example: Guest Plugin\n\nThe project includes a guest plugin example at `plugins/guest/` that demonstrates:\n\n- Plugin registration and initialization\n- Route setup under `/api/v1/plugin/guest`\n- Database model auto-migration\n- Controller implementation\n\n**Test the Guest Plugin:**\n\n```bash\ncurl -X POST http://localhost:8080/api/v1/plugin/guest/login\n```\n\n### Plugin Best Practices\n\n1. **Self-contained**: Keep plugin code isolated in its own directory\n2. **Database migrations**: Use `AutoMigrate()` in plugin's `Register()` method\n3. **Naming convention**: Use lowercase for plugin names and route paths\n4. **Error handling**: Return errors from `Register()` for proper initialization\n5. **Dependencies**: Access shared resources through `PluginEnvironment`\n\n## 🛡️ Security Recommendations\n\n1. **Change JWT Secret**: Use a strong secret key in production\n2. **HTTPS**: Use HTTPS in production environments\n3. **Database Password**: Don't commit production config files to Git\n4. **Input Validation**: Use Gin's binding for user input validation\n5. **Rate Limiting**: Add API rate limiting middleware as needed\n\n## 📦 Dependencies\n\n- [Gin](https://github.com/gin-gonic/gin) - Web framework\n- [GORM](https://gorm.io/) - ORM library\n- [Viper](https://github.com/spf13/viper) - Configuration management\n- [JWT](https://github.com/golang-jwt/jwt) - JWT authentication\n- [bcrypt](https://pkg.go.dev/golang.org/x/crypto/bcrypt) - Password encryption\n\n## 📝 TODO\n\n- [ ] Add unit tests\n- [ ] Add API documentation (Swagger)\n- [x] Add Docker support\n- [ ] Add rate limiting middleware\n- [ ] Add cache support (Redis)\n- [ ] Add file logging\n\n## 📄 License\n\nMIT License\n\n## 🤝 Contributing\n\nIssues and Pull Requests are welcome!\n\n---\n\n**Happy Coding!** 🎉\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fliiijz%2Fgin-boilerplate","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fliiijz%2Fgin-boilerplate","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fliiijz%2Fgin-boilerplate/lists"}