{"id":21834250,"url":"https://github.com/faizahmedfarooqui/go-gin-api-server","last_synced_at":"2025-04-14T08:37:00.298Z","repository":{"id":264886861,"uuid":"862230838","full_name":"faizahmedfarooqui/go-gin-api-server","owner":"faizahmedfarooqui","description":"A simple API server built with Golang using the Gin Framework and supports live reloading during development using Air, Validators Auto-Registration and has an integrated migration system.","archived":false,"fork":false,"pushed_at":"2024-09-26T07:28:29.000Z","size":49,"stargazers_count":7,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-04-05T04:16:02.488Z","etag":null,"topics":["api-server","database","gin","gin-framework","gin-gonic","go","golang","migration","postgres","postgresql","validator-auto-generate","validators"],"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/faizahmedfarooqui.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":"SECURITY.md","support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-09-24T08:57:53.000Z","updated_at":"2024-10-23T05:48:35.000Z","dependencies_parsed_at":"2024-11-26T16:56:20.097Z","dependency_job_id":"adbe776a-bb24-4ac8-ab96-bcbaf41d14a2","html_url":"https://github.com/faizahmedfarooqui/go-gin-api-server","commit_stats":null,"previous_names":["faizahmedfarooqui/go-gin-api-server"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/faizahmedfarooqui%2Fgo-gin-api-server","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/faizahmedfarooqui%2Fgo-gin-api-server/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/faizahmedfarooqui%2Fgo-gin-api-server/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/faizahmedfarooqui%2Fgo-gin-api-server/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/faizahmedfarooqui","download_url":"https://codeload.github.com/faizahmedfarooqui/go-gin-api-server/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248846899,"owners_count":21171053,"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":["api-server","database","gin","gin-framework","gin-gonic","go","golang","migration","postgres","postgresql","validator-auto-generate","validators"],"created_at":"2024-11-27T20:09:32.417Z","updated_at":"2025-04-14T08:37:00.246Z","avatar_url":"https://github.com/faizahmedfarooqui.png","language":"Go","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Go-Gin API Server\n\nThis project is a simple API server built with [Go](https://golang.org/) using the [Gin Web Framework](https://github.com/gin-gonic/gin).\n\nThe project supports live reloading during development using **Air**, has an integrated migration system, auto-registeration of validators and cron scheduling system.\n\n## Table of Contents\n- [Prerequisites](#prerequisites)\n- [Installation](#installation)\n- [Development](#development)\n- [Project Structure](#project-structure)\n  - [Explanation of Directories](#explanation-of-directories)\n- [Database Migrations](#database-migrations)\n  - [Apply Migrations](#apply-migrations)\n  - [Rollback Migrations](#rollback-migrations)\n- [Scheduled Tasks (Cron Jobs)](#scheduled-tasks-cron-jobs)\n  - [Running Cron Jobs](#running-cron-jobs)\n  - [Adding a New Cron Job](#adding-a-new-cron-job)\n- [Validators](#validators)\n  - [RegisterUserValidator](#registeruservalidator)\n  - [LoginUserValidator](#loginuservalidator)\n  - [Custom Error Messages](#custom-error-messages)\n- [Auto-Generated Code](#auto-generated-code)\n  - [Using `go generate`](#using-go-generate)\n- [Configuration](#configuration)\n- [Development Workflow](#development-workflow)\n  - [Live Reloading with Air](#live-reloading-with-air)\n- [Contributing](#contributing)\n- [License](#license)\n\n---\n\n## Prerequisites\n\nBefore setting up the project, ensure you have the following installed:\n\n- [Go 1.17+](https://golang.org/dl/)\n- [PostgreSQL](https://www.postgresql.org/) (or your preferred database)\n- [Air](https://github.com/air-verse/air) for live-reloading (installed as a dependency)\n\n## Installation\n\n1. **Clone the repository**:\n  ```bash\n  git clone https://github.com/yourusername/go-gin-api-server.git\n  cd go-gin-api-server\n  ```\n\n2. **Install dependencies**: Ensure all Go dependencies and tools (including **Air**) are installed.\n  ```bash\n  go mod tidy\n  go install github.com/air-verse/air@latest\n  ```\n\n3. **Setup environment variables**: Create a `.env` file with your database and other environment variables.\n  ```bash\n  cp .env.example .env\n  ```\n\n  Example `.env` file:\n  ```ini\n  # Available modes: debug, release or test\n  GIN_MODE=debug\n\n  # The port that the application will run on\n  APP_PORT=3000\n\n  # Database configuration\n  DB_HOST=localhost\n  DB_PORT=5432\n  DB_USER=postgres\n  DB_PASSWORD=your_password\n  DB_NAME=postgres\n  DB_SSLMODE=disable\n  ```\n\n## Development\n\nTo start the server in development mode with live-reloading (using **Air**):\n\n```bash\nmake develop\n```\n\n## Project Structure\n\n```bash\n.\n├── main.go                   # Entry point of the application\n├── tools.go                  # Track tools used in the project\n├── Makefile                  # Makefile for common tasks\n├── air.toml                  # Air configuration for live-reloading\n├── go.mod                    # Go module file\n├── go.sum                    # Go module file\n├── cmd\n│   ├── generate_validators   # Tool to auto-generate validators\n│   │   └── main.go\n│   ├── migrate               # Tool to run database migrations\n│   │   └── main.go\n│   └── schedules             # Tool to register and run cron jobs\n│       └── main.go\n├── schedules                 # Package for cron tasks\n│   └── tasks.go              # Decoupled task logic for cron jobs\n├── config                    # Configuration files\n│   └── database.go\n├── controllers               # API route handlers\n│   ├── auth_controller.go\n│   └── item_controller.go\n├── database                  # Database-related code\n│   ├── migrate.go            # Migration logic\n│   └── migrations            # SQL migration files\n│       ├── 000001_create_items_table.up.sql\n│       ├── 000001_create_items_table.down.sql\n│       └── 000002_create_users_table.up.sql\n│       ├── 000002_create_users_table.down.sql\n├── middlewares               # Middleware logic\n│   └── error_handler.go\n├── models                    # Data models\n│   ├── item.go\n│   └── user.go\n├── repositories              # Data access layer\n│   ├── item_repository.go\n│   └── user_repository.go\n├── routes                    # API routes\n│   └── routes.go\n├── services                  # Business logic\n│   ├── auth_service.go\n│   └── item_service.go\n├── tmp                       # Temporary files (excluded from version control)\n│   └── main\n├── utils                     # Utility functions\n│   └── password.go\n└── validators                # Input validation logic\n    ├── auth_validator.go\n    ├── item_validator.go\n    ├── auto_generated.go     # Auto-generated file\n    └── register.go           # Handles go:generate directive\n```\n\n### Explanation of Directories\n\n- `cmd/`: This directory contains subdirectories for command-line tools. Currently, there are two:\n  - `generate_validators`: Contains `main.go`, which is responsible for auto-generating the validator registration.\n  - `migrate`: Contains `main.go`, which handles database migration commands such as `migrate-up` and `migrate-down`.\n  - `schedules`: Contains `main.go`, which is responsible for registering and running cron jobs.\n\n- `config/`: Contains configuration-related files, such as `database.go`, which is responsible for initializing the database connection.\n\n- `controllers/`: This directory contains the handlers for your API endpoints. Each file corresponds to a different part of the API:\n  - `auth_controller.go`: Handles authentication-related API routes (e.g., login, register).\n  - `item_controller.go`: Handles item-related routes (e.g., CRUD operations for items).\n\n- `database/`: Contains all database-related code:\n  - `migrate.go`: The migration logic, handling applying and rolling back migrations.\n  - `migrations/`: Directory containing SQL migration files, including both `.up.sql` (for applying migrations) and `.down.sql` (for rolling back).\n\n- `middlewares/`: This directory contains middleware logic, such as `error_handler.go`, which is responsible for handling validation and binding errors.\n\n- `models/`: Defines the data models for the application:\n  - `item.go`: Defines the structure for the `Item` model.\n  - `user.go`: Defines the structure for the `User` model.\n\n- `repositories/`: Contains the data access layer, which abstracts database queries for different models:\n  - `item_repository.go`: Provides the database access methods for the `Item` model.\n  - `user_repository.go`: Provides the database access methods for the `User` model.\n\n- `routes/`: Responsible for setting up the API routes:\n  - `routes.go`: Contains the function that configures all the routes for the application.\n\n- `services/`: This directory contains the business logic of the application:\n  - `auth_service.go`: Contains the logic for user authentication, such as login and registration.\n  - `item_service.go`: Contains the business logic for managing items.\n\n- `tmp/`: Temporary files created during development, such as the Go binary generated by Air for live-reloading. This directory is excluded from version control.\n\n- `tools.go`: A Go file that is used to track tools like Air. This file ensures development tools are included in `go.mod` and can be installed by others working on the project.\n\n- `utils/`: This directory contains utility functions, such as `password.go`, which includes password hashing and validation logic.\n\n- `validators/`: This directory contains all the input validation logic for your application:\n  - `auth_validator.go`: Defines validators for authentication-related data (e.g., login, register).\n  - `item_validator.go`: Defines validators for item-related data (e.g., item creation).\n  - `auto_generated.go`: This file is auto-generated and contains dynamic registration of validators.\n  - `register.go`: Handles the go:generate directive for generating the auto_generated.go file.\n\n- `schedules/`: Contains the logic for scheduling and running cron jobs:\n  - `tasks.go`: Contains the decoupled task logic for cron jobs.\n\n## Database Migrations\n\nThe project includes a migration system for managing database schema changes:\n\n### Apply Migrations\n\nTo apply all pending migrations, run:\n\n```bash\nmake migrate-up\n```\n\n### Rollback Migrations\n\nTo rollback the last migration, run:\n\n```bash\nmake migrate-down\n```\n\nMigration files are located in the `database/migrations/` directory.\n- **Up Migration**: Files ending in `.up.sql` are used for applying changes.\n- **Down Migration**: Files ending in `.down.sql` are used for rolling back changes.\n\n## Scheduled Tasks (Cron Jobs)\n\nThe project uses cron jobs to perform scheduled tasks such as database cleanups or other recurring operations.\n\n### Running Cron Jobs\n\nCron jobs are defined separately from the server and run independently. To start the cron job scheduler, run:\n\n```bash\nmake run-cron\n```\n\nThis will start the cron scheduler and execute tasks based on their defined schedule.\n\n### Adding a New Cron Job\n\n1. **Define the task** in the `schedules/tasks.go`. For example:\n```go\nfunc NewTask(db *sql.DB) {\n  log.Println(\"Running a new task...\")\n  // Perform the task here\n}\n```\n\n2. **Register the task** in the `cmd/schedules/main.go` with the cron expression:\n```go\n_, err := c.AddFunc(\"0 0 * * *\", func() {\n  tasks.NewTask(db)\n})\n```\n\n**Example Cron Expression**:\n- `* * * * *`: Every minute\n- `0 0 0 * * *`: Runs at midnight every day\n\n## Validators\n\nValidators ensure that incoming data (such as user input) meets the necessary requirements before it is processed by the server. The project uses `go-playground/validator` to handle validation.\n\nValidators are defined in the `validators/` directory.\n\n### RegisterUserValidator\n\nThis validator is used when creating a new user (e.g., during registration). It ensures that the `username`, `email`, and `password` fields meet certain criteria.\n\n**Location**: `validators/auth_validator.go`\n\n```go\ntype RegisterUserValidator struct {\n\tUsername string `json:\"username\" binding:\"required,min=3,max=50\" message:\"Username is required with minimum of 3 characters and maximum of 50 characters\"`\n\tEmail    string `json:\"email\" binding:\"required,email\" message:\"Email is required and must be a valid email address\"`\n\tPassword string `json:\"password\" binding:\"required,min=6\" message:\"Password is required with minimum of 6 characters\"`\n}\n```\n\n- `Username`: Required, with a minimum length of 3 and a maximum of 50 characters.\n- `Email`: Required, must be a valid email format.\n- `Password`: Required, with a minimum length of 6 characters.\n\n### LoginUserValidator\n\nThis validator is used when logging in a user. It ensures that the `email` and `password` fields are provided.\n\n**Location**: `validators/auth_validator.go`\n\n```go\ntype LoginUserValidator struct {\n  Email    string `json:\"email\" binding:\"required,email\" message:\"Email is required and must be a valid email address\"`\n  Password string `json:\"password\" binding:\"required\" message:\"Password is required\"`\n}\n```\n\n- `Email`: Required, must be a valid email format.\n- `Password`: Required.\n\n### Custom Error Messages\n\nCustom error messages for validators are set in the validators structs using the message tag. If validation fails, custom messages will be returned in the response.\n\nFor example:\n```go\nUsername string `json:\"username\" binding:\"required,min=3,max=50\" message:\"Username is required with minimum of 3 characters and maximum of 50 characters\"`\n```\n\nIn case a custom message is not provided, default validation messages are returned by the validation middleware.\n\n## Auto-Generated Code\n\nCertain files, such as validators, can be dynamically registered using the `go generate` command.\nAuto-generated code is stored in files like `validators/auto_generated.go`.\n\n### Using `go generate`\n\nTo generate the auto-generated code, run:\n\n```bash\nmake generate\n```\n\nThis command ensures that all validator structs in the `validators` packages are automatically registered.\n\n## Configuration\n\n### air.toml (Development Mode)\n\nThe `air.toml` file is used for configuring the **Air** live-reloading tool. It watches specific directories and file types, such as `.go` and `.html`, to automatically rebuild and restart the server during development.\n\nYou can modify `air.toml` to suit your development workflow, for example:\n\n```toml\n[build]\n  cmd = \"go build -o ./tmp/main .\"\n  bin = \"./tmp/main\"\n  delay = 1000\n  tmp_dir = \"tmp\"\n\n[watch]\n  includes = [\"./controllers\", \"./routes\", \"./services\", \"./validators\", \"./config\"]\n  include_ext = [\"go\", \"html\", \"tmpl\", \"tpl\"]\n  exclude_dir = [\"vendor\", \"tmp\", \"database/migrations\"]\n\n[log]\n  level = \"info\"\n```\n\n## Development Workflow\n\nThe project includes a development workflow that simplifies the process of building and running the server in development mode.\n\n### Live Reloading with Air\n\nThe project uses **Air** for live-reloading during development. This means that the server automatically restarts whenever changes are made to the codebase.\n\nTo start the server in development mode with live-reloading:\n\n```bash\nmake develop\n```\n\n## Contributing\n\nIf you would like to contribute to the project:\n\n1. Fork the repository.\n2. Create a new branch (`git checkout -b feature-branch`).\n3. Commit your changes (`git commit -am 'Add new feature'`).\n4. Push to the branch (`git push origin feature-branch`).\n5. Create a new Pull Request.\n\nAll contributions are welcome!\n\n## License\n\nThis project is open-source and available under the [MIT License](LICENSE).\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffaizahmedfarooqui%2Fgo-gin-api-server","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ffaizahmedfarooqui%2Fgo-gin-api-server","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffaizahmedfarooqui%2Fgo-gin-api-server/lists"}