1
0
mirror of https://github.com/kataras/iris.git synced 2025-12-17 09:57:01 +00:00

apps.Switch(apps.Hosts...) example

This commit is contained in:
Gerasimos (Makis) Maropoulos
2020-08-18 04:17:53 +03:00
parent 589c8c6242
commit 5481b9a6c1
19 changed files with 164 additions and 114 deletions

View File

@@ -1,6 +1,8 @@
package apps
import (
"strings"
"github.com/kataras/iris/v12"
)
@@ -33,11 +35,18 @@ func Switch(providers ...SwitchProvider) *iris.Application {
panic("iris: switch: empty providers")
}
var friendlyAddrs []string
var cases []SwitchCase
for _, p := range providers {
for _, c := range p.GetSwitchCases() {
cases = append(cases, c)
}
if fp, ok := p.(FriendlyNameProvider); ok {
if friendlyName := fp.GetFriendlyName(); friendlyName != "" {
friendlyAddrs = append(friendlyAddrs, friendlyName)
}
}
}
if len(cases) == 0 {
@@ -61,7 +70,7 @@ func Switch(providers ...SwitchProvider) *iris.Application {
app.UseRouter(func(ctx iris.Context) {
for _, c := range cases {
if c.Filter(ctx) {
c.App.ServeHTTP(ctx.ResponseWriter().Naive(), ctx.Request())
c.App.ServeHTTP(ctx.ResponseWriter(), ctx.Request())
// if c.App.Downgraded() {
// c.App.ServeHTTP(ctx.ResponseWriter(), ctx.Request())
@@ -81,6 +90,12 @@ func Switch(providers ...SwitchProvider) *iris.Application {
ctx.Next()
})
// Configure the switcher's supervisor.
app.ConfigureHost(func(su *iris.Supervisor) {
if len(friendlyAddrs) > 0 {
su.FriendlyAddr = strings.Join(friendlyAddrs, ", ")
}
})
return app
}
@@ -88,8 +103,8 @@ type (
// SwitchCase contains the filter
// and the matched Application instance.
SwitchCase struct {
Filter iris.Filter
App *iris.Application
Filter iris.Filter // Filter runs against the Switcher.
App *iris.Application // App is the main target application responsible to handle the request.
}
// A SwitchProvider should return the switch cases.
@@ -100,6 +115,12 @@ type (
GetSwitchCases() []SwitchCase
}
// FriendlyNameProvider can be optionally implemented by providers
// to customize the Switcher's Supervisor.FriendlyAddr field (Startup log).
FriendlyNameProvider interface {
GetFriendlyName() string
}
// Join returns a new slice which joins different type of switch cases.
Join []SwitchProvider
)

View File

@@ -5,6 +5,7 @@ import (
"net/http"
"net/url"
"regexp"
"strings"
"github.com/kataras/iris/v12"
"github.com/kataras/iris/v12/context"
@@ -53,6 +54,18 @@ func (hosts Hosts) GetSwitchCases() []SwitchCase {
return cases
}
// GetFriendlyName implements the FriendlyNameProvider.
func (hosts Hosts) GetFriendlyName() string {
var patterns []string
for _, host := range hosts {
if strings.TrimSpace(host.Pattern) != "" {
patterns = append(patterns, host.Pattern)
}
}
return strings.Join(patterns, ", ")
}
func hostApp(host Host) *iris.Application {
if host.Target == nil {
return nil