{"id":15095852,"url":"https://github.com/yididev/gin-host-route","last_synced_at":"2025-10-14T14:06:24.496Z","repository":{"id":255594841,"uuid":"850770132","full_name":"YidiDev/gin-host-route","owner":"YidiDev","description":"A high-performance Gin middleware for host-based routing. Easily configure and manage host-specific routes, secure against unknown hosts, and handle generic hosts for fallback routing.","archived":false,"fork":false,"pushed_at":"2024-12-12T00:08:51.000Z","size":167,"stargazers_count":2,"open_issues_count":1,"forks_count":0,"subscribers_count":2,"default_branch":"main","last_synced_at":"2025-04-14T22:09:54.418Z","etag":null,"topics":["gin","gin-framework","gin-gonic","gin-middleware","router"],"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/YidiDev.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":".github/FUNDING.yml","license":"LICENSE.md","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},"funding":{"github":["YidiDev"]}},"created_at":"2024-09-01T18:18:17.000Z","updated_at":"2024-10-05T20:13:29.000Z","dependencies_parsed_at":"2024-09-06T07:38:47.894Z","dependency_job_id":null,"html_url":"https://github.com/YidiDev/gin-host-route","commit_stats":null,"previous_names":["yididev/gin-host-route"],"tags_count":1,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/YidiDev%2Fgin-host-route","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/YidiDev%2Fgin-host-route/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/YidiDev%2Fgin-host-route/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/YidiDev%2Fgin-host-route/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/YidiDev","download_url":"https://codeload.github.com/YidiDev/gin-host-route/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248968914,"owners_count":21191162,"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":["gin","gin-framework","gin-gonic","gin-middleware","router"],"created_at":"2024-09-25T15:42:42.838Z","updated_at":"2025-10-14T14:06:19.455Z","avatar_url":"https://github.com/YidiDev.png","language":"Go","funding_links":["https://github.com/sponsors/YidiDev"],"categories":[],"sub_categories":[],"readme":"# Host Route Library\n\nA high-performance Gin middleware library for routing based on the host. This library facilitates the configuration of different routes and behaviors for distinct hostnames, enhancing the ability to host multi-tenant applications on a single server.\n\n[![go report card](https://goreportcard.com/badge/github.com/YidiDev/gin-host-route \"go report card\")](https://goreportcard.com/report/github.com/YidiDev/gin-host-route)\n[![Go](https://github.com/YidiDev/gin-host-route/actions/workflows/tests.yml/badge.svg)](https://github.com/YidiDev/gin-host-route/actions/workflows/tests.yml)\n[![MIT license](https://img.shields.io/badge/license-MIT-brightgreen.svg)](https://opensource.org/licenses/MIT)\n[![Go.Dev reference](https://img.shields.io/badge/go.dev-reference-blue?logo=go\u0026logoColor=white)](https://pkg.go.dev/github.com/YidiDev/gin-host-route?tab=doc)\n\n## Installation\n\nAdd the module to your project by running:\n\n```sh\ngo get github.com/YidiDev/gin-host-route\n```\n\n## Usage\n\nBelow is an example of how to utilize the library to define different routes based on the host.\n\n### Example\n\n```go\npackage main\n\nimport (\n   \"github.com/YidiDev/gin-host-route\"\n   \"github.com/gin-gonic/gin\"\n   \"log\"\n   \"net/http\"\n   \"os\"\n)\n\n// defineHost1Routes sets up the routes specific to host1.com.\nfunc defineHost1Routes(rg *gin.RouterGroup) {\n   // Route to handle GET request to the root URL of host1, returns a greeting message.\n   rg.GET(\"/\", func(c *gin.Context) {\n      c.String(http.StatusOK, \"Hello from host1\")\n   })\n   // Route to handle GET request to /hi URL of host1, returns a different greeting message.\n   rg.GET(\"/hi\", func(c *gin.Context) {\n      c.String(http.StatusOK, \"Hi from host1\")\n   })\n}\n\n// defineHost2Routes sets up the routes specific to host2.com.\nfunc defineHost2Routes(rg *gin.RouterGroup) {\n   // Route to handle GET request to the root URL of host2, returns a greeting message.\n   rg.GET(\"/\", func(c *gin.Context) {\n      c.String(http.StatusOK, \"Hello from host2\")\n   })\n   // Route to handle GET request to /hi URL of host2, includes log statement and returns a greeting message.\n   rg.GET(\"/hi\", func(c *gin.Context) {\n      log.Println(\"Important stuff\")\n      c.String(http.StatusOK, \"Hi from host2\")\n   })\n}\n\n// init function sets up logging output to standard output.\nfunc init() {\n   log.SetOutput(os.Stdout)\n}\n\n// noRouteHandler defines behavior for unspecified routes, returning a not-found message.\nfunc noRouteHandler(c *gin.Context) {\n   c.String(http.StatusNotFound, \"No known route\")\n}\n\n// noRouteSpecifier applies a no-route handler for the Gin Engine.\nfunc noRouteSpecifier(_ string, r *gin.Engine) error {\n   r.NoRoute(noRouteHandler)\n   return nil\n}\n\n// main function initializes the Gin engine and sets up host-based routing.\nfunc main() {\n   r := gin.Default() // Create a new Gin Engine instance with default middleware.\n\n   // Define host-specific configurations using HostConfig structs.\n   hostConfigs := []hostroute.HostConfig{\n      {Host: \"host1.com\", Prefix: \"1\", RouterFactory: defineHost1Routes},\n      {Host: \"host2.com\", Prefix: \"2\", RouterFactory: defineHost2Routes},\n   }\n\n   // Define generic hosts to use the primary router without specialized sub-routes.\n   genericHosts := []string{\"host3.com\", \"host4.com\"}\n\n   // Set up host-based routes and handle any setup errors.\n   err := hostroute.SetupHostBasedRoutes(r, hostConfigs, genericHosts, true, noRouteSpecifier)\n   if err != nil {\n      log.Fatal(err) // Log fatal error if setup fails.\n   }\n\n   // Start the server on port 8080.\n   r.Run(\":8080\")\n}\n\n```\n\n## Configuration Options\n\n### `HostConfig`\nThe `HostConfig` struct is used to define the configuration for a specific host:\n- `Host`: The hostname for which the configuration is defined.\n- `Prefix`: A prefix to use for routes specific to this host when accessed on a generic host.\n- `RouterFactory` A function that defined the routes for this host.\n\n### Generic Hosts\nGeneric hosts are hosts that will have access to all routes defined in all the host configs and any others defined on the default router. This is useful for:\n- **Local Testing**: to be able to access all routes without changing the host. \n- **Consolidated Access**: Handle routes from multiple applications on a single host. For example:\n  - You have two applications hosted on one Go server: one at `application1.example.com` and the other at `application2.example.com`. However, you also want people to be able to access both applications by going to `example.com/application1` or `example.com/application2`.\n\n### Secure Against Unknown Hosts\nThe `secureAgainstUnknownHosts` boolean flag controls how the middleware handles requests from unknown hosts:\n- `true`: Requests from unknown hosts will receive a 404 Not Found Response. This is useful for securing your application against unexpected or unauthorized hosts.\n- `false`: Requests from unknown hosts will be passed through the primary router. This is useful if you want to catch and handle such requests manually.\n\n### Additional Host Config\nThis param is optional and allows for unlimited inputs. Each input should be a `func(*echo.Group) error`. This is meant for specifying functions that `SetupHostBasedRoutes` should run on every host group after creating it. Common use cases of this are:\n- Configuring a `NoRoute` Handler.\n- Configuring Host Specific Middleware. This can be done in the `HostConfig` in the `RouterFactory`. Alternatively, it could be done here. This may be useful if you want to centralize a lot of the host-specific middleware.\n\n### Handling Different Hosts\n\n1. **Host-specific Routes**:\n   Routes are defined uniquely for each host using a specific `RouterFactory`. The `HostConfig` struct includes the hostname, path prefix, and a function to define routes for that host.\n\n    ```go\n    hostConfigs := []hostroute.HostConfig{\n        {Host: \"host1.com\", Prefix: \"1\", RouterFactory: defineHost1Routes},\n        {Host: \"host2.com\", Prefix: \"2\", RouterFactory: defineHost2Routes},\n    }\n    ```\n\n2. **Generic Hosts**:\n   Generic hosts allow for fallback to common routes defined in the primary router.\n\n    ```go\n    genericHosts := []string{\"host3.com\", \"host4.com\"}\n    ```\n\n3. **Secure Against Unknown Hosts**:\n   Secure your application by handling unknown hosts, preventing them from accessing unintended routes.\n\n    ```go\n    hostroute.SetupHostBasedRoutes(r, hostConfigs, genericHosts, true)\n    ```\n\n## Sister Project\nThis project has a sister project for Echo framework users. If you are using Echo, check out the [Echo Host Route Library](https://github.com/YidiDev/echo-host-route) for similar functionality.\n\n## Contributing\nContributions are always welcome! If you're interested in contributing to the project, please take a look at our [Contributing Guidelines](CONTRIBUTING.md) file for guidelines on how to get started. We appreciate your help in improving the library!\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fyididev%2Fgin-host-route","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fyididev%2Fgin-host-route","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fyididev%2Fgin-host-route/lists"}