Skip to content

Commit

Permalink
Merge pull request #3 from YidiDev/dev
Browse files Browse the repository at this point in the history
Dev
  • Loading branch information
YidiDev authored Sep 19, 2024
2 parents 52ecd10 + dd50a8c commit 369d7b2
Show file tree
Hide file tree
Showing 4 changed files with 195 additions and 169 deletions.
158 changes: 61 additions & 97 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Host Route Library

A high-performance Echo middleware library for routing based on the host.
A high-performance Echo 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.

## Installation

Expand All @@ -12,65 +12,81 @@ go get github.com/YidiDev/echo-host-route

## Usage

Below is an example of how to utilize the library to define different routes based on the host.
The following example demonstrates how to use the library to define various routes based on the host name. This helps in setting up multiple applications or APIs served from the same server, each with its specific routing configuration.

### Example

```go
package main

import (
"github.com/labstack/echo/v4"
"github.com/YidiDev/echo-host-route"
"log"
"net/http"
"os"
"github.com/YidiDev/echo-host-route"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
"log"
"net/http"
"os"
)

func defineHost1Routes(rg *echo.Group) {
rg.GET("/", func(c echo.Context) error {
return c.String(http.StatusOK, "Hello from host1")
})
rg.GET("/hi", func(c echo.Context) error {
return c.String(http.StatusOK, "Hi from host1")
})
// defineHost1Routes sets up the routes specific to host1.com.
func defineHost1Routes(group *echo.Group) {
// Route to handle request to root URL of host1, returns greeting message.
group.GET("/", func(c echo.Context) error {
return c.String(http.StatusOK, "Hello from host1")
})
// Route to handle request to /hi URL of host1, returns a different greeting message.
group.GET("/hi", func(c echo.Context) error {
return c.String(http.StatusOK, "Hi from host1")
})
}

func defineHost2Routes(rg *echo.Group) {
rg.GET("/", func(c echo.Context) error {
return c.String(http.StatusOK, "Hello from host2")
})
rg.GET("/hi", func(c echo.Context) error {
return c.String(http.StatusOK, "Hi from host2")
})
// defineHost2Routes sets up the routes specific to host2.com.
func defineHost2Routes(group *echo.Group) {
// Route to handle request to root URL of host2, returns greeting message.
group.GET("/", func(c echo.Context) error {
return c.String(http.StatusOK, "Hello from host2")
})
// Route to handle request to /hi URL of host2, includes log statement and returns a greeting message.
group.GET("/hi", func(c echo.Context) error {
log.Println("Important stuff")
return c.String(http.StatusOK, "Hi from host2")
})
}

// routeNotFoundSpecifier defines behavior for unspecified routes.
func routeNotFoundSpecifier(group *echo.Group) error {
// Route handler for unspecified routes, returns a not-found message.
group.RouteNotFound("/*", func(c echo.Context) error {
return c.String(http.StatusNotFound, "No known route")
})
return nil
}

// init function sets up logging output to standard output.
func init() {
log.SetOutput(os.Stdout)
log.SetOutput(os.Stdout)
}

// main function initializes the Echo instance and sets up host-based routing.
func main() {
r := echo.New()
e := echo.New() // Create a new Echo instance.
e.Use(middleware.Recover()) // Middleware to recover from panics.

// 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"}
hostConfigs := []hostroute.HostConfig{
{Host: "host1.com", Prefix: "1", RouterFactory: defineHost1Routes},
{Host: "host2.com", Prefix: "2", RouterFactory: defineHost2Routes},
}

// Setup host-based routes
hostroute.SetupHostBasedRoutes(r, hostConfigs, genericHosts, true)
genericHosts := []string{"host3.com", "host4.com"}

// Define handler for unmatched routes
r.RouteNotFound("/*", func(c echo.Context) error {
return c.String(http.StatusNotFound, "No known route")
})
// Setup host-based routes and handle any errors during setup.
err := hostroute.SetupHostBasedRoutes(e, hostConfigs, genericHosts, true, routeNotFoundSpecifier)
if err != nil {
log.Fatal(err) // Log fatal error if setup fails.
}

// Start the server
r.Start(":8080")
// Start the server on port 8080.
e.Start(":8080")
}
```

Expand All @@ -80,7 +96,7 @@ func main() {
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.
- `RouterFactory`: A function that sets up routing for this host, taking an `*echo.Group` instance to define its routes.

### 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:
Expand All @@ -93,64 +109,12 @@ The `secureAgainstUnknownHosts` boolean flag controls how the middleware handles
- `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/labstack/echo/v4"
"github.com/YidiDev/echo-host-route"
"log"
"net/http"
"os"
)

func defineHost1Routes(rg *echo.Group) {
rg.GET("/", func(c echo.Context) error {
return c.String(http.StatusOK, "Hello from host1")
})
rg.GET("/hi", func(c echo.Context) error {
return c.String(http.StatusOK, "Hi from host1")
})
}

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

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

func main() {
r := echo.New()

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.RouteNotFound("/*", func(c echo.Context) error {
return c.String(http.StatusNotFound, "No known route")
})

r.Start(":8080")

}
```
### Additional Host Config
This 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:
- Configuring a `RouteNotFound` Handler.
- 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.

### Handling Different Hosts
## 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.
Expand Down
33 changes: 25 additions & 8 deletions example/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,32 +9,49 @@ import (
"os"
)

// defineHost1Routes sets up the routes specific to host1.com.
func defineHost1Routes(group *echo.Group) {
// Route to handle request to root URL of host1, returns greeting message.
group.GET("/", func(c echo.Context) error {
return c.String(http.StatusOK, "Hello from host1")
})
// Route to handle request to /hi URL of host1, returns a different greeting message.
group.GET("/hi", func(c echo.Context) error {
return c.String(http.StatusOK, "Hi from host1")
})
}

// defineHost2Routes sets up the routes specific to host2.com.
func defineHost2Routes(group *echo.Group) {
// Route to handle request to root URL of host2, returns greeting message.
group.GET("/", func(c echo.Context) error {
return c.String(http.StatusOK, "Hello from host2")
})
// Route to handle request to /hi URL of host2, includes log statement and returns a greeting message.
group.GET("/hi", func(c echo.Context) error {
log.Println("Important stuff")
return c.String(http.StatusOK, "Hi from host2")
})
}

// routeNotFoundSpecifier defines behavior for unspecified routes.
func routeNotFoundSpecifier(group *echo.Group) error {
// Route handler for unspecified routes, returns a not-found message.
group.RouteNotFound("/*", func(c echo.Context) error {
return c.String(http.StatusNotFound, "No known route")
})
return nil
}

// init function sets up logging output to standard output.
func init() {
log.SetOutput(os.Stdout)
}

// main function initializes the Echo instance and sets up host-based routing.
func main() {
e := echo.New()
e.Use(middleware.Recover())
e := echo.New() // Create a new Echo instance.
e.Use(middleware.Recover()) // Middleware to recover from panics.

hostConfigs := []hostroute.HostConfig{
{Host: "host1.com", Prefix: "1", RouterFactory: defineHost1Routes},
Expand All @@ -43,12 +60,12 @@ func main() {

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

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

e.RouteNotFound("/*", func(c echo.Context) error {
return c.String(http.StatusNotFound, "No known route")
})
// Setup host-based routes and handle any errors during setup.
err := hostroute.SetupHostBasedRoutes(e, hostConfigs, genericHosts, true, routeNotFoundSpecifier)
if err != nil {
log.Fatal(err) // Log fatal error if setup fails.
}

// Start the server on port 8080.
e.Start(":8080")
}
78 changes: 53 additions & 25 deletions hostroute.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,54 +6,82 @@ import (
"net/http"
)

// HostConfig holds the configuration for each host.
type HostConfig struct {
Host string
Prefix string
RouterFactory func(e *echo.Group)
Host string // The specific hostname (e.g., "host1.com").
Prefix string // Prefix for route paths (e.g., "1" or "2").
RouterFactory func(e *echo.Group) // Function to define routes for the host.
}

func createHostBasedRoutingMiddleware(hostConfigMap map[string]*HostConfig, genericHosts map[string]bool, secureAgainstUnknownHosts bool) echo.MiddlewareFunc {
// SecureAgainstUnknownHosts returns a middleware function to secure the server against requests from unknown hosts.
func SecureAgainstUnknownHosts(knownHosts map[string]bool) echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
host := c.Request().Host

if _, exists := hostConfigMap[host]; exists {
return next(c)
}

if _, exists := genericHosts[host]; exists {
return next(c)
}

if secureAgainstUnknownHosts {
if _, known := knownHosts[host]; !known {
// If host is not recognized, return a 404 Not Found response.
return c.String(http.StatusNotFound, "Unknown host")
}

return next(c)
}
}
}

func SetupHostBasedRoutes(e *echo.Echo, hostConfigs []HostConfig, genericHosts []string, secureAgainstUnknownHosts bool) {
hostConfigMap := make(map[string]*HostConfig)
genericHostsMap := stringSliceToMap(genericHosts)
// SetupHostBasedRoutes configures routing based on hostnames.
func SetupHostBasedRoutes(e *echo.Echo, hostConfigs []HostConfig, genericHosts []string, secureAgainstUnknownHosts bool, additionalHostConfig ...func(*echo.Group) error) error {
var allHosts []string

for _, hostConfig := range hostConfigs {
hostGroup := e.Host(hostConfig.Host) // Create a host-specific route group
hostConfig.RouterFactory(hostGroup) // Set up routes using the provided factory function
if secureAgainstUnknownHosts {
allHosts = append(allHosts, hostConfig.Host) // Keep track of known hosts
}
if len(additionalHostConfig) > 0 {
for _, config := range additionalHostConfig {
err := config(hostGroup) // Apply additional configurations if provided
if err != nil {
return err // Return on error
}
}
}
}

for _, genericHost := range genericHosts {
genericGroup := e.Host(genericHost) // Create a group for generic hosts

for i := range hostConfigs {
group := e.Host(hostConfigs[i].Host)
hostConfigs[i].RouterFactory(group)
for _, hostConfig := range hostConfigs {
if hostConfig.Prefix != "" {
// Create prefixed routes for generic hosts
prefixedGroup := genericGroup.Group(fmt.Sprintf("/%s", hostConfig.Prefix))
hostConfig.RouterFactory(prefixedGroup) // Set up routes for each prefix
}
}

if hostConfigs[i].Prefix != "" {
group = e.Group(fmt.Sprintf("/%s", hostConfigs[i].Prefix))
hostConfigs[i].RouterFactory(group)
if secureAgainstUnknownHosts {
allHosts = append(allHosts, genericHost) // Track generic known hosts
}

hostConfigMap[hostConfigs[i].Host] = &hostConfigs[i]
if len(additionalHostConfig) > 0 {
for _, config := range additionalHostConfig {
err := config(genericGroup) // Apply additional configurations
if err != nil {
return err // Return on error
}
}
}
}

e.Use(createHostBasedRoutingMiddleware(hostConfigMap, genericHostsMap, secureAgainstUnknownHosts))
if secureAgainstUnknownHosts {
// Apply the security middleware against unknown hosts
e.Use(SecureAgainstUnknownHosts(stringSliceToMap(allHosts)))
}

return nil
}

// stringSliceToMap converts a slice of strings to a map with the string as the key and true as the value.
func stringSliceToMap(slice []string) map[string]bool {
result := make(map[string]bool)
for _, s := range slice {
Expand Down
Loading

0 comments on commit 369d7b2

Please sign in to comment.