router

package
v12.2.0-alpha Latest Latest
Warning

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

Go to latest
Published: Sep 13, 2020 License: BSD-3-Clause Imports: 33 Imported by: 48

Documentation

Index

Constants

View Source
const (
	// SubdomainWildcardIndicator where a registered path starts with '*.'.
	// if subdomain == "*." then its wildcard.
	//
	// used internally by router and api builder.
	SubdomainWildcardIndicator = "*."

	// SubdomainWildcardPrefix where a registered path starts with "*./",
	// then this route should accept any subdomain.
	SubdomainWildcardPrefix = SubdomainWildcardIndicator + "/"
	// SubdomainPrefix where './' exists in a registered path then it contains subdomain
	//
	// used on api builder.
	SubdomainPrefix = "./" // i.e subdomain./ -> Subdomain: subdomain. Path: /
)
View Source
const (
	// ParamStart the character in string representation where the underline router starts its dynamic named parameter.
	ParamStart = ":"
	// WildcardParamStart the character in string representation where the underline router starts its dynamic wildcard
	// path parameter.
	WildcardParamStart = "*"
)
View Source
const MethodNone = "NONE"

MethodNone is a Virtual method to store the "offline" routes.

Variables

AllMethods contains the valid HTTP Methods: "GET", "POST", "PUT", "DELETE", "CONNECT", "HEAD", "PATCH", "OPTIONS", "TRACE".

View Source
var DefaultDirOptions = DirOptions{
	IndexName:         indexName,
	PushTargets:       make(map[string][]string),
	PushTargetsRegexp: make(map[string]*regexp.Regexp),
	Cache: DirCacheOptions{

		Enable: false,

		CompressMinSize: 300,

		Encodings: context.AllEncodings,

		Verbose: 1,
	},
	Compress: true,
	ShowList: false,
	DirList: DirListRich(DirListRichOptions{
		Tmpl:     DirListRichTemplate,
		TmplName: "dirlist",
	}),
	Attachments: Attachments{
		Enable: false,
		Limit:  0,
		Burst:  0,
	},
	AssetValidator: nil,
}

DefaultDirOptions holds the default settings for `FileServer`.

View Source
var DirListRichTemplate = template.Must(template.New("dirlist").
	Funcs(template.FuncMap{
		"formatBytes": FormatBytes,
	}).Parse(`
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>{{.Title}}</title>
    <style>
        a {
            padding: 8px 8px;
            text-decoration:none;
            cursor:pointer;
            color: #10a2ff;
        }
        table {
            position: absolute;
            top: 0;
            bottom: 0;
            left: 0;
            right: 0;
            height: 100%;
            width: 100%;
            border-collapse: collapse;
            border-spacing: 0;
            empty-cells: show;
            border: 1px solid #cbcbcb;
        }
        
        table caption {
            color: #000;
            font: italic 85%/1 arial, sans-serif;
            padding: 1em 0;
            text-align: center;
        }
        
        table td,
        table th {
            border-left: 1px solid #cbcbcb;
            border-width: 0 0 0 1px;
            font-size: inherit;
            margin: 0;
            overflow: visible;
            padding: 0.5em 1em;
        }
        
        table thead {
            background-color: #10a2ff;
            color: #fff;
            text-align: left;
            vertical-align: bottom;
        }
        
        table td {
            background-color: transparent;
        }

        .table-odd td {
            background-color: #f2f2f2;
        }

        .table-bordered td {
            border-bottom: 1px solid #cbcbcb;
        }
        .table-bordered tbody > tr:last-child > td {
            border-bottom-width: 0;
        }
	</style>
</head>
<body>
    <table class="table-bordered table-odd">
        <thead>
            <tr>
                <th>#</th>
                <th>Name</th>
				<th>Size</th>
            </tr>
        </thead>
        <tbody>
            {{ range $idx, $file := .Files }}
            <tr>
                <td>{{ $idx }}</td>
                {{ if $file.Download }}
                <td><a href="{{ $file.Path }}" title="{{ $file.ModTime }}" download>{{ $file.Name }}</a></td> 
                {{ else }}
                <td><a href="{{ $file.Path }}" title="{{ $file.ModTime }}">{{ $file.Name }}</a></td>
                {{ end }}
				{{ if $file.Info.IsDir }}
				<td>Dir</td>
				{{ else }}
				<td>{{ formatBytes $file.Info.Size }}</td>
				{{ end }}
            </tr>
            {{ end }}
        </tbody>
	</table>
</body></html>
`))

DirListRichTemplate is the html template the `DirListRich` function is using to render the directories and files.

View Source
var ErrNotRouteAdder = errors.New("request handler does not implement AddRoute method")

ErrNotRouteAdder throws on `AddRouteUnsafe` when a registered `RequestHandler` does not implements the optional `AddRoute(*Route) error` method.

Functions

func Abs

func Abs(path string) string

Abs calls filepath.Abs but ignores the error and returns the original value if any error occurred.

func DirList added in v12.2.0

func DirList(ctx *context.Context, dirOptions DirOptions, dirName string, dir http.File) error

DirList is a `DirListFunc` which renders directories and files in html, but plain, mode. See `DirListRich` for more.

func DirectoryExists

func DirectoryExists(dir string) bool

DirectoryExists returns true if a directory(or file) exists, otherwise false

func FileServer

func FileServer(fs http.FileSystem, options DirOptions) context.Handler

FileServer returns a Handler which serves files from a specific file system. The first parameter is the file system, if it's a `http.Dir` the files should be located near the executable program. The second parameter is the settings that the caller can use to customize the behavior.

See `Party#HandleDir` too. Examples can be found at: https://github.com/kataras/iris/tree/master/_examples/file-server

func FormatBytes added in v12.2.0

func FormatBytes(b int64) string

FormatBytes returns a string representation of the "b" bytes.

func NewSubdomainPartyRedirectHandler added in v12.2.0

func NewSubdomainPartyRedirectHandler(to Party) context.Handler

NewSubdomainPartyRedirectHandler returns a handler which can be registered through `UseRouter` or `Use` to redirect from the current request's subdomain to the one which the given `to` Party can handle.

func NewSubdomainRedirectHandler added in v12.2.0

func NewSubdomainRedirectHandler(toSubdomain string) context.Handler

NewSubdomainRedirectHandler returns a handler which can be registered through `UseRouter` or `Use` to redirect from the current request's subdomain to the given "toSubdomain".

func Param

func Param(name string) string

Param receives a parameter name prefixed with the ParamStart symbol.

func RedirectAbsolute added in v12.2.0

func RedirectAbsolute(w http.ResponseWriter, r *http.Request, url string, code int)

RedirectAbsolute replies to the request with a redirect to an absolute URL.

The provided code should be in the 3xx range and is usually StatusMovedPermanently, StatusFound or StatusSeeOther.

If the Content-Type header has not been set, Redirect sets it to "text/html; charset=utf-8" and writes a small HTML body. Setting the Content-Type header to any value, including nil, disables that behavior.

func StripPrefix

func StripPrefix(prefix string, h context.Handler) context.Handler

StripPrefix returns a handler that serves HTTP requests by removing the given prefix from the request URL's Path and invoking the handler h. StripPrefix handles a request for a path that doesn't begin with prefix by replying with an HTTP 404 not found error.

Usage: fileserver := FileServer("./static_files", DirOptions {...}) h := StripPrefix("/static", fileserver) app.Get("/static/{file:path}", h) app.Head("/static/{file:path}", h)

func TraceTitleColorCode added in v12.2.0

func TraceTitleColorCode(method string) int

TraceTitleColorCode returns the color code depending on the method or the status.

func TypeByExtension

func TypeByExtension(ext string) (typ string)

TypeByExtension returns the MIME type associated with the file extension ext. The extension ext should begin with a leading dot, as in ".html". When ext has no associated type, typeByExtension returns "".

Extensions are looked up first case-sensitively, then case-insensitively.

The built-in table is small but on unix it is augmented by the local system's mime.types file(s) if available under one or more of these names:

/etc/mime.types
/etc/apache2/mime.types
/etc/apache/mime.types

On Windows, MIME types are extracted from the registry.

Text types have the charset parameter set to "utf-8" by default.

func TypeByFilename

func TypeByFilename(fullFilename string) string

TypeByFilename same as TypeByExtension but receives a filename path instead.

func WildcardFileParam

func WildcardFileParam() string

WildcardFileParam wraps a named parameter "file" with the trailing "path" macro parameter type. At build state this "file" parameter is prefixed with the request handler's `WildcardParamStart`. Created mostly for routes that serve static files to be visibly collected by the `Application#GetRouteReadOnly` via the `Route.Tmpl().Src` instead of the underline request handler's representation (`Route.Path()`).

func WildcardParam

func WildcardParam(name string) string

WildcardParam receives a parameter name prefixed with the WildcardParamStart symbol.

Types

type APIBuilder

type APIBuilder struct {
	// contains filtered or unexported fields
}

APIBuilder the visible API for constructing the router and child routers.

func NewAPIBuilder

func NewAPIBuilder(logger *golog.Logger) *APIBuilder

NewAPIBuilder creates & returns a new builder which is responsible to build the API and the router handler.

func (*APIBuilder) AllowMethods

func (api *APIBuilder) AllowMethods(methods ...string) Party

AllowMethods will re-register the future routes that will be registered via `Handle`, `Get`, `Post`, ... to the given "methods" on that Party and its children "Parties", duplicates are not registered.

Call of `AllowMethod` will override any previous allow methods.

func (*APIBuilder) Any

func (api *APIBuilder) Any(relativePath string, handlers ...context.Handler) (routes []*Route)

Any registers a route for ALL of the HTTP methods: Get Post Put Delete Head Patch Options Connect Trace

func (*APIBuilder) ConfigureContainer added in v12.2.0

func (api *APIBuilder) ConfigureContainer(builder ...func(*APIContainer)) *APIContainer

ConfigureContainer accepts one or more functions that can be used to configure dependency injection features of this Party such as register dependency and register handlers that will automatically inject any valid dependency. However, if the "builder" parameter is nil or not provided then it just returns the *APIContainer, which automatically initialized on Party allocation.

It returns the same `APIBuilder` featured with Dependency Injection.

func (*APIBuilder) Connect

func (api *APIBuilder) Connect(relativePath string, handlers ...context.Handler) *Route

Connect registers a route for the Connect HTTP Method.

Returns a *Route and an error which will be filled if route wasn't registered successfully.

func (*APIBuilder) CreateRoutes added in v12.1.0

func (api *APIBuilder) CreateRoutes(methods []string, relativePath string, handlers ...context.Handler) []*Route

CreateRoutes returns a list of Party-based Routes. It does NOT registers the route. Use `Handle, Get...` methods instead. This method can be used for third-parties Iris helpers packages and tools that want a more detailed view of Party-based Routes before take the decision to register them.

func (*APIBuilder) Delete

func (api *APIBuilder) Delete(relativePath string, handlers ...context.Handler) *Route

Delete registers a route for the Delete HTTP Method.

Returns a *Route and an error which will be filled if route wasn't registered successfully.

func (*APIBuilder) Done

func (api *APIBuilder) Done(handlers ...context.Handler)

Done appends to the very end, Handler(s) to the current Party's routes and child routes. The given "handlers" will be executed only on matched routes.

Call order matters, it should be called right before the routes that they care about these handlers.

The difference from .Use is that this/or these Handler(s) are being always running last.

func (*APIBuilder) DoneGlobal

func (api *APIBuilder) DoneGlobal(handlers ...context.Handler)

DoneGlobal registers handlers that should run at the very end. It appends those handler(s) to all routes, including all parties, subdomains. It doesn't care about call order, it will append the handlers to all existing routes and the future routes that may being registered.

The given "handlers" will be executed only on matched and registered error routes.

The difference from `.UseGlobal` is that this/or these Handler(s) are being always running last. Use of `ctx.Next()` at the previous handler is necessary. It's always a good practise to call it right before the `Application#Run` function.

func (*APIBuilder) Favicon

func (api *APIBuilder) Favicon(favPath string, requestPath ...string) *Route

Favicon serves static favicon accepts 2 parameters, second is optional favPath (string), declare the system directory path of the __.ico requestPath (string), it's the route's path, by default this is the "/favicon.ico" because some browsers tries to get this by default first, you can declare your own path if you have more than one favicon (desktop, mobile and so on)

this func will add a route for you which will static serve the /yuorpath/yourfile.ico to the /yourfile.ico (nothing special that you can't handle by yourself). Note that you have to call it on every favicon you have to serve automatically (desktop, mobile and so on).

Returns the GET *Route.

func (*APIBuilder) Get

func (api *APIBuilder) Get(relativePath string, handlers ...context.Handler) *Route

Get registers a route for the Get HTTP Method.

Returns a *Route and an error which will be filled if route wasn't registered successfully.

func (*APIBuilder) GetDefaultErrorMiddleware added in v12.2.0

func (api *APIBuilder) GetDefaultErrorMiddleware() context.Handlers

GetDefaultErrorMiddleware returns the application's error pre handlers registered through `UseError` for the default error handlers. This is used when no matching error handlers registered for a specific status code but `UseError` is called to register a middleware, so the default error handler should make use of those middleware now.

func (*APIBuilder) GetRelPath

func (api *APIBuilder) GetRelPath() string

GetRelPath returns the current party's relative path. i.e: if r := app.Party("/users"), then the `r.GetRelPath()` is the "/users". if r := app.Party("www.") or app.Subdomain("www") then the `r.GetRelPath()` is the "www.".

func (*APIBuilder) GetRoute

func (api *APIBuilder) GetRoute(routeName string) *Route

GetRoute returns the registered route based on its name, otherwise nil. One note: "routeName" should be case-sensitive.

func (*APIBuilder) GetRouteByPath

func (api *APIBuilder) GetRouteByPath(tmplPath string) *Route

GetRouteByPath returns the registered route based on the template path (`Route.Tmpl().Src`).

func (*APIBuilder) GetRouteReadOnly

func (api *APIBuilder) GetRouteReadOnly(routeName string) context.RouteReadOnly

GetRouteReadOnly returns the registered "read-only" route based on its name, otherwise nil. One note: "routeName" should be case-sensitive. Used by the context to get the current route. It returns an interface instead to reduce wrong usage and to keep the decoupled design between the context and the routes. Look `GetRoutesReadOnly` to fetch a list of all registered routes.

Look `GetRoute` for more.

func (*APIBuilder) GetRouteReadOnlyByPath

func (api *APIBuilder) GetRouteReadOnlyByPath(tmplPath string) context.RouteReadOnly

GetRouteReadOnlyByPath returns the registered read-only route based on the template path (`Route.Tmpl().Src`).

func (*APIBuilder) GetRouterFilters added in v12.2.0

func (api *APIBuilder) GetRouterFilters() map[Party]*Filter

GetRouterFilters returns the global router filters. Read `UseRouter` for more. The map can be altered before router built. The router internally prioritized them by the subdomains and longest static path. Implements the `RoutesProvider` interface.

func (*APIBuilder) GetRoutes

func (api *APIBuilder) GetRoutes() []*Route

GetRoutes returns the routes information, some of them can be changed at runtime some others not.

Needs refresh of the router to Method or Path or Handlers changes to take place.

func (*APIBuilder) GetRoutesReadOnly

func (api *APIBuilder) GetRoutesReadOnly() []context.RouteReadOnly

GetRoutesReadOnly returns the registered routes with "read-only" access, you cannot and you should not change any of these routes' properties on request state, you can use the `GetRoutes()` for that instead.

It returns interface-based slice instead of the real ones in order to apply safe fetch between context(request-state) and the builded application.

Look `GetRouteReadOnly` too.

func (*APIBuilder) Handle

func (api *APIBuilder) Handle(method string, relativePath string, handlers ...context.Handler) *Route

Handle registers a route to this Party. if empty method is passed then handler(s) are being registered to all methods, same as .Any.

Returns a *Route, app will throw any errors later on.

func (*APIBuilder) HandleDir

func (api *APIBuilder) HandleDir(requestPath string, fsOrDir interface{}, opts ...DirOptions) (routes []*Route)

HandleDir registers a handler that serves HTTP requests with the contents of a file system (physical or embedded).

first parameter : the route path second parameter : the file system needs to be served third parameter : not required, the serve directory options.

Alternatively, to get just the handler for that look the FileServer function instead.

api.HandleDir("/static", iris.Dir("./assets"), iris.DirOptions{IndexName: "/index.html", Compress: true})

Returns all the registered routes, including GET index and path patterm and HEAD.

Usage: HandleDir("/public", "./assets", DirOptions{...}) or HandleDir("/public", iris.Dir("./assets"), DirOptions{...})

Examples: https://github.com/kataras/iris/tree/master/_examples/file-server

func (*APIBuilder) HandleMany

func (api *APIBuilder) HandleMany(methodOrMulti string, relativePathorMulti string, handlers ...context.Handler) (routes []*Route)

HandleMany works like `Handle` but can receive more than one paths separated by spaces and returns always a slice of *Route instead of a single instance of Route.

It's useful only if the same handler can handle more than one request paths, otherwise use `Party` which can handle many paths with different handlers and middlewares.

Usage:

app.HandleMany("GET", "/user /user/{id:uint64} /user/me", genericUserHandler)

At the other side, with `Handle` we've had to write:

app.Handle("GET", "/user", userHandler)
app.Handle("GET", "/user/{id:uint64}", userByIDHandler)
app.Handle("GET", "/user/me", userMeHandler)

app.HandleMany("GET POST", "/path", handler)

func (*APIBuilder) Head

func (api *APIBuilder) Head(relativePath string, handlers ...context.Handler) *Route

Head registers a route for the Head HTTP Method.

Returns a *Route and an error which will be filled if route wasn't registered successfully.

func (*APIBuilder) IsRoot added in v12.2.0

func (api *APIBuilder) IsRoot() bool

IsRoot reports whether this Party is the root Application's one. It will return false on all children Parties, no exception.

func (*APIBuilder) Layout

func (api *APIBuilder) Layout(tmplLayoutFile string) Party

Layout overrides the parent template layout with a more specific layout for this Party. It returns the current Party.

The "tmplLayoutFile" should be a relative path to the templates dir. Usage:

app := iris.New() app.RegisterView(iris.$VIEW_ENGINE("./views", ".$extension")) my := app.Party("/my").Layout("layouts/mylayout.html")

my.Get("/", func(ctx iris.Context) {
	ctx.View("page1.html")
})

Examples: https://github.com/kataras/iris/tree/master/_examples/view

func (*APIBuilder) Logger added in v12.2.0

func (api *APIBuilder) Logger() *golog.Logger

Logger returns the Application Logger.

func (*APIBuilder) Macros

func (api *APIBuilder) Macros() *macro.Macros

Macros returns the macro collection that is responsible to register custom macros with their own parameter types and their macro functions for all routes.

Learn more at: https://github.com/kataras/iris/tree/master/_examples/routing/dynamic-path

func (*APIBuilder) Match added in v12.2.0

func (api *APIBuilder) Match(ctx *context.Context) bool

Match reports whether the `UseRouter` handlers should be executed. Calls its parent's Match if possible. Implements the `PartyMatcher` interface.

func (*APIBuilder) None

func (api *APIBuilder) None(relativePath string, handlers ...context.Handler) *Route

None registers an "offline" route see context.ExecRoute(routeName) and party.Routes().Online(handleResultRouteInfo, "GET") and Offline(handleResultRouteInfo)

Returns a *Route and an error which will be filled if route wasn't registered successfully.

func (*APIBuilder) OnAnyErrorCode

func (api *APIBuilder) OnAnyErrorCode(handlers ...context.Handler) (routes []*Route)

OnAnyErrorCode registers a handlers chain for all error codes (4xxx and 5xxx, change the `context.ClientErrorCodes` and `context.ServerErrorCodes` variables to modify those) Look `UseError` and `OnErrorCode` too.

func (*APIBuilder) OnErrorCode

func (api *APIBuilder) OnErrorCode(statusCode int, handlers ...context.Handler) (routes []*Route)

OnErrorCode registers a handlers chain for this `Party` for a specific HTTP status code. Read more at: http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml Look `UseError` and `OnAnyErrorCode` too.

func (*APIBuilder) Options

func (api *APIBuilder) Options(relativePath string, handlers ...context.Handler) *Route

Options registers a route for the Options HTTP Method.

Returns a *Route and an error which will be filled if route wasn't registered successfully.

func (*APIBuilder) Party

func (api *APIBuilder) Party(relativePath string, handlers ...context.Handler) Party

Party returns a new child Party which inherites its parent's options and middlewares. If "relativePath" matches the parent's one then it returns the current Party. A Party groups routes which may have the same prefix or subdomain and share same middlewares.

To create a group of routes for subdomains use the `Subdomain` or `WildcardSubdomain` methods or pass a "relativePath" as "admin." or "*." respectfully.

func (*APIBuilder) PartyFunc

func (api *APIBuilder) PartyFunc(relativePath string, partyBuilderFunc func(p Party)) Party

PartyFunc same as `Party`, groups routes that share a base path or/and same handlers. However this function accepts a function that receives this created Party instead. Returns the Party in order the caller to be able to use this created Party to continue the top-bottom routes "tree".

Note: `iris#Party` and `core/router#Party` describes the exactly same interface.

Usage:

app.PartyFunc("/users", func(u iris.Party){
	u.Use(authMiddleware, logMiddleware)
	u.Get("/", getAllUsers)
	u.Post("/", createOrUpdateUser)
	u.Delete("/", deleteUser)
})

Look `Party` for more.

func (*APIBuilder) Patch

func (api *APIBuilder) Patch(relativePath string, handlers ...context.Handler) *Route

Patch registers a route for the Patch HTTP Method.

Returns a *Route and an error which will be filled if route wasn't registered successfully.

func (*APIBuilder) Post

func (api *APIBuilder) Post(relativePath string, handlers ...context.Handler) *Route

Post registers a route for the Post HTTP Method.

Returns a *Route and an error which will be filled if route wasn't registered successfully.

func (*APIBuilder) Put

func (api *APIBuilder) Put(relativePath string, handlers ...context.Handler) *Route

Put registers a route for the Put HTTP Method.

Returns a *Route and an error which will be filled if route wasn't registered successfully.

func (*APIBuilder) RegisterView added in v12.2.0

func (api *APIBuilder) RegisterView(viewEngine context.ViewEngine)

RegisterView registers and loads a view engine middleware for that group of routes. It overrides any of the application's root registered view engines. To register a view engine per handler chain see the `Context.ViewEngine` instead. Read `Configuration.ViewEngineContextKey` documentation for more.

func (*APIBuilder) Reset

func (api *APIBuilder) Reset() Party

Reset removes all the begin and done handlers that may derived from the parent party via `Use` & `Done`, and the execution rules. Note that the `Reset` will not reset the handlers that are registered via `UseGlobal` & `DoneGlobal`.

Returns this Party.

func (*APIBuilder) ResetRouterFilters added in v12.2.0

func (api *APIBuilder) ResetRouterFilters() Party

ResetRouterFilters deactivates any previous registered router filters and the parents ones for this Party.

Returns this Party.

func (*APIBuilder) SetExecutionRules

func (api *APIBuilder) SetExecutionRules(executionRules ExecutionRules) Party

SetExecutionRules alters the execution flow of the route handlers outside of the handlers themselves.

For example, if for some reason the desired result is the (done or all) handlers to be executed no matter what even if no `ctx.Next()` is called in the previous handlers, including the begin(`Use`), the main(`Handle`) and the done(`Done`) handlers themselves, then:

Party#SetExecutionRules(iris.ExecutionRules {
  Begin: iris.ExecutionOptions{Force: true},
  Main:  iris.ExecutionOptions{Force: true},
  Done:  iris.ExecutionOptions{Force: true},
})

Note that if : true then the only remained way to "break" the handler chain is by `ctx.StopExecution()` now that `ctx.Next()` does not matter.

These rules are per-party, so if a `Party` creates a child one then the same rules will be applied to that as well. Reset of these rules (before `Party#Handle`) can be done with `Party#SetExecutionRules(iris.ExecutionRules{})`.

The most common scenario for its use can be found inside Iris MVC Applications; when we want the `Done` handlers of that specific mvc app's `Party` to be executed but we don't want to add `ctx.Next()` on the `OurController#EndRequest`.

Returns this Party.

Example: https://github.com/kataras/iris/tree/master/_examples/mvc/middleware/without-ctx-next

func (*APIBuilder) SetPartyMatcher added in v12.2.0

func (api *APIBuilder) SetPartyMatcher(matcherFunc PartyMatcherFunc)

SetPartyMatcher accepts a function which runs against a Party and should report whether its `UseRouter` handlers should be executed. PartyMatchers are run through parent to children. It modifies the default Party filter that decides which `UseRouter` middlewares to run before the Router, each one of those middlewares can skip `Context.Next` or call `Context.StopXXX` to stop the main router from searching for a route match. Can be called before or after `UseRouter`, it doesn't matter.

func (*APIBuilder) SetRegisterRule added in v12.1.7

func (api *APIBuilder) SetRegisterRule(rule RouteRegisterRule) Party

SetRegisterRule sets a `RouteRegisterRule` for this Party and its children. Available values are: * RouteOverride (the default one) * RouteSkip * RouteError * RouteOverlap.

func (*APIBuilder) StaticContent

func (api *APIBuilder) StaticContent(reqPath string, cType string, content []byte) *Route

StaticContent registers a GET and HEAD method routes to the requestPath that are ready to serve raw static bytes, memory cached.

Returns the GET *Route.

func (*APIBuilder) Subdomain

func (api *APIBuilder) Subdomain(subdomain string, middleware ...context.Handler) Party

Subdomain returns a new party which is responsible to register routes to this specific "subdomain".

If called from a child party then the subdomain will be prepended to the path instead of appended. So if app.Subdomain("admin").Subdomain("panel") then the result is: "panel.admin.".

func (*APIBuilder) Trace

func (api *APIBuilder) Trace(relativePath string, handlers ...context.Handler) *Route

Trace registers a route for the Trace HTTP Method.

Returns a *Route and an error which will be filled if route wasn't registered successfully.

func (*APIBuilder) Use

func (api *APIBuilder) Use(handlers ...context.Handler)

Use appends Handler(s) to the current Party's routes and child routes. If the current Party is the root, then it registers the middleware to all child Parties' routes too. The given "handlers" will be executed only on matched routes.

Call order matters, it should be called right before the routes that they care about these handlers.

If it's called after the routes then these handlers will never be executed. Use `UseGlobal` if you want to register begin handlers(middleware) that should be always run before all application's routes. To register a middleware for error handlers, look `UseError` method instead.

func (*APIBuilder) UseError added in v12.2.0

func (api *APIBuilder) UseError(handlers ...context.Handler)

UseError upserts one or more handlers that will be fired, as middleware, before any error handler registered through `On(Any)ErrorCode`. See `OnErrorCode` too.

func (*APIBuilder) UseGlobal

func (api *APIBuilder) UseGlobal(handlers ...context.Handler)

UseGlobal registers handlers that should run at the very beginning. It prepends those handler(s) to all routes, including all parties, subdomains and errors. It doesn't care about call order, it will prepend the handlers to all existing routes and the future routes that may being registered.

The given "handlers" will be executed only on matched routes and registered errors. See `UseRouter` if you want to register middleware that will always run, even on 404 not founds.

The difference from `.DoneGlobal` is that this/or these Handler(s) are being always running first. Use of `ctx.Next()` of those handler(s) is necessary to call the main handler or the next middleware. It's always a good practise to call it right before the `Application#Run` function.

func (*APIBuilder) UseOnce added in v12.2.0

func (api *APIBuilder) UseOnce(handlers ...context.Handler)

UseOnce either inserts a middleware, or on the basis of the middleware already existing, replace that existing middleware instead. To register a middleware for error handlers, look `UseError` method instead.

func (*APIBuilder) UseRouter added in v12.2.0

func (api *APIBuilder) UseRouter(handlers ...context.Handler)

UseRouter upserts one or more handlers that will be fired right before the main router's request handler.

Use this method to register handlers, that can ran independently of the incoming request's values, that they will be executed ALWAYS against ALL children incoming requests. Example of use-case: CORS.

Note that because these are executed before the router itself the Context should not have access to the `GetCurrentRoute` as it is not decided yet which route is responsible to handle the incoming request. It's one level higher than the `WrapRouter`. The context SHOULD call its `Next` method in order to proceed to the next handler in the chain or the main request handler one.

func (*APIBuilder) WildcardSubdomain

func (api *APIBuilder) WildcardSubdomain(middleware ...context.Handler) Party

WildcardSubdomain returns a new party which is responsible to register routes to a dynamic, wildcard(ed) subdomain. A dynamic subdomain is a subdomain which can reply to any subdomain requests. Server will accept any subdomain (if not static subdomain found) and it will search and execute the handlers of this party.

type APIContainer added in v12.2.0

type APIContainer struct {
	// Self returns the original `Party` without DI features.
	Self Party

	// Container is the per-party (and its children gets a clone) DI container..
	Container *hero.Container
}

APIContainer is a wrapper of a common `Party` featured by Dependency Injection. See `Party.ConfigureContainer` for more.

func (*APIContainer) Any added in v12.2.0

func (api *APIContainer) Any(relativePath string, handlersFn ...interface{}) (routes []*Route)

Any registers a route for ALL of the HTTP methods: Get Post Put Delete Head Patch Options Connect Trace

func (*APIContainer) Connect added in v12.2.0

func (api *APIContainer) Connect(relativePath string, handlersFn ...interface{}) *Route

Connect registers a route for the Connect HTTP Method.

Returns a *Route and an error which will be filled if route wasn't registered successfully.

func (*APIContainer) Delete added in v12.2.0

func (api *APIContainer) Delete(relativePath string, handlersFn ...interface{}) *Route

Delete registers a route for the Delete HTTP Method.

Returns a *Route and an error which will be filled if route wasn't registered successfully.

func (*APIContainer) Done added in v12.2.0

func (api *APIContainer) Done(handlersFn ...interface{})

Done same as `Self.Done` but it accepts dynamic functions as its "handlersFn" input. See `OnError`, `RegisterDependency`, `Use` and `Handle` for more.

func (*APIContainer) Get added in v12.2.0

func (api *APIContainer) Get(relativePath string, handlersFn ...interface{}) *Route

Get registers a route for the Get HTTP Method.

Returns a *Route and an error which will be filled if route wasn't registered successfully.

func (*APIContainer) Handle added in v12.2.0

func (api *APIContainer) Handle(method, relativePath string, handlersFn ...interface{}) *Route

Handle same as `Self.Handle` but it accepts one or more "handlersFn" functions which each one of them can accept any input arguments that match with the Party's registered Container's `Dependencies` and any output result; like custom structs <T>, string, []byte, int, error, a combination of the above, hero.Result(hero.View | hero.Response) and more.

It's common from a hero handler to not even need to accept a `Context`, for that reason, the "handlersFn" will call `ctx.Next()` automatically when not called manually. To stop the execution and not continue to the next "handlersFn" the end-developer should output an error and return `iris.ErrStopExecution`.

See `OnError`, `RegisterDependency`, `Use`, `Done`, `Get`, `Post`, `Put`, `Patch` and `Delete` too.

func (*APIContainer) Handler added in v12.2.0

func (api *APIContainer) Handler(handlerFn interface{}, handlerParamsCount int) context.Handler

Handler receives a function which can receive dependencies and output result and returns a common Iris Handler, useful for Versioning API integration otherwise the `Handle/Get/Post...` methods are preferable.

func (*APIContainer) Head added in v12.2.0

func (api *APIContainer) Head(relativePath string, handlersFn ...interface{}) *Route

Head registers a route for the Head HTTP Method.

Returns a *Route and an error which will be filled if route wasn't registered successfully.

func (*APIContainer) OnError added in v12.2.0

func (api *APIContainer) OnError(errorHandler func(*context.Context, error))

OnError adds an error handler for this Party's DI Hero Container and its handlers (or controllers). The "errorHandler" handles any error may occurred and returned during dependencies injection of the Party's hero handlers or from the handlers themselves.

Same as: Container.GetErrorHandler = func(ctx iris.Context) hero.ErrorHandler { return errorHandler }

See `RegisterDependency`, `Use`, `Done` and `Handle` too.

func (*APIContainer) Options added in v12.2.0

func (api *APIContainer) Options(relativePath string, handlersFn ...interface{}) *Route

Options registers a route for the Options HTTP Method.

Returns a *Route and an error which will be filled if route wasn't registered successfully.

func (*APIContainer) Party added in v12.2.0

func (api *APIContainer) Party(relativePath string, handlersFn ...interface{}) *APIContainer

Party returns a child of this `APIContainer` featured with Dependency Injection. Like the `Self.Party` method does for the common Router Groups.

func (*APIContainer) PartyFunc added in v12.2.0

func (api *APIContainer) PartyFunc(relativePath string, fn func(*APIContainer)) *APIContainer

PartyFunc same as `Party` but it accepts a party builder function instead. Returns the new Party's APIContainer

func (*APIContainer) Patch added in v12.2.0

func (api *APIContainer) Patch(relativePath string, handlersFn ...interface{}) *Route

Patch registers a route for the Patch HTTP Method.

Returns a *Route and an error which will be filled if route wasn't registered successfully.

func (*APIContainer) Post added in v12.2.0

func (api *APIContainer) Post(relativePath string, handlersFn ...interface{}) *Route

Post registers a route for the Post HTTP Method.

Returns a *Route and an error which will be filled if route wasn't registered successfully.

func (*APIContainer) Put added in v12.2.0

func (api *APIContainer) Put(relativePath string, handlersFn ...interface{}) *Route

Put registers a route for the Put HTTP Method.

Returns a *Route and an error which will be filled if route wasn't registered successfully.

func (*APIContainer) RegisterDependency added in v12.2.0

func (api *APIContainer) RegisterDependency(dependency interface{}) *hero.Dependency

RegisterDependency adds a dependency. The value can be a single struct value or a function. Follow the rules: * <T>{structValue} * func(accepts <T>) returns <D> or (<D>, error) * func(accepts iris.Context) returns <D> or (<D>, error)

A Dependency can accept a previous registered dependency and return a new one or the same updated. * func(accepts1 <D>, accepts2 <T>) returns <E> or (<E>, error) or error * func(acceptsPathParameter1 string, id uint64) returns <T> or (<T>, error)

Usage:

- RegisterDependency(loggerService{prefix: "dev"}) - RegisterDependency(func(ctx iris.Context) User {...}) - RegisterDependency(func(User) OtherResponse {...})

See `OnError`, `Use`, `Done` and `Handle` too.

func (*APIContainer) Trace added in v12.2.0

func (api *APIContainer) Trace(relativePath string, handlersFn ...interface{}) *Route

Trace registers a route for the Trace HTTP Method.

Returns a *Route and an error which will be filled if route wasn't registered successfully.

func (*APIContainer) Use added in v12.2.0

func (api *APIContainer) Use(handlersFn ...interface{})

Use same as `Self.Use` but it accepts dynamic functions as its "handlersFn" input.

See `OnError`, `RegisterDependency`, `Done` and `Handle` for more.

func (*APIContainer) UseResultHandler added in v12.2.0

func (api *APIContainer) UseResultHandler(handler func(next hero.ResultHandler) hero.ResultHandler) *APIContainer

UseResultHandler adds a result handler to the Container. A result handler can be used to inject the returned struct value from a request handler or to replace the default renderer.

type Attachments added in v12.2.0

type Attachments struct {
	// Set to true to enable the files to be downloaded and
	// saved locally by the client, instead of serving the file.
	Enable bool
	// Options to send files with a limit of bytes sent per second.
	Limit float64
	Burst int
	// Use this function to change the sent filename.
	NameFunc func(systemName string) (attachmentName string)
}

Attachments options for files to be downloaded and saved locally by the client. See `DirOptions`.

type DirCacheOptions added in v12.2.0

type DirCacheOptions struct {
	// Enable or disable cache.
	Enable bool
	// Minimum content size for compression in bytes.
	CompressMinSize int64
	// Ignore compress files that match this pattern.
	CompressIgnore *regexp.Regexp
	// The available sever's encodings to be negotiated with the client's needs,
	// common values: gzip, br.
	Encodings []string

	// If greater than zero then prints information about cached files to the stdout.
	// If it's 1 then it prints only the total cached and after-compression reduced file sizes
	// If it's 2 then it prints it per file too.
	Verbose uint8
}

DirCacheOptions holds the options for the cached file system. See `DirOptions`structure for more.

type DirListFunc added in v12.2.0

type DirListFunc func(ctx *context.Context, dirOptions DirOptions, dirName string, dir http.File) error

DirListFunc is the function signature for customizing directory and file listing. See `DirList` and `DirListRich` functions for its implementations.

func DirListRich added in v12.2.0

func DirListRich(opts ...DirListRichOptions) DirListFunc

DirListRich is a `DirListFunc` which can be passed to `DirOptions.DirList` field to override the default file listing appearance. See `DirListRichTemplate` to modify the template, if necessary.

type DirListRichOptions added in v12.2.0

type DirListRichOptions struct {
	// If not nil then this template's "dirlist" is used to render the listing page.
	Tmpl *template.Template
	// If not empty then this view file is used to render the listing page.
	// The view should be registered with `Application.RegisterView`.
	// E.g. "dirlist.html"
	TmplName string
}

DirListRichOptions the options for the `DirListRich` helper function.

type DirOptions

type DirOptions struct {
	// Defaults to "/index.html", if request path is ending with **/*/$IndexName
	// then it redirects to **/*(/).
	// That index handler is registered automatically
	// by the framework unless but it can be overridden.
	IndexName string
	// PushTargets filenames (map's value) to
	// be served without additional client's requests (HTTP/2 Push)
	// when a specific request path (map's key WITHOUT prefix)
	// is requested and it's not a directory (it's an `IndexFile`).
	//
	// Example:
	// 	"/": {
	// 		"favicon.ico",
	// 		"js/main.js",
	// 		"css/main.css",
	// 	}
	PushTargets map[string][]string
	// PushTargetsRegexp like `PushTargets` but accepts regexp which
	// is compared against all files under a directory (recursively).
	// The `IndexName` should be set.
	//
	// Example:
	// "/": regexp.MustCompile("((.*).js|(.*).css|(.*).ico)$")
	// See `iris.MatchCommonAssets` too.
	PushTargetsRegexp map[string]*regexp.Regexp

	// Cache to enable in-memory cache and pre-compress files.
	Cache DirCacheOptions
	// When files should served under compression.
	Compress bool

	// List the files inside the current requested
	// directory if `IndexName` not found.
	ShowList bool
	// If `ShowList` is true then this function will be used instead
	// of the default one to show the list of files
	// of a current requested directory(dir).
	// See `DirListRich` package-level function too.
	DirList DirListFunc

	// Files downloaded and saved locally.
	Attachments Attachments

	// Optional validator that loops through each requested resource.
	AssetValidator func(ctx *context.Context, name string) bool
}

DirOptions contains the settings that `FileServer` can use to serve files. See `DefaultDirOptions`.

type ExecutionOptions

type ExecutionOptions struct {
	// Force if true then the handler9s) will execute even if the previous (or/and current, depends on the type of the rule)
	// handler does not calling the `ctx.Next()`,
	// note that the only way remained to stop a next handler is with the `ctx.StopExecution()` if this option is true.
	//
	// If true and `ctx.Next()` exists in the handlers that it shouldn't be, the framework will understand it but use it wisely.
	//
	// Defaults to false.
	Force bool
}

ExecutionOptions is a set of default behaviors that can be changed in order to customize the execution flow of the routes' handlers with ease.

See `ExecutionRules` and `Party#SetExecutionRules` for more.

type ExecutionRules

type ExecutionRules struct {
	// Begin applies from `Party#Use`/`APIBUilder#UseGlobal` to the first...!last `Party#Handle`'s IF main handlers > 1.
	Begin ExecutionOptions
	// Done applies to the latest `Party#Handle`'s (even if one) and all done handlers.
	Done ExecutionOptions
	// Main applies to the `Party#Handle`'s all handlers, plays nice with the `Done` rule
	// when more than one handler was registered in `Party#Handle` without `ctx.Next()` (for Force: true).
	Main ExecutionOptions
}

ExecutionRules gives control to the execution of the route handlers outside of the handlers themselves. Usage:

Party#SetExecutionRules(ExecutionRules {
  Done: ExecutionOptions{Force: true},
})

See `Party#SetExecutionRules` for more.

type Filter added in v12.2.0

type Filter struct {
	Matcher   PartyMatcher             // it's a Party, for freedom that can be changed through a custom matcher which accepts the same filter.
	Skippers  map[*APIBuilder]struct{} // skip execution on these builders ( see `Reset`)
	Subdomain string
	Path      string
	Handlers  context.Handlers
}

Filter is a wraper for a Router Filter contains information for its Party's fullpath, subdomain the Party's matcher and the associated handlers to be executed before main router's request handler.

type HTTPErrorHandler added in v12.2.0

type HTTPErrorHandler interface {
	// FireErrorCode should send an error response to the client based
	// on the given context's response status code.
	FireErrorCode(ctx *context.Context)
}

HTTPErrorHandler should contain a method `FireErrorCode` which handles http unsuccessful status codes.

type Party

type Party interface {
	// Logger returns the Application Logger.
	Logger() *golog.Logger

	// IsRoot reports whether this Party is the root Application's one.
	// It will return false on all children Parties, no exception.
	IsRoot() bool

	// ConfigureContainer accepts one or more functions that can be used
	// to configure dependency injection features of this Party
	// such as register dependency and register handlers that will automatically inject any valid dependency.
	// However, if the "builder" parameter is nil or not provided then it just returns the *APIContainer,
	// which automatically initialized on Party allocation.
	//
	// It returns the same `APIBuilder` featured with Dependency Injection.
	ConfigureContainer(builder ...func(*APIContainer)) *APIContainer

	// GetRelPath returns the current party's relative path.
	// i.e:
	// if r := app.Party("/users"), then the `r.GetRelPath()` is the "/users".
	// if r := app.Party("www.") or app.Subdomain("www") then the `r.GetRelPath()` is the "www.".
	GetRelPath() string
	// Macros returns the macro collection that is responsible
	// to register custom macros with their own parameter types and their macro functions for all routes.
	//
	// Learn more at:  https://github.com/kataras/iris/tree/master/_examples/routing/dynamic-path
	Macros() *macro.Macros

	// OnErrorCode registers a handlers chain for this `Party` for a specific HTTP status code.
	// Read more at: http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
	// Look `UseError` and `OnAnyErrorCode` too.
	OnErrorCode(statusCode int, handlers ...context.Handler) []*Route
	// OnAnyErrorCode registers a handlers chain for all error codes
	// (4xxx and 5xxx, change the `ClientErrorCodes` and `ServerErrorCodes` variables to modify those)
	// Look `UseError` and `OnErrorCode` too.
	OnAnyErrorCode(handlers ...context.Handler) []*Route

	// Party returns a new child Party which inherites its
	// parent's options and middlewares.
	// If "relativePath" matches the parent's one then it returns the current Party.
	// A Party groups routes which may have the same prefix or subdomain and share same middlewares.
	//
	// To create a group of routes for subdomains
	// use the `Subdomain` or `WildcardSubdomain` methods
	// or pass a "relativePath" as "admin." or "*." respectfully.
	Party(relativePath string, middleware ...context.Handler) Party
	// PartyFunc same as `Party`, groups routes that share a base path or/and same handlers.
	// However this function accepts a function that receives this created Party instead.
	// Returns the Party in order the caller to be able to use this created Party to continue the
	// top-bottom routes "tree".
	//
	// Note: `iris#Party` and `core/router#Party` describes the exactly same interface.
	//
	// Usage:
	// app.PartyFunc("/users", func(u iris.Party){
	//	u.Use(authMiddleware, logMiddleware)
	//	u.Get("/", getAllUsers)
	//	u.Post("/", createOrUpdateUser)
	//	u.Delete("/", deleteUser)
	// })
	//
	// Look `Party` for more.
	PartyFunc(relativePath string, partyBuilderFunc func(p Party)) Party
	// Subdomain returns a new party which is responsible to register routes to
	// this specific "subdomain".
	//
	// If called from a child party then the subdomain will be prepended to the path instead of appended.
	// So if app.Subdomain("admin").Subdomain("panel") then the result is: "panel.admin.".
	Subdomain(subdomain string, middleware ...context.Handler) Party

	// UseRouter upserts one or more handlers that will be fired
	// right before the main router's request handler.
	//
	// Use this method to register handlers, that can ran
	// independently of the incoming request's values,
	// that they will be executed ALWAYS against ALL children incoming requests.
	// Example of use-case: CORS.
	//
	// Note that because these are executed before the router itself
	// the Context should not have access to the `GetCurrentRoute`
	// as it is not decided yet which route is responsible to handle the incoming request.
	// It's one level higher than the `WrapRouter`.
	// The context SHOULD call its `Next` method in order to proceed to
	// the next handler in the chain or the main request handler one.
	UseRouter(handlers ...context.Handler)
	// UseError upserts one or more handlers that will be fired,
	// as middleware, before any error handler registered through `On(Any)ErrorCode`.
	// See `OnErrorCode` too.
	UseError(handlers ...context.Handler)
	// Use appends Handler(s) to the current Party's routes and child routes.
	// If the current Party is the root, then it registers the middleware to all child Parties' routes too.
	// To register a middleware for error handlers, look `UseError` method instead.
	Use(middleware ...context.Handler)
	// UseOnce either inserts a middleware,
	// or on the basis of the middleware already existing,
	// replace that existing middleware instead.
	// To register a middleware for error handlers, look `UseError` method instead.
	UseOnce(handlers ...context.Handler)
	// Done appends to the very end, Handler(s) to the current Party's routes and child routes.
	// The difference from .Use is that this/or these Handler(s) are being always running last.
	Done(handlers ...context.Handler)

	// Reset removes all the begin and done handlers that may derived from the parent party via `Use` & `Done`,
	// and the execution rules.
	// Note that the `Reset` will not reset the handlers that are registered via `UseGlobal` & `DoneGlobal`.
	//
	// Returns this Party.
	Reset() Party
	// ResetRouterFilters deactivates any previous registered
	// router filters and the parents ones for this Party.
	//
	// Returns this Party.
	ResetRouterFilters() Party

	// AllowMethods will re-register the future routes that will be registered
	// via `Handle`, `Get`, `Post`, ... to the given "methods" on that Party and its children "Parties",
	// duplicates are not registered.
	//
	// Call of `AllowMethod` will override any previous allow methods.
	AllowMethods(methods ...string) Party

	// SetExecutionRules alters the execution flow of the route handlers outside of the handlers themselves.
	//
	// For example, if for some reason the desired result is the (done or all) handlers to be executed no matter what
	// even if no `ctx.Next()` is called in the previous handlers, including the begin(`Use`),
	// the main(`Handle`) and the done(`Done`) handlers themselves, then:
	// Party#SetExecutionRules(iris.ExecutionRules {
	//   Begin: iris.ExecutionOptions{Force: true},
	//   Main:  iris.ExecutionOptions{Force: true},
	//   Done:  iris.ExecutionOptions{Force: true},
	// })
	//
	// Note that if : true then the only remained way to "break" the handler chain is by `ctx.StopExecution()` now that `ctx.Next()` does not matter.
	//
	// These rules are per-party, so if a `Party` creates a child one then the same rules will be applied to that as well.
	// Reset of these rules (before `Party#Handle`) can be done with `Party#SetExecutionRules(iris.ExecutionRules{})`.
	//
	// The most common scenario for its use can be found inside Iris MVC Applications;
	// when we want the `Done` handlers of that specific mvc app's `Party`
	// to be executed but we don't want to add `ctx.Next()` on the `OurController#EndRequest`.
	//
	// Returns this Party.
	//
	// Example: https://github.com/kataras/iris/tree/master/_examples/mvc/middleware/without-ctx-next
	SetExecutionRules(executionRules ExecutionRules) Party
	// SetRegisterRule sets a `RouteRegisterRule` for this Party and its children.
	// Available values are:
	// * RouteOverride (the default one)
	// * RouteSkip
	// * RouteError
	// * RouteOverlap.
	SetRegisterRule(rule RouteRegisterRule) Party

	// Handle registers a route to the server's router.
	// if empty method is passed then handler(s) are being registered to all methods, same as .Any.
	//
	// Returns the read-only route information.
	Handle(method string, registeredPath string, handlers ...context.Handler) *Route
	// HandleMany works like `Handle` but can receive more than one
	// paths separated by spaces and returns always a slice of *Route instead of a single instance of Route.
	//
	// It's useful only if the same handler can handle more than one request paths,
	// otherwise use `Party` which can handle many paths with different handlers and middlewares.
	//
	// Usage:
	// 	app.HandleMany(iris.MethodGet, "/user /user/{id:uint64} /user/me", userHandler)
	// At the other side, with `Handle` we've had to write:
	// 	app.Handle(iris.MethodGet, "/user", userHandler)
	// 	app.Handle(iris.MethodGet, "/user/{id:uint64}", userHandler)
	// 	app.Handle(iris.MethodGet, "/user/me", userHandler)
	//
	// This method is used behind the scenes at the `Controller` function
	// in order to handle more than one paths for the same controller instance.
	HandleMany(method string, relativePath string, handlers ...context.Handler) []*Route

	// HandleDir registers a handler that serves HTTP requests
	// with the contents of a file system (physical or embedded).
	//
	// first parameter  : the route path
	// second parameter : the file system needs to be served
	// third parameter  : not required, the serve directory options.
	//
	// Alternatively, to get just the handler for that look the FileServer function instead.
	//
	//     api.HandleDir("/static", iris.Dir("./assets"), iris.DirOptions{IndexName: "/index.html", Compress: true})
	//
	// Returns all the registered routes, including GET index and path patterm and HEAD.
	//
	// Usage:
	// HandleDir("/public", "./assets", DirOptions{...}) or
	// HandleDir("/public", iris.Dir("./assets"), DirOptions{...})
	//
	// Examples:
	// https://github.com/kataras/iris/tree/master/_examples/file-server
	HandleDir(requestPath string, fileSystem interface{}, opts ...DirOptions) []*Route

	// None registers an "offline" route
	// see context.ExecRoute(routeName) and
	// party.Routes().Online(handleResultregistry.*Route, "GET") and
	// Offline(handleResultregistry.*Route)
	//
	// Returns the read-only route information.
	None(path string, handlers ...context.Handler) *Route

	// Get registers a route for the Get HTTP Method.
	//
	// Returns the read-only route information.
	Get(path string, handlers ...context.Handler) *Route
	// Post registers a route for the Post HTTP Method.
	//
	// Returns the read-only route information.
	Post(path string, handlers ...context.Handler) *Route
	// Put registers a route for the Put HTTP Method.
	//
	// Returns the read-only route information.
	Put(path string, handlers ...context.Handler) *Route
	// Delete registers a route for the Delete HTTP Method.
	//
	// Returns the read-only route information.
	Delete(path string, handlers ...context.Handler) *Route
	// Connect registers a route for the Connect HTTP Method.
	//
	// Returns the read-only route information.
	Connect(path string, handlers ...context.Handler) *Route
	// Head registers a route for the Head HTTP Method.
	//
	// Returns the read-only route information.
	Head(path string, handlers ...context.Handler) *Route
	// Options registers a route for the Options HTTP Method.
	//
	// Returns the read-only route information.
	Options(path string, handlers ...context.Handler) *Route
	// Patch registers a route for the Patch HTTP Method.
	//
	// Returns the read-only route information.
	Patch(path string, handlers ...context.Handler) *Route
	// Trace registers a route for the Trace HTTP Method.
	//
	// Returns the read-only route information.
	Trace(path string, handlers ...context.Handler) *Route
	// Any registers a route for ALL of the HTTP methods:
	// Get
	// Post
	// Put
	// Delete
	// Head
	// Patch
	// Options
	// Connect
	// Trace
	Any(registeredPath string, handlers ...context.Handler) []*Route
	// CreateRoutes returns a list of Party-based Routes.
	// It does NOT registers the route. Use `Handle, Get...` methods instead.
	// This method can be used for third-parties Iris helpers packages and tools
	// that want a more detailed view of Party-based Routes before take the decision to register them.
	CreateRoutes(methods []string, relativePath string, handlers ...context.Handler) []*Route
	// StaticContent registers a GET and HEAD method routes to the requestPath
	// that are ready to serve raw static bytes, memory cached.
	//
	// Returns the GET *Route.
	StaticContent(requestPath string, cType string, content []byte) *Route
	// Favicon serves static favicon
	// accepts 2 parameters, second is optional
	// favPath (string), declare the system directory path of the __.ico
	// requestPath (string), it's the route's path, by default this is the "/favicon.ico" because some browsers tries to get this by default first,
	// you can declare your own path if you have more than one favicon (desktop, mobile and so on)
	//
	// this func will add a route for you which will static serve the /yuorpath/yourfile.ico to the /yourfile.ico
	// (nothing special that you can't handle by yourself).
	// Note that you have to call it on every favicon you have to serve automatically (desktop, mobile and so on).
	//
	// Returns the GET *Route.
	Favicon(favPath string, requestPath ...string) *Route

	// RegisterView registers and loads a view engine middleware for that group of routes.
	// It overrides any of the application's root registered view engines.
	// To register a view engine per handler chain see the `Context.ViewEngine` instead.
	// Read `Configuration.ViewEngineContextKey` documentation for more.
	RegisterView(viewEngine context.ViewEngine)
	// Layout overrides the parent template layout with a more specific layout for this Party.
	// It returns the current Party.
	//
	// The "tmplLayoutFile" should be a relative path to the templates dir.
	// Usage:
	//
	// app := iris.New()
	// app.RegisterView(iris.$VIEW_ENGINE("./views", ".$extension"))
	// my := app.Party("/my").Layout("layouts/mylayout.html")
	// 	my.Get("/", func(ctx iris.Context) {
	// 		ctx.View("page1.html")
	// 	})
	//
	// Examples: https://github.com/kataras/iris/tree/master/_examples/view
	Layout(tmplLayoutFile string) Party
}

Party is just a group joiner of routes which have the same prefix and share same middleware(s) also. Party could also be named as 'Join' or 'Node' or 'Group' , Party chosen because it is fun.

Look the `APIBuilder` structure for its implementation.

type PartyMatcher added in v12.2.0

type PartyMatcher interface {
	Match(ctx *context.Context) bool
}

PartyMatcher decides if `UseRouter` handlers should be executed or not. A different interface becauwe we want to separate the Party's public API from `UseRouter` internals.

type PartyMatcherFunc added in v12.2.0

type PartyMatcherFunc func(*context.Context, Party) bool

PartyMatcherFunc used to build a filter which decides if the given Party is responsible to fire its `UseRouter` handlers or not. Can be customized through `SetPartyMatcher` method. See `Match` method too.

type RequestHandler

type RequestHandler interface {
	// Note: A different interface in order  to hide the rest of the implementation.
	// We only need the `FireErrorCode` to be accessible through the Iris application (see `iris.go#Build`)
	HTTPErrorHandler

	// HandleRequest should handle the request based on the Context.
	HandleRequest(ctx *context.Context)
	// Build should builds the handler, it's being called on router's BuildRouter.
	Build(provider RoutesProvider) error
	// RouteExists reports whether a particular route exists.
	RouteExists(ctx *context.Context, method, path string) bool
}

RequestHandler the middle man between acquiring a context and releasing it. By-default is the router algorithm.

func NewDefaultHandler

func NewDefaultHandler(config context.ConfigurationReadOnly, logger *golog.Logger) RequestHandler

NewDefaultHandler returns the handler which is responsible to map the request with a route (aka mux implementation).

type Route

type Route struct {
	Title       string `json:"title"`       // custom name to replace the method on debug logging.
	Name        string `json:"name"`        // "userRoute"
	Description string `json:"description"` // "lists a user"
	Method      string `json:"method"`      // "GET"
	StatusCode  int    `json:"statusCode"`  // 404 (only for HTTP error handlers).

	Subdomain string `json:"subdomain"` // "admin."

	// Handlers are the main route's handlers, executed by order.
	// Cannot be empty.
	Handlers         context.Handlers `json:"-"`
	MainHandlerName  string           `json:"mainHandlerName"`
	MainHandlerIndex int              `json:"mainHandlerIndex"`

	Path string `json:"path"` // the underline router's representation, i.e "/api/user/:id"
	// FormattedPath all dynamic named parameters (if any) replaced with %v,
	// used by Application to validate param values of a Route based on its name.
	FormattedPath string `json:"formattedPath"`

	// the source code's filename:filenumber that this route was created from.
	SourceFileName   string `json:"sourceFileName"`
	SourceLineNumber int    `json:"sourceLineNumber"`

	// where the route registered.
	RegisterFileName   string `json:"registerFileName"`
	RegisterLineNumber int    `json:"registerLineNumber"`

	// Sitemap properties: https://www.sitemaps.org/protocol.html
	NoSitemap  bool      // when this route should be hidden from sitemap.
	LastMod    time.Time `json:"lastMod,omitempty"`
	ChangeFreq string    `json:"changeFreq,omitempty"`
	Priority   float32   `json:"priority,omitempty"`

	// ReadOnly is the read-only structure of the Route.
	ReadOnly context.RouteReadOnly

	// OnBuild runs right before BuildHandlers.
	OnBuild func(r *Route)
	NoLog   bool // disables debug logging.
	// contains filtered or unexported fields
}

Route contains the information about a registered Route. If any of the following fields are changed then the caller should Refresh the router.

func NewRoute

func NewRoute(statusErrorCode int, method, subdomain, unparsedPath string,
	handlers context.Handlers, macros macro.Macros) (*Route, error)

NewRoute returns a new route based on its method, subdomain, the path (unparsed or original), handlers and the macro container which all routes should share. It parses the path based on the "macros", handlers are being changed to validate the macros at serve time, if needed.

func (*Route) BuildHandlers

func (r *Route) BuildHandlers()

BuildHandlers is executed automatically by the router handler at the `Application#Build` state. Do not call it manually, unless you were defined your own request mux handler.

func (*Route) ChangeMethod

func (r *Route) ChangeMethod(newMethod string) bool

ChangeMethod will try to change the HTTP Method of this route instance. A call of `RefreshRouter` is required after this type of change in order to change to be really applied.

func (*Route) DeepEqual

func (r *Route) DeepEqual(other *Route) bool

DeepEqual compares the method, subdomain, the underline representation of the route's path, and the template source.

func (*Route) Describe added in v12.2.0

func (r *Route) Describe(description string) *Route

Describe sets the route's description that will be logged alongside with the route information in DEBUG log level. Returns the `Route` itself.

func (*Route) Done

func (r *Route) Done(handlers ...context.Handler)

Done adds explicit finish handlers to this route. Alternatively the end-dev can append to the `Handlers` field. Should be used before the `BuildHandlers` which is called by the framework itself on `Application#Run` (build state).

Used internally at `APIBuilder#DoneGlobal` -> `doneGlobalHandlers` -> `APIBuilder#Handle`.

func (*Route) Equal

func (r *Route) Equal(other *Route) bool

Equal compares the method, subdomain and the underline representation of the route's path, instead of the `String` function which returns the front representation.

func (*Route) ExcludeSitemap added in v12.2.0

func (r *Route) ExcludeSitemap() *Route

ExcludeSitemap excludes this route page from sitemap generator. It sets the NoSitemap field to true.

See `SetLastMod`, `SetChangeFreq`, `SetPriority` methods and `iris.WithSitemap`.

func (*Route) GetTitle added in v12.2.0

func (r *Route) GetTitle() string

GetTitle returns the custom Title or the method or the error code.

func (*Route) IsOnline

func (r *Route) IsOnline() bool

IsOnline returns true if the route is marked as "online" (state).

func (*Route) IsStatic added in v12.1.1

func (r *Route) IsStatic() bool

IsStatic reports whether this route is a static route. Does not contain dynamic path parameters, is online and registered on GET HTTP Method.

func (*Route) RegisteredHandlersLen

func (r *Route) RegisteredHandlersLen() int

RegisteredHandlersLen returns the end-developer's registered handlers, all except the macro evaluator handler if was required by the build process.

func (*Route) ResolvePath

func (r *Route) ResolvePath(args ...string) string

ResolvePath returns the formatted path's %v replaced with the args.

func (*Route) RestoreStatus

func (r *Route) RestoreStatus() bool

RestoreStatus will try to restore the status of this route instance, i.e if `SetStatusOffline` called on a "GET" route, then this function will make this route available with "GET" HTTP Method. Note if that you want to set status online for an offline registered route then you should call the `ChangeMethod` instead. It will return true if the status restored, otherwise false. A call of `RefreshRouter` is required after this type of change in order to change to be really applied.

func (*Route) SetChangeFreq added in v12.1.0

func (r *Route) SetChangeFreq(freq string) *Route

SetChangeFreq sets how frequently this static GET route's page is likely to change, possible values: - "always" - "hourly" - "daily" - "weekly" - "monthly" - "yearly" - "never"

func (*Route) SetLastMod added in v12.1.0

func (r *Route) SetLastMod(t time.Time) *Route

SetLastMod sets the date of last modification of the file served by this static GET route.

func (*Route) SetPriority added in v12.1.0

func (r *Route) SetPriority(prio float32) *Route

SetPriority sets the priority of this static GET route's URL relative to other URLs on your site.

func (*Route) SetSourceLine added in v12.2.0

func (r *Route) SetSourceLine(fileName string, lineNumber int) *Route

SetSourceLine sets the route's source caller, useful for debugging. Returns the `Route` itself.

func (*Route) SetStatusOffline

func (r *Route) SetStatusOffline() bool

SetStatusOffline will try make this route unavailable. A call of `RefreshRouter` is required after this type of change in order to change to be really applied.

func (*Route) StaticPath

func (r *Route) StaticPath() string

StaticPath returns the static part of the original, registered route path. if /user/{id} it will return /user if /user/{id}/friend/{friendid:uint64} it will return /user too if /assets/{filepath:path} it will return /assets.

func (*Route) String

func (r *Route) String() string

String returns the form of METHOD, SUBDOMAIN, TMPL PATH.

func (*Route) Tmpl

func (r *Route) Tmpl() macro.Template

Tmpl returns the path template, it contains the parsed template for the route's path. May contain zero named parameters.

Developer can get his registered path via Tmpl().Src, Route.Path is the path converted to match the underline router's specs.

func (*Route) Trace

func (r *Route) Trace(w io.Writer, stoppedIndex int)

Trace prints some debug info about the Route to the "w". Should be called after `Build` state.

It prints the @method: @path (@description) (@route_rel_location)

  • @handler_name (@handler_rel_location)
  • @second_handler ...

If route and handler line:number locations are equal then the second is ignored.

func (*Route) Use

func (r *Route) Use(handlers ...context.Handler)

Use adds explicit begin handlers to this route. Alternatively the end-dev can prepend to the `Handlers` field. Should be used before the `BuildHandlers` which is called by the framework itself on `Application#Run` (build state).

Used internally at `APIBuilder#UseGlobal` -> `beginGlobalHandlers` -> `APIBuilder#Handle`.

type RoutePathReverser

type RoutePathReverser struct {
	// contains filtered or unexported fields
}

RoutePathReverser contains methods that helps to reverse a (dynamic) path from a specific route, route name is required because a route may being registered on more than one http method.

func NewRoutePathReverser

func NewRoutePathReverser(apiRoutesProvider RoutesProvider, options ...RoutePathReverserOption) *RoutePathReverser

NewRoutePathReverser returns a new path reverser based on a routes provider, needed to get a route based on its name. Options is required for the URL function. See WithScheme and WithHost or WithServer.

func (*RoutePathReverser) Path

func (ps *RoutePathReverser) Path(routeName string, paramValues ...interface{}) string

Path returns a route path based on a route name and any dynamic named parameter's values-only.

func (*RoutePathReverser) URL

func (ps *RoutePathReverser) URL(routeName string, paramValues ...interface{}) (url string)

URL same as Path but returns the full uri, i.e https://mysubdomain.mydomain.com/hello/iris

type RoutePathReverserOption

type RoutePathReverserOption func(*RoutePathReverser)

RoutePathReverserOption option signature for the RoutePathReverser.

func WithHost

func WithHost(host string) RoutePathReverserOption

WithHost enables the RoutePathReverser's URL feature. Both "WithHost" and "WithScheme" can be different from the real server's listening address, i.e nginx in front.

func WithScheme

func WithScheme(scheme string) RoutePathReverserOption

WithScheme is an option for the RoutepathReverser, it sets the optional field "vscheme", v for virtual. if vscheme is empty then it will try to resolve it from the RoutePathReverser's vhost field.

See WithHost or WithServer to enable the URL feature.

func WithServer

func WithServer(srv *http.Server) RoutePathReverserOption

WithServer enables the RoutePathReverser's URL feature. It receives an *http.Server and tries to resolve a scheme and a host to be used in the URL function.

type RouteRegisterRule added in v12.1.7

type RouteRegisterRule uint8

RouteRegisterRule is a type of uint8. Defines the register rule for new routes that already exists. Available values are: RouteOverride, RouteSkip and RouteError.

See `Party#SetRegisterRule`.

const (
	// RouteOverride replaces an existing route with the new one, the default rule.
	RouteOverride RouteRegisterRule = iota
	// RouteSkip keeps the original route and skips the new one.
	RouteSkip
	// RouteError log when a route already exists, shown after the `Build` state,
	// server never starts.
	RouteError
	// RouteOverlap will overlap the new route to the previous one.
	// If the route stopped and its response can be reset then the new route will be execute.
	RouteOverlap
)

type Router

type Router struct {
	// contains filtered or unexported fields
}

Router is the "director". Caller should provide a request handler (router implementation or root handler). Router is responsible to build the received request handler and run it to serve requests, based on the received context.Pool.

User can refresh the router with `RefreshRouter` whenever a route's field is changed by him.

func NewRouter

func NewRouter() *Router

NewRouter returns a new empty Router.

func (*Router) AddRouteUnsafe added in v12.1.0

func (router *Router) AddRouteUnsafe(routes ...*Route) error

AddRouteUnsafe adds a route directly to the router's request handler. Works before or after Build state. Mainly used for internal cases like `iris.WithSitemap`. Do NOT use it on serve-time.

func (*Router) AddRouterWrapper added in v12.2.0

func (router *Router) AddRouterWrapper(wrapperFunc WrapperFunc)

AddRouterWrapper adds a router wrapper. Unlike `WrapRouter` the first registered will be executed first so a wrapper wraps its next not the previous one. it defers the wrapping until the `BuildRouter`. Redirection wrappers should be added using this method e.g. SubdomainRedirect.

func (*Router) BuildRouter

func (router *Router) BuildRouter(cPool *context.Pool, requestHandler RequestHandler, routesProvider RoutesProvider, force bool) error

BuildRouter builds the router based on the context factory (explicit pool in this case), the request handler which manages how the main handler will multiplexes the routes provided by the third parameter, routerProvider (it's the api builder in this case) and its wrapper.

Use of RefreshRouter to re-build the router if needed.

func (*Router) Downgrade

func (router *Router) Downgrade(newMainHandler http.HandlerFunc)

Downgrade "downgrades", alters the router supervisor service(Router.mainHandler) algorithm to a custom one, be aware to change the global variables of 'ParamStart' and 'ParamWildcardStart'. can be used to implement a custom proxy or a custom router which should work with raw ResponseWriter, *Request instead of the Context(which again, can be retrieved by the Framework's context pool).

Note: Downgrade will by-pass the Wrapper, the caller is responsible for everything. Downgrade is thread-safe.

func (*Router) Downgraded

func (router *Router) Downgraded() bool

Downgraded returns true if this router is downgraded.

func (*Router) FindClosestPaths added in v12.1.1

func (router *Router) FindClosestPaths(subdomain, searchPath string, n int) []string

FindClosestPaths returns a list of "n" paths close to "path" under the given "subdomain".

Order may change.

func (*Router) PrependRouterWrapper added in v12.2.0

func (router *Router) PrependRouterWrapper(wrapperFunc WrapperFunc)

PrependRouterWrapper like `AddRouterWrapper` but this wrapperFunc will always be executed before the previous `AddRouterWrapper`. Path form (no modification) wrappers should be added using this method e.g. ForceLowercaseRouting.

func (*Router) RefreshRouter

func (router *Router) RefreshRouter() error

RefreshRouter re-builds the router. Should be called when a route's state changed (i.e Method changed at serve-time).

func (*Router) RouteExists

func (router *Router) RouteExists(ctx *context.Context, method, path string) bool

RouteExists reports whether a particular route exists It will search from the current subdomain of context's host, if not inside the root domain.

func (*Router) ServeHTTP

func (router *Router) ServeHTTP(w http.ResponseWriter, r *http.Request)

func (*Router) ServeHTTPC

func (router *Router) ServeHTTPC(ctx *context.Context)

ServeHTTPC serves the raw context, useful if we have already a context, it by-pass the wrapper.

func (*Router) WrapRouter

func (router *Router) WrapRouter(wrapperFunc WrapperFunc)

WrapRouter adds a wrapper on the top of the main router. Usually it's useful for third-party middleware when need to wrap the entire application with a middleware like CORS.

Developers can add more than one wrappers, those wrappers' execution comes from last to first. That means that the second wrapper will wrap the first, and so on.

Before build.

type RoutesProvider

type RoutesProvider interface {
	GetRoutes() []*Route
	GetRoute(routeName string) *Route
	// GetRouterFilters returns the app's router filters.
	// Read `UseRouter` for more.
	// The map can be altered before router built.
	GetRouterFilters() map[Party]*Filter
	// GetDefaultErrorMiddleware should return
	// the default error handler middleares.
	GetDefaultErrorMiddleware() context.Handlers
}

RoutesProvider should be implemented by iteral which contains the registered routes.

type WrapperFunc

type WrapperFunc func(w http.ResponseWriter, r *http.Request, router http.HandlerFunc)

WrapperFunc is used as an expected input parameter signature for the WrapRouter. It's a "low-level" signature which is compatible with the net/http. It's being used to run or no run the router based on a custom logic.

func NewSubdomainRedirectWrapper

func NewSubdomainRedirectWrapper(rootDomainGetter func() string, from, to string) WrapperFunc

NewSubdomainRedirectWrapper returns a router wrapper which if it's registered to the router via `router#WrapRouter` it redirects(StatusMovedPermanently) a subdomain or the root domain to another subdomain or to the root domain.

It receives three arguments, the first one is a function which returns the root domain, (in the application it's the app.ConfigurationReadOnly().GetVHost()). The second and third are the from and to locations, 'from' can be a wildcard subdomain as well (*. or *) 'to' is not allowed to be a wildcard for obvious reasons, 'from' can be the root domain when the 'to' is not the root domain and visa-versa. To declare a root domain as 'from' or 'to' you MUST pass an empty string or a slash('/') or a dot('.'). Important note: the 'from' and 'to' should end with "." like we use the `APIBuilder#Party`, if they are subdomains.

Usage(package-level): sd := NewSubdomainRedirectWrapper(func() string { return "mydomain.com" }, ".", "www.") router.AddRouterWrapper(sd)

Usage(high-level using `iris#Application.SubdomainRedirect`) www := app.Subdomain("www") app.SubdomainRedirect(app, www) Because app's rel path is "/" it translates it to the root domain and www's party's rel path is the "www.", so it's the target subdomain.

All the above code snippets will register a router wrapper which will redirect all http(s)://mydomain.com/%anypath% to http(s)://www.mydomain.com/%anypath%.

One or more subdomain redirect wrappers can be used to the same router instance.

NewSubdomainRedirectWrapper may return nil if not allowed input arguments values were received but in that case, the `AddRouterWrapper` will, simply, ignore that wrapper.

Example: https://github.com/kataras/iris/tree/master/_examples/routing/subdomains/redirect

Jump to

Keyboard shortcuts

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