MCPcopy Create free account
hub / github.com/kataras/iris / Switch

Function Switch

apps/switch.go:60–133  ·  view source on GitHub ↗

Switch returns a new Application with the sole purpose of routing the matched Applications through the "provided cases". The cases are filtered in order of their registration. Example Code: switcher := Switch(Hosts{ { Pattern: "mydomain.com", Target: app }, { Pattern: "test.mydomain.com", Ta

(provider SwitchProvider, options ...SwitchOption)

Source from the content-addressed store, hash-verified

58//
59// app.Listen(":80")
60func Switch(provider SwitchProvider, options ...SwitchOption) *iris.Application {
61 cases := provider.GetSwitchCases()
62 if len(cases) == 0 {
63 panic("iris: switch: empty cases")
64 }
65
66 var friendlyAddrs []string
67 if fp, ok := provider.(FriendlyNameProvider); ok {
68 if friendlyName := fp.GetFriendlyName(); friendlyName != "" {
69 friendlyAddrs = append(friendlyAddrs, friendlyName)
70 }
71 }
72
73 opts := DefaultSwitchOptions()
74 for _, opt := range options {
75 if opt == nil {
76 continue
77 }
78
79 opt.Apply(&opts)
80 }
81
82 app := iris.New()
83 // Try to build the cases apps on app.Build/Listen/Run so
84 // end-developers don't worry about it.
85 app.OnBuild = func() error {
86 for _, c := range cases {
87 if err := c.App.Build(); err != nil {
88 return err
89 }
90 }
91 return nil
92 }
93 // If we have a request to support
94 // middlewares in that switcher app then
95 // we can use app.Get("{p:path}"...) instead.
96 app.UseRouter(func(ctx iris.Context) {
97 for _, c := range cases {
98 if c.Filter(ctx) {
99 w := ctx.ResponseWriter()
100 r := ctx.Request()
101
102 for _, reqMod := range opts.RequestModifiers {
103 reqMod(r)
104 }
105
106 c.App.ServeHTTP(w, r)
107
108 // if c.App.Downgraded() {
109 // c.App.ServeHTTP(w, r)
110 // } else {
111 // Note(@kataras): don't ever try something like that;
112 // the context pool is the switcher's one.
113 // ctx.SetApplication(c.App)
114 // c.App.ServeHTTPC(ctx)
115 // ctx.SetApplication(app)
116 // }
117 return

Callers 4

mainFunction · 0.92
TestSetHostFunction · 0.85
TestSwitchHostsFunction · 0.85
TestSwitchHostsRedirectFunction · 0.85

Calls 13

DefaultSwitchOptionsFunction · 0.85
NewMethod · 0.80
FilterMethod · 0.80
ResponseWriterMethod · 0.80
RequestMethod · 0.80
NextMethod · 0.80
ConfigureHostMethod · 0.80
GetSwitchCasesMethod · 0.65
GetFriendlyNameMethod · 0.65
ApplyMethod · 0.65
BuildMethod · 0.65
UseRouterMethod · 0.65

Tested by 3

TestSetHostFunction · 0.68
TestSwitchHostsFunction · 0.68
TestSwitchHostsRedirectFunction · 0.68

Used in the wild real call sites across dependent graphs

searching dependent graphs…