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)
| 58 | // |
| 59 | // app.Listen(":80") |
| 60 | func 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 |
searching dependent graphs…