Skip to content

Commit

Permalink
first commit
Browse files Browse the repository at this point in the history
  • Loading branch information
YidiDev committed Sep 1, 2024
0 parents commit 3616fc6
Show file tree
Hide file tree
Showing 8 changed files with 658 additions and 0 deletions.
56 changes: 56 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
# Go related
/bin/
/pkg/
*.exe
*.exe~
*.dll
*.so
*.dylib
*.test
*.out

# Go vendor directory
vendor/

# Mac related
.DS_Store

# Windows related
Thumbs.db
Desktop.ini

# GoLand IDE related files
.idea/
*.iml
*.log
*.hprof
/out/

# IDE directories
.vscode/
*.sublime-workspace

# Ignore editor swap files
*~
# Support for IntelliJ caching
/.idea/
# Support for .env files
.env
/.env.local
/.env.development.local
/.env.test.local
/.env.qa.local

# GoLand version-specific
/workspace.xml
/tasks.xml
/taskDescriptions.xml
/usage.statistics.xml
/gradle.xml
/jarRepositories.xml
# Rope project settings
.settings/
/project/
/.Rproj.user/
/.vscode/*
.Rproj.user/
7 changes: 7 additions & 0 deletions LICENSE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
Copyright 2024 Yidi Sprei

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
176 changes: 176 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,176 @@
# Host Route Library

A high-performance Gin middleware library for routing based on the host.

## Installation

Add the module to your project by running:

```sh
go get github.com/YidiDev/gin-host-route
```

## Usage

Below is an example of how to utilize the library to define different routes based on the host.

### Example

```go
package main

import (
"github.com/gin-gonic/gin"
"github.com/YidiDev/gin-host-route"
"log"
"net/http"
"os"
)

func defineHost1Routes(rg *gin.RouterGroup) {
rg.GET("/", func(c *gin.Context) {
c.String(http.StatusOK, "Hello from host1")
})
rg.GET("/hi", func(c *gin.Context) {
c.String(http.StatusOK, "Hi from host1")
})
}

func defineHost2Routes(rg *gin.RouterGroup) {
rg.GET("/", func(c *gin.Context) {
c.String(http.StatusOK, "Hello from host2")
})
rg.GET("/hi", func(c *gin.Context) {
c.String(http.StatusOK, "Hi from host2")
})
}

func init() {
log.SetOutput(os.Stdout)
}

func main() {
r := gin.Default()

// Define host-specific configurations
hostConfigs := []hostroute.HostConfig{
{Host: "host1.com", Prefix: "1", RouterFactory: defineHost1Routes},
{Host: "host2.com", Prefix: "2", RouterFactory: defineHost2Routes},
}

// Generic hosts are hosts that will use the primary router without special sub-routes
genericHosts := []string{"host3.com", "host4.com"}

// Setup host-based routes
hostroute.SetupHostBasedRoutes(r, hostConfigs, genericHosts, true)

// Define handler for unmatched routes
r.NoRoute(func(c *gin.Context) {
c.String(http.StatusNotFound, "No known route")
})

// Start the server
r.Run(":8080")
}
```

## Configuration Options

### `HostConfig`
The `HostConfig` struct is used to define the configuration for a specific host:
- `Host`: The hostname for which the configuration is defined.
- `Prefix`: A prefix to use for routes specific to this host when accessed on a generic host.
- `RouterFactory` A function that defined the routes for this host.

### Generic Hosts
Generic 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:
- **Local Testing**: to be able to access all routes without changing the host.
- **Consolidated Access**: Handle routes from multiple applications on a single host. For example:
- 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`.

### Secure Against Unknown Hosts
The `secureAgainstUnknownHosts` boolean flag controls how the middleware handles requests from unknown hosts:
- `true`: Requests from unknown hosts will receive a 404 Not Found Response. This is useful for securing your application against unexpected or unauthorized hosts.
- `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.

### Route Configuration Example

```go
package main

import (
"github.com/gin-gonic/gin"
"github.com/YidiDev/gin-host-route"
"log"
"net/http"
"os"
)

func defineHost1Routes(rg *gin.RouterGroup) {
rg.GET("/", func(c *gin.Context) {
c.String(http.StatusOK, "Hello from host1")
})
rg.GET("/hi", func(c *gin.Context) {
c.String(http.StatusOK, "Hi from host1")
})
}

func defineHost2Routes(rg *gin.RouterGroup) {
rg.GET("/", func(c *gin.Context) {
c.String(http.StatusOK, "Hello from host2")
})
rg.GET("/hi", func(c *gin.Context) {
log.Println("Important stuff")
c.String(http.StatusOK, "Hi from host2")
})
}

func init() {
log.SetOutput(os.Stdout)
}

func main() {
r := gin.Default()

hostConfigs := []hostroute.HostConfig{
{Host: "host1.com", Prefix: "1", RouterFactory: defineHost1Routes},
{Host: "host2.com", Prefix: "2", RouterFactory: defineHost2Routes},
}

genericHosts := []string{"host3.com", "host4.com"}

hostroute.SetupHostBasedRoutes(r, hostConfigs, genericHosts, true)

r.NoRoute(func(c *gin.Context) {
c.String(http.StatusNotFound, "No known route")
})

r.Run(":8080")
}
```

### Handling Different Hosts

1. **Host-specific Routes**:
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.

```go
hostConfigs := []hostroute.HostConfig{
{Host: "host1.com", Prefix: "1", RouterFactory: defineHost1Routes},
{Host: "host2.com", Prefix: "2", RouterFactory: defineHost2Routes},
}
```

2. **Generic Hosts**:
Generic hosts allow for fallback to common routes defined in the primary router.

```go
genericHosts := []string{"host3.com", "host4.com"}
```

3. **Secure Against Unknown Hosts**:
Secure your application by handling unknown hosts, preventing them from accessing unintended routes.

```go
hostroute.SetupHostBasedRoutes(r, hostConfigs, genericHosts, true)
```
51 changes: 51 additions & 0 deletions example/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package main

import (
"github.com/YidiDev/gin-host-route"
"github.com/gin-gonic/gin"
"log"
"net/http"
"os"
)

func defineHost1Routes(rg *gin.RouterGroup) {
rg.GET("/", func(c *gin.Context) {
c.String(http.StatusOK, "Hello from host1")
})
rg.GET("/hi", func(c *gin.Context) {
c.String(http.StatusOK, "Hi from host1")
})
}

func defineHost2Routes(rg *gin.RouterGroup) {
rg.GET("/", func(c *gin.Context) {
c.String(http.StatusOK, "Hello from host2")
})
rg.GET("/hi", func(c *gin.Context) {
log.Println("Important stuff")
c.String(http.StatusOK, "Hi from host2")
})
}

func init() {
log.SetOutput(os.Stdout)
}

func main() {
r := gin.Default()

hostConfigs := []hostroute.HostConfig{
{Host: "host1.com", Prefix: "1", RouterFactory: defineHost1Routes},
{Host: "host2.com", Prefix: "2", RouterFactory: defineHost2Routes},
}

genericHosts := []string{"host3.com", "host4.com"}

hostroute.SetupHostBasedRoutes(r, hostConfigs, genericHosts, true)

r.NoRoute(func(c *gin.Context) {
c.String(http.StatusNotFound, "No known route")
})

r.Run(":8080")
}
39 changes: 39 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
module github.com/YidiDev/gin-host-route

go 1.23.0

require (
github.com/gin-gonic/gin v1.10.0
github.com/stretchr/testify v1.9.0
)

require (
github.com/bytedance/sonic v1.11.6 // indirect
github.com/bytedance/sonic/loader v0.1.1 // indirect
github.com/cloudwego/base64x v0.1.4 // indirect
github.com/cloudwego/iasm v0.2.0 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/gabriel-vasile/mimetype v1.4.3 // indirect
github.com/gin-contrib/sse v0.1.0 // indirect
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/go-playground/validator/v10 v10.20.0 // indirect
github.com/goccy/go-json v0.10.2 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/cpuid/v2 v2.2.7 // indirect
github.com/leodido/go-urn v1.4.0 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/pelletier/go-toml/v2 v2.2.2 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
github.com/ugorji/go/codec v1.2.12 // indirect
golang.org/x/arch v0.8.0 // indirect
golang.org/x/crypto v0.23.0 // indirect
golang.org/x/net v0.25.0 // indirect
golang.org/x/sys v0.20.0 // indirect
golang.org/x/text v0.15.0 // indirect
google.golang.org/protobuf v1.34.1 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
Loading

0 comments on commit 3616fc6

Please sign in to comment.