apps

package
v12.2.10 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 18, 2024 License: BSD-3-Clause Imports: 7 Imported by: 2

README

The apps package

Package github.com/kataras/iris/v12/apps provides a globally scoped control over all registered Iris Applications of the same Program.

Example Application

Below you will find a use case for each feature.

The Get function

The Get function returns an Iris Application based on its "appName". It returns nil when no application was found with the given exact name.

If "appName" parameter is missing then it returns the last registered one. When no application is registered yet then it creates a new on-fly with a "Default" name and returns that instead. The "Default" one can be used across multiple Go packages of the same Program too.

Applications of the same program are registered automatically.

To check if at least one application is registered or not, use the GetAll() []*iris.Application function instead.

func Get(appName ...string) *iris.Application
Features
  • Access an Iris Application globally from all of your Go packages of the same Program without a global parameter and import cycle.
/* myserver/api/user.go */

package userapi

import (
	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/apps"
)

func init() {
	app := apps.Get()
	app.Get("/", list)
}

func list(ctx iris.Context) {
	// [...]
	ctx.WriteString("list users")
}
/* myserver/main.go */

package main

import (
	_ "myserver/api/user"

	"github.com/kataras/iris/v12/apps"
)

func main() {
	app := apps.Get()
	app.Listen(":80")
}

The empty _ import statement will call the userapi.init function (before main) which initializes an Iris Application, if not already exists, and registers it to the internal global store for further use across packages.

  • Reference one or more Iris Applications based on their names.

The Application.SetName method sets a unique name to this Iris Application. It sets a child prefix for the current Application's Logger. Its Application.String method returns the given name. It returns itself.

func (app *Application) SetName(appName string) *Application
/* myserver/main.go */

package main

import "github.com/kataras/iris/v12"

func main() {
    app := iris.New().SetName("app.company.com")
}
/* myserver/pkg/something.go */

package pkg

import "github.com/kataras/iris/v12/apps"

func DoSomething() {
    app := apps.Get("app.company.com")
}

The main function creates and registers an Iris Application on "app.company.com" name, after that declaration every package of the same Program can retrieve that specific Application instance through its name.

The Switch function

The Switch function returns a new Application with the sole purpose of routing the matched Applications through the "provided cases". Read below about the available SwitchProviders and how you can create and use your own one.

The cases are filtered in order of their registration.

func Switch(provider SwitchProvider, options ...SwitchOption) *iris.Application

Example Code:

switcher := Switch(Hosts{
	{Pattern: "mydomain.com", Target: app},
	{Pattern: "test.mydomain.com", Target: testSubdomainApp},
	{Pattern: "otherdomain.com", Target: "appName"},
})
switcher.Listen(":80")

Note that this is NOT an alternative for a load balancer. The filters are executed by registration order and a matched Application handles the request, that's all it does.

The returned Switch Iris Application can register routes that will run when neither of the registered Applications is responsible to handle the incoming request against the provided filters.

The returned Switch Iris Application can also register custom error code handlers, e.g. to inject the 404 on not responsible Application was found. It can also be wrapped with its WrapRouter method, which is really useful for logging and statistics.

The SwitchProvider interface

This is the first required input argument for the Switch function.

A SwitchProvider should return one or more SwitchCase values.

type SwitchProvider interface {
	GetSwitchCases() []SwitchCase
}

The SwitchCase structure contains the Filter and the target Iris Application.

type SwitchCase struct {
	Filter func(ctx iris.Context) bool
	App    *iris.Application
}
The SwitchOptions structure

This is the last variadic (optional) input argument for the Switch function.

type SwitchOptions struct {
	// RequestModifiers holds functions to run
	// if and only if at least one Filter passed.
	// They are used to modify the request object
	// of the matched Application, e.g. modify the host.
	//
	// See `SetHost` option too.
	RequestModifiers []func(*http.Request)
}

The SetHost function is a SwitchOption. It force sets a Host field for the matched Application's request object. Extremely useful when used with Hosts SwitchProvider. Usecase: www. to root domain without redirection (SEO reasons) and keep the same internal request Host for both of them so the root app's handlers will always work with a single host no matter what the real request Host was.

func SetHost(hostField string) SwitchOptionFunc

Example Code:

cases := Hosts{
	{"^(www.)?mydomain.com$", rootApp},
}
switcher := Switch(cases, SetHost("mydomain.com"))
Join different type of SwitchProviders

Wrap with the Join slice to pass more than one provider at the same time.

Example Code:

Switch(Join{
	SwitchCase{
		Filter: customFilter,
		App:    myapp,
	},
	Hosts{
		{Pattern: "^test.*$", Target: myapp},
	},
})

Documentation

Overview

Package apps is responsible to control many Iris Applications. This package directly imports the iris root package and cannot be used inside Iris' codebase itself. Only external packages/programs can make use of it.

Index

Constants

View Source
const AnyDomain = `` /* 183-byte string literal not displayed */

AnyDomain is a regexp that matches any domain. It can be used as the Pattern field of a Host.

Example:

apps.Switch(apps.Hosts{
	{
		Pattern: "^id.*$", Target: identityApp,
	},
	{
		Pattern: apps.AnyDomain, Target: app,
	},
}).Listen(":80")

Variables

View Source
var HostsRedirectCode = iris.StatusMovedPermanently

HostsRedirectCode is the default status code is used to redirect a matching host to a url.

Functions

func Get

func Get(appName ...string) *iris.Application

Get returns an Iris Application based on its "appName". It returns nil when no application was found with the given exact name.

If "appName" parameter is missing then it returns the last registered one. When no application is registered yet then it creates a new on-fly with a "Default" name and returns that instead. The "Default" one can be used across multiple Go packages of the same Program too.

Applications of the same program are registered automatically.

To check if at least one application is registered or not use the `GetAll` function instead.

func GetAll

func GetAll() []*iris.Application

GetAll returns a slice of all registered Iris Applications.

func OnApplicationRegistered

func OnApplicationRegistered(listeners ...func(app *iris.Application))

OnApplicationRegistered adds a function which fires when a new application is registered.

func Switch

func Switch(provider SwitchProvider, options ...SwitchOption) *iris.Application

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", Target: testSubdomainApp },
	{ Pattern: "otherdomain.com", "Target: appName" },
})
switcher.Listen(":80")

Note that this is NOT an alternative for a load balancer. The filters are executed by registration order and a matched Application handles the request, that's all it does.

The returned Switch Iris Application can register routes that will run when neither of the registered Applications is responsible to handle the incoming request against the provided filters. The returned Switch Iris Application can also register custom error code handlers, e.g. to inject the 404 on not responsible Application was found. It can also be wrapped with its `WrapRouter` method, which is really useful for logging and statistics.

Wrap with the `Join` slice to pass more than one provider at the same time.

An alternative way for manually embedding an Iris Application to another one is:

app := iris.New() // root app.
myOtherApp := api.NewServer(otherServerConfiguration) // embedded app.
// myOtherApp.Logger().SetLevel("debug")

if err := myOtherApp.Build(); err != nil {
	panic(err)
}

app.Any("/api/identity/{p:path}", func(ctx iris.Context) {
	apiPath := "/" + ctx.Params().Get("p")
	r := ctx.Request()
	r.URL.Path = apiPath
	r.URL.RawPath = apiPath
	ctx.Params().Remove("p")

	myOtherApp.ServeHTTPC(ctx)
})

app.Listen(":80")

Types

type FriendlyNameProvider

type FriendlyNameProvider interface {
	GetFriendlyName() string
}

FriendlyNameProvider can be optionally implemented by providers to customize the Switcher's Supervisor.FriendlyAddr field (Startup log).

type Host

type Host struct {
	// Pattern is the incoming host matcher regexp or a literal.
	Pattern string
	// Target is the target Host that incoming requests will be redirected on pattern match
	// or an Application's Name that will handle the incoming request matched the Pattern.
	Target interface{} // It was a string in my initial design but let's do that interface{}, we may support more types here in the future, until generics are in, keep it interface{}.
}

Host holds the pattern for the SwitchCase filter and the Target host or application.

type Hosts

type Hosts []Host

Hosts is a switch provider. It can be used as input argument to the `Switch` function to map host to existing Iris Application instances, e.g. { "www.mydomain.com": "mydomainApp" } . It can accept regexp as a host too, e.g. { "^my.*$": "mydomainApp" } .

func (Hosts) GetFriendlyName

func (hosts Hosts) GetFriendlyName() string

GetFriendlyName implements the FriendlyNameProvider.

func (Hosts) GetSwitchCases

func (hosts Hosts) GetSwitchCases() []SwitchCase

GetSwitchCases completes the SwitchProvider. It returns a slice of SwitchCase which if passed on `Switch` function, they act as a router between matched domains and subdomains between existing Iris Applications.

type Join

type Join []SwitchProvider

Join returns a new slice which joins different type of switch cases.

func (Join) GetSwitchCases

func (j Join) GetSwitchCases() (cases []SwitchCase)

GetSwitchCases completes the switch provider.

type SwitchCase

type SwitchCase struct {
	Filter iris.Filter       // Filter runs against the Switcher.
	App    *iris.Application // App is the main target application responsible to handle the request.
}

SwitchCase contains the filter and the matched Application instance.

func (SwitchCase) GetSwitchCases

func (sc SwitchCase) GetSwitchCases() []SwitchCase

GetSwitchCases completes the SwitchProvider, it returns itself.

type SwitchOption

type SwitchOption interface {
	Apply(*SwitchOptions)
}

SwitchOption should be implemented by all options passed to the `Switch` package-level last variadic input argument.

type SwitchOptionFunc

type SwitchOptionFunc func(*SwitchOptions)

SwitchOptionFunc provides a functional way to pass options to the `Switch` package-level function's last variadic input argument.

func SetHost

func SetHost(hostField string) SwitchOptionFunc

SetHost is a SwitchOption. It force sets a Host field for the matched Application's request object. Extremely useful when used with Hosts SwitchProvider. Usecase: www. to root domain without redirection (SEO reasons) and keep the same internal request Host for both of them so the root app's handlers will always work with a single host no matter what the real request Host was.

func (SwitchOptionFunc) Apply

func (f SwitchOptionFunc) Apply(opts *SwitchOptions)

Apply completes the `SwitchOption` interface.

type SwitchOptions

type SwitchOptions struct {
	// RequestModifiers holds functions to run
	// if and only if at least one Filter passed.
	// They are used to modify the request object
	// of the matched Application, e.g. modify the host.
	//
	// See `SetHost` option too.
	RequestModifiers []func(*http.Request)
}

SwitchOptions holds configuration for the switcher application.

func DefaultSwitchOptions

func DefaultSwitchOptions() SwitchOptions

DefaultSwitchOptions returns a fresh SwitchOptions struct value with its fields set to their defaults.

func (SwitchOptions) Apply

func (o SwitchOptions) Apply(opts *SwitchOptions)

Apply completes the `SwitchOption` interface. It does copies values from "o" to "opts" when necessary.

type SwitchProvider

type SwitchProvider interface {
	GetSwitchCases() []SwitchCase
}

A SwitchProvider should return the switch cases. It's an interface instead of a direct slice because we want to make available different type of structures without wrapping.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL