{"id":14987613,"url":"https://github.com/hunter-ji/go-gin-api-starter","last_synced_at":"2025-04-12T00:15:49.814Z","repository":{"id":255603605,"uuid":"852267757","full_name":"hunter-ji/go-gin-api-starter","owner":"hunter-ji","description":"🚀 go-gin-api-starter is a powerful and flexible template for building RESTful APIs","archived":false,"fork":false,"pushed_at":"2024-09-05T15:02:08.000Z","size":60,"stargazers_count":12,"open_issues_count":0,"forks_count":1,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-04-12T00:15:42.443Z","etag":null,"topics":["backend","gin","golang","jwt","makefile","middleware","modules","mvc","postgresql","redis","rest-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/hunter-ji.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","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":"2024-09-04T14:15:04.000Z","updated_at":"2025-01-14T12:01:01.000Z","dependencies_parsed_at":"2024-09-06T09:04:20.693Z","dependency_job_id":null,"html_url":"https://github.com/hunter-ji/go-gin-api-starter","commit_stats":null,"previous_names":["hunter-ji/go-gin-api-starter"],"tags_count":0,"template":true,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hunter-ji%2Fgo-gin-api-starter","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hunter-ji%2Fgo-gin-api-starter/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hunter-ji%2Fgo-gin-api-starter/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hunter-ji%2Fgo-gin-api-starter/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/hunter-ji","download_url":"https://codeload.github.com/hunter-ji/go-gin-api-starter/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248497818,"owners_count":21113984,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","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":["backend","gin","golang","jwt","makefile","middleware","modules","mvc","postgresql","redis","rest-api","template"],"created_at":"2024-09-24T14:15:00.975Z","updated_at":"2025-04-12T00:15:49.792Z","avatar_url":"https://github.com/hunter-ji.png","language":"Go","readme":"# go-gin-api-starter\n\nEnglish | [简体中文](https://github.com/hunter-ji/go-gin-api-starter/blob/main/doc/README.zh-CN.md)\n\n## 📚 Project Introduction\n\ngo-gin-api-starter is a RESTful API project starter based on the Gin framework. It helps developers quickly build and\nstart scalable Go backend services. This starter template focusing on API development. It provides a clear and easy project base.\n\nYou can also check out my other templates:\n\n- Frontend template: [vue-ts-tailwind-vite-starter](https://github.com/hunter-ji/vue-ts-tailwind-vite-starter)\n- Database template: [postgres-redis-dev-docker-compose](https://github.com/hunter-ji/postgres-redis-dev-docker-compose)\n\n## ✨ Project Features\n\n- **Gin Framework**: Uses Gin's high performance and flexibility to quickly build RESTful APIs.\n- **MVC**: Uses MVC design to make code easier to maintain and test.\n- **PostgreSQL Support**: Uses PostgreSQL as the main database for reliable data and strong query abilities.\n- **Redis Support**: Uses Redis for caching management to improve app performance.\n- **Modular Structure**: Clear directory structure for easy project expansion and maintenance.\n- **Middleware Support**: Includes common middlewares like logging, error handling, and authentication.\n- **Config Management**: Flexible config management, supports multi-environment deployment.\n- **Custom Validators**: Built-in custom format validators, registered in Gin's binding for easy expansion.\n- **JWT Authentication**: Including auto token refresh and active refresh requests, easy to use.\n- **User Module**: Pre-set user module and test code for quick development reference and base.\n- **API Version Control**: Built-in API version control for managing different API versions.\n- **Enhanced Dev Mode Logging**: In dev mode, automatically prints detailed HTTP request and response info, greatly\n  helping API debugging and development.\n\n## 🚀 Quick Start\n\nFollow these steps to quickly set up and run your project:\n\n### 1. Clone the Project\n\n```bash\ngit clone https://github.com/hunter-ji/go-gin-api-starter\ncd go-gin-api-starter\n```\n\n### 2. Initialize Project\n\nUse the provided `project_bootstrap.sh` script to quickly initialize your project:\n\n```bash\nbash project_bootstrap.sh\n```\n\nThe process is as follows:\n\n```\n🚀 Welcome to the Go Project Initializer!\n\n📝 Please enter the new project name:\n\u003e new-project\n\nInitializing your project...\nProject name updated successfully!\n\n🐰 Do you need RabbitMQ in your project? [Y/n]:\n\u003e n\nRabbitMQ folder removed.\n\n🗑️ Do you want to remove the existing .git directory? [Y/n]:\n\u003e\nExisting .git directory removed.\n\n🔧 Do you want to initialize a new Git repository? [Y/n]:\n\u003e\nInitialized empty Git repository in /path/to/new-project/.git/\nNew Git repository initialized successfully.\n\n🎉 Project initialization complete!\nSummary:\n   Old project name: Template\n   New project name: new-project\n   RabbitMQ: Removed\n   Git: Reinitialized\n\n🧹 Do you want to run 'go mod tidy' to clean up dependencies? [Y/n]:\n\u003e n\nSkipped 'go mod tidy'. Remember to run it later if needed.\n\n🚀 How to start your project:\n1. Modify .env.development in the project root to set Redis and PostgreSQL configurations.\n2. Run the following command to start your project:\n   make run\n\n🎈 Your project is ready! Happy coding!\n```\n\nThis will help you:\n\n- Change project name\n- Remove unneeded modules, like RabbitMQ\n- Delete/reinitialize .git folder\n- Install dependencies\n\n### 3. Configure Database\n\nAdd Redis and PostgreSQL configs in the .env.development file. Example config:\n\n```\n# postgresql\nDB_HOST=\nDB_PORT=\nDB_USER=\nDB_PASSWORD=\nDB_DATABASE_NAME=\n\n# redis\nREDIS_HOST=\nREDIS_PORT=\nREDIS_PASSWORD=\nREDIS_DB=0\n```\n\nFor a quick dev environment database, you can use\nmy [Database Docker Compose](https://github.com/hunter-ji/postgres-redis-dev-docker-compose).\n\n### 4. Start Project\n\nAfter config, use this command to start the project:\n\n```bash\nmake run\n```\n\n### 5. Verify\n\nOpen a browser or use curl to access:\n\n```\nhttp://localhost:9000/api/ping\n```\n\nIf all is well, you should see a \"pong\" response.\n\n## 🏗️ Project Structure\n\n### `/cmd`\n\nMain project applications.\n\n- `/api`: Entry point for API server.\n\n### `/config`\n\nConfig files and loading logic.\n\n- config.go: Main config file.\n- constant.go: Constant definitions.\n- environment_variable.go: Environment variable handling.\n- router_white_list.go: Router whitelist config.\n\n### `/doc`\n\nDesign docs, user docs, and other project-related docs.\n\n### `/internal`\n\nPrivate app and library code.\n\n- `/api`: API layer, defines routes and handler functions.\n- `/constant`: Internal constants.\n- `/database`: Database connection and init logic.\n- `/middleware`: HTTP middleware.\n- `/model`: Data models and struct definitions.\n- `/repository`: Data access layer, handles data persistence.\n- `/service`: Business logic layer.\n\n### `/migration`\n\nDatabase migration files.\n\n- `000001_init_schema.down.sql`: Rollback script for initial schema.\n- `000001_init_schema.up.sql`: Execution script for initial schema.\n\n### `/pkg`\n\nLibrary code that can be used by external apps.\n\n- /auth: Auth-related functions.\n- /util: Common utility functions.\n\n### `/test`\n\nAdditional external test apps and test data.\n\n- `ping_test.go`: Ping function test.\n- `user_test.go`: User-related function tests.\n\n### Root Directory Files\n\n- `Makefile`: Makefile defining common commands.\n- `project_bootstrap.sh`: Project init script.\n\n## 🧪 Running Tests\n\nThis project offers various ways to run tests for different testing needs.\n\n### Run All Tests\n\nRun all tests in the project:\n\n```bash\nmake test\n```\n\n### Run Tests in a Specific Folder\n\nRun tests in the ./test folder:\n\n```bash\nmake test-folder\n```\n\n### Run a Specific Test File\n\nRun a specified test file:\n\n```bash\nmake test-file FILE=path/to/your_test.go\n```\n\nFor example:\n\n```bash\nmake test-file FILE=./test/user_test.go\n```\n\n### Output Detailed Test Logs\n\nFor all the above test commands, you can add -verbose, for example:\n\n```bash\nmake test-verbose\nmake test-folder-verbose\nmake test-file-verbose FILE=./test/user_test.go \n```\n\n## 🔄 Switching Run Environments\n\nThe project relies on the `NODE_ENV` environment variable to switch environments. If not set, it defaults to\n`development`.\nThe project loads different config files based on the environment, like `.env.development`, `.env.test`,\n`.env.production`, etc.\nJust create a new `.env` file and set the `NODE_ENV` variable.\n\n## 📖 More Usage Methods\n\nFor more usage methods, you can refer to:\n\n- The `Makefile` file, which defines common commands like run, test, build, clean, etc.\n- README files inside module folders\n- Code comments\n\nThe documentation will be continuously updated and improved in the future.\n\n## ❓ Frequently Asked Questions (FAQ)\n\n### Q1: How to change the default server port?\n\nA: Modify the `SERVER_PORT` variable in the `.env.development` file. For example, setting it to `SERVER_PORT=8080` will\nmake\nthe server run on port 8080.\n\n### Q2: Which databases does the project support?\n\nA: Currently, the project mainly supports PostgreSQL as the main database. If you need to use other databases, you may\nneed to modify the database connection code in `internal/database`.\n\n### Q3: How to add new API routes?\n\nA: Add new handler functions in the appropriate version folder (like v1) under the `internal/api` directory, then\nregister\nthis new route in the `internal/api/router.go` file.\n\n### Q4: How to customize middleware?\n\nA: Create a new middleware file in the `internal/middleware` directory, implement the middleware logic, then use the\n`r.Use()` method in `internal/api/router.go` to apply this middleware.\n\n### Q5: How to turn on or off the enhanced logging feature in development mode?\n\nA: This feature is automatically enabled in development mode by default. If you want to disable it in production, make\nsure the `NODE_ENV` environment variable is not set to `development`.\n\n### Q6: How to run specific tests?\n\nA: Use the make test-file command, specifying the test file to run. For example:\n\n```bash\nmake test-file FILE=./test/user_test.go\n```\n\n### Q7: How to configure JWT token expiration time?\n\nA: Modify variables like `accessTokenExpire` in the `pkg/auth/token.go` file.\n\n### Q8: How to add new custom validators?\n\nA: Add new validation functions in the `pkg/util/formatValidator` directory, then register this new validator in\n`pkg/util/customBindValidator`.\n\n### Q9: Does the project support CORS?\n\nA: Yes, the project has CORS middleware configured by default.\n\n## 💬 Author's Note\n\nIn recent years when writing Go projects, I summarized a template for myself. When developing new projects recently, I\nfound some shortcomings and areas that were not fully improved before, which I hadn't systematically updated and\nimproved. This time, before developing the project, I started from scratch and reorganized it. Not only did it benefit\nmyself, but I also hope it can help other developers.\n\nThis project will have some of my personal style, such as directory structure, naming conventions, etc. Of course, these\ncan be adjusted according to your own preferences and project requirements.\n\nIf you have any suggestions, you are welcome to issue or PR.\n\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhunter-ji%2Fgo-gin-api-starter","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fhunter-ji%2Fgo-gin-api-starter","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhunter-ji%2Fgo-gin-api-starter/lists"}