router

package
v14.0.0 Latest Latest
Warning

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

Go to latest
Published: Nov 12, 2026 License: BSD-3-Clause Imports: 31 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// MethodNone is a Virtual method
	// to store the "offline" routes.
	MethodNone = "NONE"

	MethodGet     = "GET"
	MethodHead    = "HEAD"
	MethodPost    = "POST"
	MethodPut     = "PUT"
	MethodPatch   = "PATCH" // RFC 5789
	MethodDelete  = "DELETE"
	MethodConnect = "CONNECT"
	MethodOptions = "OPTIONS"
	MethodTrace   = "TRACE"
	// MethodQuery is the RFC 10008 QUERY method: safe, idempotent,
	// carries a request body and its response is cacheable.
	// It becomes http.MethodQuery once go.mod requires Go 1.28.
	MethodQuery = "QUERY"
)
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 (
	// NoRouteName is the name of the default 404 not found route.
	NoRouteName = "NO_ROUTE"
	// NoMethodName is the name of the default 405 method not allowed route.
	NoMethodName = "NO_METHOD"
	// PreRoutingName is the name of the default pre-routing route.
	PreRoutingName = "PRE_ROUTING"
)
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 = "*"
)

Variables

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

Functions

func CleanPath

func CleanPath(path string) string

CleanPath applies the following rules iteratively until no further processing can be done:

  1. Replace multiple slashes with a single slash.
  2. Replace '\' with '/'
  3. Replace "\\" with '/'
  4. Ignore anything inside '{' and '}' (dynamic path parameter)
  5. Makes sure that prefixed with '/'
  6. Remove any trailing '/'.

The returned path ends in a slash only if it is the root "/". The function does not modify the dynamic path parts.

func JoinMethods

func JoinMethods(methods ...string) string

JoinMethods joins the given methods with a space into one string.

func JoinPath

func JoinPath(path1 string, path2 string) string

JoinPath joins the given paths with a slash.

func Param

func Param(name string) string

Param receives a parameter name prefixed with the ParamStart symbol.

func RedirectAbsolute

func RedirectAbsolute(ctx *context.Context, 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 RegisterControllerResolver

func RegisterControllerResolver(resolver ControllerResolver)

RegisterControllerResolver registers a new ControllerResolver. It's useful when you want to register a custom controller resolver. The last registered resolver has the highest priority. Use it before of the `Router.Router` method call.

It can register any method that can resolve a Controller directly or even after its dependencies are resolved from a function outputs the controller.

func RegisterMethods

func RegisterMethods(newCustomHTTPVerbs ...string)

RegisterMethods adds custom http methods to the "AllMethods" list. Use it on initialization of your program.

func RemoveDuplicates

func RemoveDuplicates[T comparable](elements []T) []T

RemoveDuplicates removes the duplicated elements from a slice of T.

func SplitMethod

func SplitMethod(methodMany string) []string

SplitMethod splits the given method with a comma or space.

func SplitPath

func SplitPath(pathMany string) (paths []string)

SplitPath splits the given paths, which are separated by a space (e.g. "/user /admin"), and returns each one of them prefixed with a slash. A single path is returned as it is.

func SplitSubdomainAndPath

func SplitSubdomainAndPath(fullUnparsedPath string) (subdomain string, path string)

SplitSubdomainAndPath checks if the path has subdomain and if it's it splits the subdomain and path and returns them, otherwise it returns an empty subdomain and the clean path.

First return value is the subdomain, second is the path.

func TraceTitleColorCode

func TraceTitleColorCode(method string) int

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

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.

func WithPrefix

func WithPrefix(s string, prefix string) string

WithPrefix returns the given string prefixed with the given prefix if it's not already prefixed.

Types

type AddRouteError

type AddRouteError struct {
	New *Route
	Old *Route
}

AddRouteError is the error type for the `Add` method of route repository when the register rule is `RouteError“ and a route conflicts with an already registered one.

func (*AddRouteError) Error

func (e *AddRouteError) Error() string

type Controller

type Controller interface {
	// Routing should register the routes of the controller.
	Routing(child Router)
}

Controller is an interface which all child routers that are registered through `Controller` should implement.

func Dependencies

func Dependencies(deps ...any) Controller

Dependencies returns a Controller which can be used to register dependencies to the controllers follows in the same `Router.Router` method call. By default controllers will inherit the dependencies registered to the Router, this method overrides the inherited dependencies for the controllers only.

Useful when you have the same interface declared for different services that can be binded to more than one controller.

func Join

func Join(controllers ...any) Controller

Join is a Controller helper which can be used as a shortcut to join multiple controllers into one. Useful when you want to group multiple controllers under the same path and the call expects a single Controller output parameter.

func Middleware

func Middleware(handlers ...context.Handler) Controller

Middleware is a Controller helper which can be used as a shortcut to add middlewares on Router.Router("/path", Middleware(handler), new(example.API)).

func Prefix

func Prefix(relativePath string, controllers ...any) Controller

Prefix is a Controller helper which can be used as a shortcut to add a relative path to all controllers passed to it.

func ResolveController

func ResolveController[T any]() Controller

ResolveController returns a Controller which was already registered as a dependency to the Router before.

type ControllerResolver

type ControllerResolver func(any) (Controller, bool)

ControllerResolver turns an arbitrary value into a Controller. It reports false when the value is none of its business, so the next resolver gets a turn. See RegisterControllerResolver.

type Route

type Route struct {
	Properties  context.Map // Properties (map) coming from the Router this route belongs to.
	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"
	Subdomain   string      `json:"subdomain"`   // "admin."

	// MiddlewareList contains the middleware handlers as they given by the end-developer (router builder).
	MiddlewareList *context.HandlerList `json:"middleware_list"`
	// MainHandlerList contains the main handlers as they given by the end-developer (router builder).
	MainHandlerList *context.HandlerList `json:"main_handler_list"`

	// HandlerList contains the middleware and main handlers.
	// They are built after BuildHandlers method (except newEmptyRoute).
	HandlerList *context.HandlerList `json:"handler_list"`

	// Handlers are the main route's handlers, executed by order.
	// Cannot be empty. Empty until built by the BuildHandlers method.
	Handlers context.Handlers `json:"-"`

	// Path is the registered path part (without subdomain), i.e "/api/user/{id:uint64}".
	// Shortcut of Tmpl().Src.
	Path string `json:"path"` // the registered path, i.e "/api/user/{id:uuid}"

	// NodePath is the underline router's representation, i.e "/api/user/:id".
	NodePath string `json:"node_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:"formatted_path"`

	// Initialized on buildHandlers and used for the trace.
	MainHandlerName  string `json:"main_handler_name"`
	MainHandlerIndex int    `json:"main_handler_index"`

	// the source code's filename:filenumber that this route was registered on.
	RegisterFileName   string `json:"register_filename"`
	RegisterLineNumber int    `json:"register_line_number"`

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

	// OnBuild runs right before BuildHandlers.
	OnBuild func(r *Route)
	NoLog   bool // disables debug logging for this route.
	// 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(router *RouterBuilder,
	method, relativePath, pattern string,
	middlewareList, mainHandlersList *context.HandlerList) (*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) 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

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) 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

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 the `sitemap.New` controller of the github.com/kataras/iris/v14/controller/sitemap package too.

func (*Route) GetChangeFreq

func (r *Route) GetChangeFreq() string

GetChangeFreq returns the the page frequently is likely to change.

func (*Route) GetHandlerList

func (r *Route) GetHandlerList() *context.HandlerList

GetHandlerList returns the route's handler list. It contains all handlers, middleware and main handlers. It's available only after BuildHandlers method.

func (*Route) GetLastMod

func (r *Route) GetLastMod() time.Time

GetLastMod returns the date of last modification of the file served by this static GET route.

func (*Route) GetMainHandlerIndex

func (r *Route) GetMainHandlerIndex() int

GetMainHandlerIndex returns the index of the route's main handler inside the MainHandlerList, that is the index of its last handler.

func (*Route) GetMainHandlerName

func (r *Route) GetMainHandlerName() string

GetMainHandlerName returns the name of the route's main handler, that is the last handler registered in the MainHandlerList.

func (*Route) GetMethod

func (r *Route) GetMethod() string

GetMethod returns the route's method.

func (*Route) GetName

func (r *Route) GetName() string

GetName returns the route's name.

func (*Route) GetPath

func (r *Route) GetPath() string

GetPath returns the route's original registered path.

func (*Route) GetPriority

func (r *Route) GetPriority() float32

GetPriority returns the priority of this route's URL relative to other URLs on your site.

func (*Route) GetProperty

func (r *Route) GetProperty(key string) (any, bool)

GetProperty returns a specific property based on its "key" of this route's Router owner.

func (*Route) GetRegisterFileName

func (r *Route) GetRegisterFileName() string

GetRegisterFileName returns the file name that this route was registered on.

func (*Route) GetRegisterLineNumber

func (r *Route) GetRegisterLineNumber() int

GetRegisterLineNumber returns the line number that this route was registered on.

func (*Route) GetSubdomain

func (r *Route) GetSubdomain() string

GetSubdomain returns the route's subdomain.

func (*Route) GetTitle

func (r *Route) GetTitle() string

GetTitle returns the custom Title or the method.

func (*Route) IsMethodNotAllowed

func (r *Route) IsMethodNotAllowed() bool

IsMethodNotAllowed reports whether this route is a no-method (405, method not allowed, fired by the serve mux). Access of the forbidden request method is gain by `ctx.Method()` and allowed methods through "Allow" response header.

func (*Route) IsNoRoute

func (r *Route) IsNoRoute() bool

IsNoRoute reports whether this route is a no-route (404, fired by the serve mux). Access of the not found path is gain by `ctx.Path()`.

func (*Route) IsOnline

func (r *Route) IsOnline() bool

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

func (*Route) IsPreRouting

func (r *Route) IsPreRouting() bool

IsPreRouting reports whether this route is running before the main serve mux. Means that this Route's Handlers are running under `UseRouter`.

func (*Route) IsRoute

func (r *Route) IsRoute() bool

IsRoute reports whether this route is a registered, end-developer route (not a built-in 404 or 405 one, and not nil). Note that the pre-routing slot reports true as well, see `IsPreRouting`.

func (*Route) IsSitemapDisabled

func (r *Route) IsSitemapDisabled() bool

IsSitemapDisabled reports whether this route is excluded from the sitemap.

func (*Route) IsStatic

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) Router

func (r *Route) Router() context.Router

Router returns the read-only router that this route belongs to.

func (*Route) SetCaller

func (r *Route) SetCaller(fileName string, fileLine int)

SetCaller sets the route's source caller, useful for debugging.

func (*Route) SetChangeFreq

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

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) SetName

func (r *Route) SetName(newRouteName string) *Route

SetName overrides the default route name which defaults to method + subdomain + path and statusErrorCode_method+subdomain+path for error routes.

Note that the route name MUST BE unique per Iris Application.

func (*Route) SetPriority

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) SetSourceByMethodType

func (r *Route) SetSourceByMethodType(typ reflect.Type, methodName string)

SetSourceByMethodType sets the route's source caller based on the method's type and name.

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.

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(routes *RouteRegistry, 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.

Example: ps := NewRoutePathReverser(app.Routes(), router.WithHost(host), router.WithScheme("http"))

func (*RoutePathReverser) Path

func (ps *RoutePathReverser) Path(routeName string, paramValues ...any) 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 ...any) (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

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 `Router#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
)

func (RouteRegisterRule) String

func (rule RouteRegisterRule) String() string

type RouteRegistry

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

RouteRegistry contains an unexported slice of *Route. It's used to store and manage the registered routes before `Application.Listen`.

func (*RouteRegistry) Add

func (repo *RouteRegistry) Add(route *Route) (*Route, error)

Add registers a route to the list of routes before `Application.Listen`. Returns the route and an error if such route already exists and the `rule` is `RouteError`. If the `rule` is `RouteSkip` then it returns the existing route and nil error. If the `rule` is `RouteOverride` then it replaces the existing route with the new one and returns the new route and nil error.

func (*RouteRegistry) Build

func (repo *RouteRegistry) Build() []*Route

Build sorts the underline slice of routes and returns it, it's a kind of a "build" method.

func (*RouteRegistry) Connect

func (repo *RouteRegistry) Connect() *Route

Connect returns the first route that its method is "CONNECT".

func (*RouteRegistry) CopyRoutes

func (repo *RouteRegistry) CopyRoutes(otherRepo *RouteRegistry)

CopyRoutes adds one or more routes to the list of routes of another repository. It does not check for anything (like Add does). It's only used by internal methods.

func (*RouteRegistry) CountHandlers

func (repo *RouteRegistry) CountHandlers() int

CountHandlers returns the size of the unique handlers that are registered.

func (*RouteRegistry) Delete

func (repo *RouteRegistry) Delete() *Route

Delete returns the first route that its method is "DELETE".

func (*RouteRegistry) First

func (repo *RouteRegistry) First() *Route

First returns the first route of the list. Returns nil if the list is empty.

func (*RouteRegistry) Get

func (repo *RouteRegistry) Get() *Route

Get returns the first route that its method is "GET".

func (*RouteRegistry) GetByIndex

func (repo *RouteRegistry) GetByIndex(index int) *Route

GetByIndex returns the route by its index.

func (*RouteRegistry) GetByMethod

func (repo *RouteRegistry) GetByMethod(method string) *Route

GetByMethod returns the first route that its method is equal to the "method" argument.

func (*RouteRegistry) GetByMethodAndPath

func (repo *RouteRegistry) GetByMethodAndPath(method, path string) *Route

GetByMethodAndPath returns the first route that its method and path are equal to the "method" and "path" arguments.

func (*RouteRegistry) GetByName

func (repo *RouteRegistry) GetByName(name string) *Route

GetByName returns the first route that its name is equal to the "name" argument.

func (*RouteRegistry) GetByPath

func (repo *RouteRegistry) GetByPath(tmplPath string) *Route

GetByPath returns the first route that its path is equal to the "tmplPath" argument.

func (*RouteRegistry) GetIndexByName

func (repo *RouteRegistry) GetIndexByName(routeName string) int

GetIndexByName returns the index of the route by its name.

func (*RouteRegistry) GetRelative

func (repo *RouteRegistry) GetRelative(r *Route) *Route

GetRelative returns the first non-trailing route that its subdomain, method and formatted path is equal to the given one's, i.e. the same path registered with different parameter types. Routes with the identical path template are skipped. Returns nil if not found.

func (*RouteRegistry) Head

func (repo *RouteRegistry) Head() *Route

Head returns the first route that its method is "HEAD".

func (*RouteRegistry) Last

func (repo *RouteRegistry) Last() *Route

Last returns the last route of the list.

func (*RouteRegistry) Len

func (repo *RouteRegistry) Len() int

Len returns the length of the routes.

func (*RouteRegistry) List

func (repo *RouteRegistry) List() []*Route

List returns the slice of the registered routes as it is.

func (*RouteRegistry) ListByMethod

func (repo *RouteRegistry) ListByMethod(method string) *RouteRegistry

ListByMethod returns a new RouteRegistry which contains the routes that their method is equal to the "method" argument.

func (*RouteRegistry) ListByPattern

func (repo *RouteRegistry) ListByPattern(pattern string) *RouteRegistry

ListByPattern returns the routes that their (relative) pattern is equal to the "pattern" argument.

func (*RouteRegistry) ListSubdomains

func (repo *RouteRegistry) ListSubdomains() []string

ListSubdomains returns the list of subdomains that are registered before Build. It's empty until the Build method is called.

func (*RouteRegistry) New

func (repo *RouteRegistry) New(n int) *RouteRegistry

New returns a new empty RouteRegistry with the same route register rule as the current "repo". It panics if the receiver is nil.

func (*RouteRegistry) Options

func (repo *RouteRegistry) Options() *Route

Options returns the first route that its method is "OPTIONS".

func (*RouteRegistry) Patch

func (repo *RouteRegistry) Patch() *Route

Patch returns the first route that its method is "PATCH".

func (*RouteRegistry) Post

func (repo *RouteRegistry) Post() *Route

Post returns the first route that its method is "POST".

func (*RouteRegistry) Put

func (repo *RouteRegistry) Put() *Route

Put returns the first route that its method is "PUT".

func (*RouteRegistry) Query

func (repo *RouteRegistry) Query() *Route

Query returns the first route that its method is "QUERY".

func (*RouteRegistry) RemoveByIndex

func (repo *RouteRegistry) RemoveByIndex(indexToDelete int) bool

RemoveByIndex deletes a registered route by its index before `Application.Listen`.

func (*RouteRegistry) RemoveByName

func (repo *RouteRegistry) RemoveByName(routeName string) bool

RemoveByName deletes a registered route by its name before `Application.Listen`. The default naming for newly created routes is: method + subdomain + path. Reports whether a route with that name was found and removed successfully.

Note that this method applies to all Parties (sub routers) even if each of the Parties have access to this method, as the route name is unique per Iris Application.

func (*RouteRegistry) SetRegisterRule

func (repo *RouteRegistry) SetRegisterRule(rule RouteRegisterRule)

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

func (*RouteRegistry) SetSourceByMethodType

func (repo *RouteRegistry) SetSourceByMethodType(typ reflect.Type, methodName string)

SetSourceByMethodType sets the source caller of the routes by the method's type.

func (*RouteRegistry) Trace

func (repo *RouteRegistry) Trace() *Route

Trace returns the first route that its method is "TRACE".

type Router

type Router interface {
	context.Router

	// Application returns the read-only application.
	// Can be casted as *iris.Application and used to access the application's properties and methods
	// on Router Controllers.
	Application() context.Application
	// IsRoot reports whether this Router is the root Application's one.
	// It will return false on all children Routers, no exception.
	IsRoot() bool

	// GetRoot returns the very first Router (the Application's Router Builder).
	GetRoot() *RouterBuilder

	// Routes returns the route repository.
	// It's been used by the `ServeMux` and `Application` to register the routes
	// on Handle, Get, Post and so on.
	Routes() *RouteRegistry
	// GetRelPath returns the current Router's relative path.
	// i.e:
	// if r := app.Router("/users"), then the `r.GetRelPath()` is the "/users".
	// if r := app.Router("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/main/_examples/02-routing/custom-macro
	Macros() *macro.Macros

	// Properties returns the original Router's properties map,
	// it can be modified before server startup but not afterwards.
	Properties() context.Map

	// SetRoutesNoLog disables (true) the verbose logging for the next registered
	// routes under this Router and its children.
	//
	// It covers the controllers registered through Router too.
	//
	// Defaults to false when log level is "debug".
	SetRoutesNoLog(disable bool)

	// DI returns the Dependency Injection Container of this Router.
	// Useful to configure the dependencies and inject them on the controllers and handlers.
	DI() *dep.Container
	// RegisterDependency registers a single or multiple dependencies to the router's DI Container.
	// It's a shortcut of `router.DI().RegisterDependency`.
	RegisterDependency(deps ...any) error
	// HandlerFunc resolves a function which returns a Handler as a Handler.
	// It accepts a function with arguments that are resolved by the registered dependencies and returns a Handler.
	// It panics if the given function returns nil or a different type than Handler.
	//
	// Example:
	//
	//	app.RegisterDependency(func(otherDependnecies...) *MyService {
	//		return &MyService{...}
	//	})
	//
	//	handler := app.HandlerFunc(func(service *MyService) iris.Handler {
	//		return func(ctx iris.Context) {
	//			ctx.WriteString(service.Get())
	//		}
	//	})
	//
	//	app.Get("/", handler)
	//
	// Or as middleware:
	//
	//	app.Use("/", app.HandlerFunc(func(service *MyService) iris.Handler {
	//		return func(ctx iris.Context) {
	//			// [middleware action...] before the main handler.
	//			ctx.Next()
	//		}
	//	}))
	HandlerFunc(fn any) context.Handler
	// HandlerFuncs resolves a list of functions which return functions with dependencies as Handlers.
	// Read the `HandlerFunc` documentation for more information.
	HandlerFuncs(fns ...any) context.Handlers
	// Router creates and returns a new child Router based on a prefix path.
	// It accepts a relative path and one or more handlers or controllers and returns the child group.
	//
	// Simple group usage:
	// It accepts one or more handlers as middlewares.
	// 	usersAPI := app.Router("/users", authMiddleware, logMiddleware)
	// 	usersAPI.Handle("GET", ...)
	//
	// Router func usage:
	// It accepts a function that receives this created child Router.
	// 	app.Router("/users", func(r iris.Router) {
	//		r.Use(authMiddleware, logMiddleware)
	//		r.Get("/", getAllUsers)
	//		r.Post("/", createOrUpdateUser)
	//		r.Delete("/", deleteUser)
	// 	})
	//
	// Routing interface usage:
	// It accepts a pointer to a struct value which implements the Routing interface: Routing(r Router) method.
	// Useful when the api's dependencies amount are too much to pass on a function.
	//	app.Router("/users", &api.UserController{UserRepository: ..., ...})
	//
	// Where UserController looks like:
	//
	//	type UserController struct { Users UserRepository }
	//	func(c *UserController) Routing(r iris.Router) {
	//	 r.Get("/{id:uuid}", c.getUser)
	//	 [...]
	//	}
	//
	// Usage with (static) dependencies:
	//
	//	app.RegisterDependency(userRepo, ...)
	//	app.Router("/users", new(router.UserController))
	//
	// Controller usage:
	// A controller can be any type of the following:
	//
	//   - A struct which implements the Controller interface.
	//   - A struct which its fields are binded based on the registered dependencies.
	//   - A function which returns a struct which implements the Controller interface.
	//   - A function which accepts a Router and returns nothing.
	//   - A function which accepts a Router and returns a struct which implements the Controller interface.
	//   - A function which returns a struct which implements the Controller interface and accepts a Router.
	//   - A function which returns a struct which implements the Controller interface and accepts a Router and
	//     a pointer to a struct which its fields are binded based on the registered dependencies.
	Router(relativePath string, c ...any) Router
	// Subdomain returns a new Router which is responsible to register routes to this specific "subdomain".
	//
	// If called from a child Router 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) Router

	// UseRouter appends one or more middlewares to the Application.
	// The given "handlers" will be executed before the routing logic itself.
	// So before any route, no match routes and no method allowed requests.
	// The handlers are registered to the top-level router, even on 404s.
	// Useful when you want to log all incoming requests or change the path before mux or add a global rate limiter.
	UseRouter(handlers ...context.Handler)
	// Use registers middlewares on all routes, including 404 and 405 requests for root application
	// and just matched routes for child routers.
	Use(handlers ...context.Handler)
	// UseRelevant registers middlewares on matched routes only, on the root
	// application as well. Prefer it over Use when the middleware makes no
	// sense for a request that matched nothing, an authentication check for
	// instance: through Use, on the root application, it would answer for
	// every unknown path too.
	UseRelevant(handlers ...context.Handler)
	// UseOnce either inserts a middleware or on the basis of the middleware already existing, replace that existing middleware instead.
	// The given "handlers" will be executed on all routes, including 404 and 405 requests for root application
	// and just matched routes for child routers.
	UseOnce(handlers ...context.Handler)
	// RoutesHandlers returns the list of this Router's registered route handlers information.
	// The returned value is a cloned one, any changes made to the returned value
	// will NOT affect the next registered route handlers.
	RoutesHandlers() *context.HandlerList

	// EnableStatusCodeResponse registers a middleware that will handle the status code responses automatically.
	EnableStatusCodeResponse()
	// AllowMethods will re-register the future routes that will be registered
	// via `Handle`, `Get`, `Post`, ... to the given "methods" on that Router and its children,
	// duplicates are not registered.
	//
	// Call of `AllowMethods` will override any previous allow methods.
	AllowMethods(methods ...string)

	// Handle registers a route to this specific group of routes (Router).
	// If "method" is empty then the route is registered to all available HTTP Methods.
	// The "method" parameter can be any valid HTTP method, including the HTTP verb itself,
	// i.e. "GET", "POST", "PUT", "DELETE", "OPTIONS", "CONNECT", "HEAD", "PATCH", "TRACE".
	// The method supports multiple HTTP verbs as well, separated by a single space or single comma,
	// i.e.: "GET POST", "GET,POST" and so on.
	//
	// It returns the registered routes.
	//
	// Patterns can match the host and path of a request.
	//   - "/index.html" matches the path "/index.html" for any host and registered method(s)..
	//   - "www." matches the root path for the "www" subdomain to the current host (let's call it {app_domain}).
	//   - "site.example./index" matches the path "/index" for the host "site.example.{app_domain}".
	//   - "*./index" matches the path "/index.html" to any subdomain (* is the wildcard character).
	//   - "/lists/{listname}/objects/{objectname:path}" matches paths whose first segment is "lists"
	//     and whose third segment is "objects". The name "listname" denotes the second
	//     segment and "objectname" denotes the remainder of the (trailing) path.
	//
	// For more information about the available path parameters and their types please
	// read below.
	// Standard macro types for parameters:
	// +------------------------+
	// | {param:string}         |
	// +------------------------+
	// string type
	// anything (single path segmnent)
	//
	// +-------------------------------+
	// | {param:int}                   |
	// +-------------------------------+
	// int type
	// -9223372036854775808 to 9223372036854775807 (x64) or -2147483648 to 2147483647 (x32), depends on the host arch
	//
	// +------------------------+
	// | {param:int8}           |
	// +------------------------+
	// int8 type
	// -128 to 127
	//
	// +------------------------+
	// | {param:int16}          |
	// +------------------------+
	// int16 type
	// -32768 to 32767
	//
	// +------------------------+
	// | {param:int32}          |
	// +------------------------+
	// int32 type
	// -2147483648 to 2147483647
	//
	// +------------------------+
	// | {param:int64}          |
	// +------------------------+
	// int64 type
	// -9223372036854775808 to 9223372036854775807
	//
	// +------------------------+
	// | {param:uint}           |
	// +------------------------+
	// uint type
	// 0 to 18446744073709551615 (x64) or 0 to 4294967295 (x32)
	//
	// +------------------------+
	// | {param:uint8}          |
	// +------------------------+
	// uint8 type
	// 0 to 255
	//
	// +------------------------+
	// | {param:uint16}         |
	// +------------------------+
	// uint16 type
	// 0 to 65535
	//
	// +------------------------+
	// | {param:uint32}          |
	// +------------------------+
	// uint32 type
	// 0 to 4294967295
	//
	// +------------------------+
	// | {param:uint64}         |
	// +------------------------+
	// uint64 type
	// 0 to 18446744073709551615
	//
	// +---------------------------------+
	// | {param:bool} or {param:boolean} |
	// +---------------------------------+
	// bool type
	// only "1" or "t" or "T" or "TRUE" or "true" or "True"
	// or "0" or "f" or "F" or "FALSE" or "false" or "False"
	//
	// +------------------------+
	// | {param:alphabetical}   |
	// +------------------------+
	// alphabetical/letter type
	// letters only (upper or lowercase)
	//
	// +------------------------+
	// | {param:file}           |
	// +------------------------+
	// file type
	// letters (upper or lowercase)
	// numbers (0-9)
	// underscore (_)
	// dash (-)
	// point (.)
	// no spaces ! or other character
	//
	// +------------------------+
	// | {param:path}           |
	// +------------------------+
	// path type
	// anything, should be the last part, can be requested for more than one path segment,
	// i.e: "/test/{param:path}" and request: "/test/path1/path2/path3" , ctx.Params().GetString("param") == "path1/path2/path3"
	//
	// +------------------------+
	// | {param:uuid}           |
	// +------------------------+
	// UUIDv4 (and v1) path parameter validation.
	//
	// +------------------------+
	// | {param:mail}           |
	// +------------------------+
	// Email without domain validation.
	//
	// +------------------------+
	// | {param:email}           |
	// +------------------------+
	// Email with domain validation.
	//
	// +------------------------+
	// | {param:date}           |
	// +------------------------+
	// yyyy/mm/dd format e.g. /blog/{param:date} matches /blog/2022/04/21.
	//
	// +------------------------+
	// | {param:weekday}        |
	// +------------------------+
	// positive integer 0 to 6 or
	// string of time.Weekday longname format ("sunday" to "monday" or "Sunday" to "Monday")
	// format e.g. /schedule/{param:weekday} matches /schedule/monday.
	//
	// If type is missing then parameter's type is defaulted to string, so
	// {param} is identical to {param:string}.
	//
	// If a function not found on that type then the `string` macro type's functions are being used.
	//
	// Besides the fact that iris provides the basic types and some default "macro funcs"
	// you are able to register your own too.
	//
	// Register a named path parameter function:
	//
	//	app.Macros().Number.RegisterFunc("min", func(argument int) func(paramValue string) bool {
	//	 [...]
	//	 return true/false -> true means valid.
	//	})
	//
	// at the func(argument ...) you can have any standard type, it will be validated before the server starts
	// so don't care about performance here, the only thing it runs at serve time is the returning func(paramValue string) bool.
	//
	// {param:string equal(iris)} , "iris" will be the argument here:
	//
	//	app.Macros().String.RegisterFunc("equal", func(argument string) func(paramValue string) bool {
	//		return func(paramValue string) bool { return argument == paramValue }
	//	})
	//
	// Some examples:
	//
	//	app.Handle("GET", "/user/{id:uint64}", userByIDHandler)
	//	app.Handle("GET", "/user/{name}", userNameHandler)
	//	app.Handle("GET", "/user/{name:string min(1) else 504}", userNameHandler)
	//	app.Handle("GET", "/user/{name:string min(1) else 504}/profile", userProfileHandler)
	//	app.Handle("GET", "/user/{id:uuid}/{name}/profile", userProfileHandler)
	//	app.Handle("GET", "/api/{version}/users", apiUsersHandler)
	//	app.Handle("GET", "/api/{version}/users/{id:uint64}", apiUserByIDHandler)
	//	app.Handle("GET", "/api/{version}/users/{id:uint64}/friends", apiUserFriendsHandler)
	//	app.Handle("GET", "/api/{version}/users/{id:uint64}/friends/{friendID:uint64}", apiUserFriendByIDHandler)
	//	app.Handle("GET", "/api/{version}/users/{id:uint64}/friends/{friendID:uint64}/messages", apiUserFriendMessagesHandler)
	//	app.Handle("GET", "/api/{version}/users/{id:uint64}/friends/{friendID:uint64}/messages/{messageID:uint64}", apiUserFriendMessageByIDHandler)
	//	app.Handle("POST", "/api/{version}/users/{id:uint64}/friends/{friendID:uint64}/messages/{messageID:uint64}/reply", apiUserFriendMessageReplyHandler)
	//	app.Handle("POST", "/api/{version}/users/{id:uint64}/friends/{friendID:uint64}/messages/{messageID:uint64}/forward", apiUserFriendMessageForwardHandler)
	//	app.Handle("DELETE", "/api/{version}/users/{id:uint64}/friends/{friendID:uint64}/messages/{messageID:uint64}/delete", apiUserFriendMessageDeleteHandler)
	//	app.Handle("PUT", "/api/{version}/users/{id:uint64}/friends/{friendID:uint64}/messages/{messageID:uint64}/edit", apiUserFriendMessageEditHandler)
	//	app.Handle("POST", "/api/{version}/users/{id:uint64}/friends/{friendID:uint64}/messages/{messageID:uint64}/report", apiUserFriendMessageReportHandler)
	//	app.Handle("GET", "/api/{version}/users/{id:uint64}/friends/{friendID:uint64}/messages/{messageID:uint64}/report/{reportID:uint64}", apiUserFriendMessageReportByIDHandler)
	//
	// Please refer to the _examples directory for even more productive code samples
	// for almost every use case you can imagine. The _examples/02-routing/path-parameters/main.go is the main
	// example file you could navigate to.
	Handle(method string, registeredPath string, handlers ...context.Handler) *RouteRegistry

	// None registers an "offline" route: it is added to the registry under the
	// MethodNone method, so the serve mux never matches an incoming request to it.
	//
	// Returns the registered route or nil on failure.
	None(relativePath string, handlers ...context.Handler) *Route

	// Get registers a route for the Get HTTP Method.
	//
	// Returns the registered route or nil on failure.
	Get(relativePath string, handlers ...context.Handler) *Route
	// Post registers a route for the Post HTTP Method.
	//
	// Returns the registered route or nil on failure.
	Post(relativePath string, handlers ...context.Handler) *Route
	// Query registers a route for the QUERY HTTP Method (RFC 10008):
	// a safe, idempotent request that carries a body, e.g. a list filter.
	//
	// Returns the registered route or nil on failure.
	Query(relativePath string, handlers ...context.Handler) *Route
	// Put registers a route for the Put HTTP Method.
	//
	// Returns the registered route or nil on failure.
	Put(relativePath string, handlers ...context.Handler) *Route
	// Delete registers a route for the Delete HTTP Method.
	//
	// Returns the registered route or nil on failure.
	Delete(relativePath string, handlers ...context.Handler) *Route
	// Connect registers a route for the Connect HTTP Method.
	//
	// Returns the registered route or nil on failure.
	Connect(relativePath string, handlers ...context.Handler) *Route
	// Head registers a route for the Head HTTP Method.
	//
	// Returns the registered route or nil on failure.
	Head(relativePath string, handlers ...context.Handler) *Route
	// Options registers a route for the Options HTTP Method.
	//
	// Returns the registered route or nil on failure.
	Options(relativePath string, handlers ...context.Handler) *Route
	// Patch registers a route for the Patch HTTP Method.
	//
	// Returns the registered route or nil on failure.
	Patch(relativePath string, handlers ...context.Handler) *Route
	// Trace registers a route for the Trace HTTP Method.
	//
	// Returns the registered route or nil on failure.
	Trace(relativePath string, handlers ...context.Handler) *Route
	// Any registers a route for ALL of the HTTP methods:
	// Get
	// Post
	// Put
	// Delete
	// Head
	// Patch
	// Options
	// Connect
	// Trace
	// Query
	Any(registeredPath string, handlers ...context.Handler) *RouteRegistry
	// Resource registers a route for the Get and Head HTTP Methods.
	// It's a shortcut for router.Handle("GET HEAD", relativePath, handlers...).
	Resource(relativePath string, handlers ...context.Handler) *RouteRegistry
	// HandleServer registers a route for all HTTP methods which forwards the requests to the given server.
	//
	// Usage:
	//
	//	app.HandleServer("/api/identity/{first:string}/orgs/{second:string}/{p:path}", otherApp)
	//
	// OR
	//
	//	app.HandleServer("/api/identity", otherApp)
	HandleServer(relativePath string, server ServerHandler)

	// RemoveRoute deletes a registered route by its name before `Application.Listen`.
	// The default naming for newly created routes is: method + subdomain + path.
	// Reports whether a route with that name was found and removed successfully.
	//
	// Note that this method applies to all children Routers
	// even if each of the Router have access to this method,
	// as the route name is unique per Iris Application.
	RemoveRoute(routeName string) bool

	// 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
}

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

Look the `RouterBuilder` structure for its implementation.

type RouterBuilder

type RouterBuilder struct {

	// Set on `BuildRouter` method call.
	http.Handler // the main handler.
	ServeMux
	// contains filtered or unexported fields
}

RouterBuilder is the API builder for the Router. It's responsible to build the API and the router handler. It's the only one that should be used to create a new Router. It's been used inside the Iris `Application`.

func New

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

func (*RouterBuilder) AddRouterWrapper

func (router *RouterBuilder) 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 (*RouterBuilder) AllowMethods

func (router *RouterBuilder) AllowMethods(methods ...string)

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

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

func (*RouterBuilder) Any

func (router *RouterBuilder) Any(relativePath string, handlers ...context.Handler) *RouteRegistry

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

func (*RouterBuilder) Application

func (router *RouterBuilder) Application() context.Application

Application returns the read-only application.

func (*RouterBuilder) BuildRouter

func (router *RouterBuilder) BuildRouter(options RouterOptions, logger *golog.Logger, contextPool *context.Pool) error

BuildRouter builds the router, it's being called by the main Iris Application Builder. It's being called once after all routes have been registered and before the server starts.

func (*RouterBuilder) Connect

func (router *RouterBuilder) Connect(relativePath string, handlers ...context.Handler) *Route

Connect registers a route for the Connect HTTP Method.

Returns the registered route or nil on failure.

func (*RouterBuilder) ContextOptions

func (router *RouterBuilder) ContextOptions() *context.ContextOptions

ContextOptions returns the context options.

func (*RouterBuilder) CreateRoutes

func (router *RouterBuilder) CreateRoutes(methods []string, relativePath string, handlers ...context.Handler) *RouteRegistry

CreateRoutes returns a list of Router-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 Router-based Routes before take the decision to register them.

func (*RouterBuilder) DI

func (router *RouterBuilder) DI() *dep.Container

DI returns the Dependency Injection Container of this Router. Useful to configure the dependencies and inject them on the controllers and handlers.

func (*RouterBuilder) Delete

func (router *RouterBuilder) Delete(relativePath string, handlers ...context.Handler) *Route

Delete registers a route for the Delete HTTP Method.

Returns the registered route or nil on failure.

func (*RouterBuilder) Downgrade

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

Downgrade "downgrades", alters the router supervisor service (the RouterBuilder's embedded http.Handler, set on `BuildRouter`) algorithm to a custom one, be aware of the 'ParamStart' (":") and 'WildcardParamStart' ("*") constants which the built-in router syntax is based on. 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 NOT safe for concurrent use: it writes the router's main handler without any synchronization, so it must be called on the design state, before the server starts serving.

func (*RouterBuilder) Downgraded

func (router *RouterBuilder) Downgraded() bool

Downgraded returns true if this router is downgraded.

func (*RouterBuilder) EnableStatusCodeResponse

func (router *RouterBuilder) EnableStatusCodeResponse()

EnableStatusCodeResponse registers a middleware that will handle the status code responses automatically.

func (*RouterBuilder) Get

func (router *RouterBuilder) Get(relativePath string, handlers ...context.Handler) *Route

Get registers a route for the Get HTTP Method.

Returns the registered route or nil on failure.

func (*RouterBuilder) GetRelPath

func (router *RouterBuilder) GetRelPath() string

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

func (*RouterBuilder) GetRoot

func (router *RouterBuilder) GetRoot() *RouterBuilder

GetRoot returns the very first Router (the Application's Router Builder). It walks the parent chain to the root RouterBuilder. Safe to call on the root itself: in that case the receiver is returned. Not safe to call concurrently with router cloning.

func (*RouterBuilder) Handle

func (router *RouterBuilder) Handle(method string, pattern string, handlers ...context.Handler) *RouteRegistry

Handle registers a route to this specific group of routes (Router). If "method" is empty then the route is registered to all available HTTP Methods. The "method" parameter can be any valid HTTP method, including the HTTP verb itself, i.e. "GET", "POST", "PUT", "DELETE", "OPTIONS", "CONNECT", "HEAD", "PATCH", "TRACE". The method supports multiple HTTP verbs as well, separated by a single space or single comma, i.e.: "GET POST", "GET,POST" and so on.

It returns the registered routes.

Patterns can match the host and path of a request.

  • "/index.html" matches the path "/index.html" for any host and registered method(s)..
  • "www." matches the root path for the "www" subdomain to the current host (let's call it {app_domain}).
  • "site.example./index" matches the path "/index" for the host "site.example.{app_domain}".
  • "*./index" matches the path "/index.html" to any subdomain (* is the wildcard character).
  • "/lists/{listname}/objects/{objectname:path}" matches paths whose first segment is "lists" and whose third segment is "objects". The name "listname" denotes the second segment and "objectname" denotes the remainder of the (trailing) path.

For more information about the available path parameters and their types please read below. Standard macro types for parameters: +------------------------+ | {param:string} | +------------------------+ string type anything (single path segmnent)

+-------------------------------+ | {param:int} | +-------------------------------+ int type -9223372036854775808 to 9223372036854775807 (x64) or -2147483648 to 2147483647 (x32), depends on the host arch

+------------------------+ | {param:int8} | +------------------------+ int8 type -128 to 127

+------------------------+ | {param:int16} | +------------------------+ int16 type -32768 to 32767

+------------------------+ | {param:int32} | +------------------------+ int32 type -2147483648 to 2147483647

+------------------------+ | {param:int64} | +------------------------+ int64 type -9223372036854775808 to 9223372036854775807

+------------------------+ | {param:uint} | +------------------------+ uint type 0 to 18446744073709551615 (x64) or 0 to 4294967295 (x32)

+------------------------+ | {param:uint8} | +------------------------+ uint8 type 0 to 255

+------------------------+ | {param:uint16} | +------------------------+ uint16 type 0 to 65535

+------------------------+ | {param:uint32} | +------------------------+ uint32 type 0 to 4294967295

+------------------------+ | {param:uint64} | +------------------------+ uint64 type 0 to 18446744073709551615

+---------------------------------+ | {param:bool} or {param:boolean} | +---------------------------------+ bool type only "1" or "t" or "T" or "TRUE" or "true" or "True" or "0" or "f" or "F" or "FALSE" or "false" or "False"

+------------------------+ | {param:alphabetical} | +------------------------+ alphabetical/letter type letters only (upper or lowercase)

+------------------------+ | {param:file} | +------------------------+ file type letters (upper or lowercase) numbers (0-9) underscore (_) dash (-) point (.) no spaces ! or other character

+------------------------+ | {param:path} | +------------------------+ path type anything, should be the last part, can be requested for more than one path segment, i.e: "/test/{param:path}" and request: "/test/path1/path2/path3" , ctx.Params().GetString("param") == "path1/path2/path3"

+------------------------+ | {param:uuid} | +------------------------+ UUIDv4 (and v1) path parameter validation.

+------------------------+ | {param:mail} | +------------------------+ Email without domain validation.

+------------------------+ | {param:email} | +------------------------+ Email with domain validation.

+------------------------+ | {param:date} | +------------------------+ yyyy/mm/dd format e.g. /blog/{param:date} matches /blog/2022/04/21.

+------------------------+ | {param:weekday} | +------------------------+ positive integer 0 to 6 or string of time.Weekday longname format ("sunday" to "monday" or "Sunday" to "Monday") format e.g. /schedule/{param:weekday} matches /schedule/monday.

If type is missing then parameter's type is defaulted to string, so {param} is identical to {param:string}.

If a function not found on that type then the `string` macro type's functions are being used.

Besides the fact that iris provides the basic types and some default "macro funcs" you are able to register your own too.

Register a named path parameter function:

app.Macros().Number.RegisterFunc("min", func(argument int) func(paramValue string) bool {
 [...]
 return true/false -> true means valid.
})

at the func(argument ...) you can have any standard type, it will be validated before the server starts so don't care about performance here, the only thing it runs at serve time is the returning func(paramValue string) bool.

{param:string equal(iris)} , "iris" will be the argument here:

app.Macros().String.RegisterFunc("equal", func(argument string) func(paramValue string) bool {
	return func(paramValue string) bool { return argument == paramValue }
})

Some examples:

app.Handle("GET", "/user/{id:uint64}", userByIDHandler)
app.Handle("GET", "/user/{name}", userNameHandler)
app.Handle("GET", "/user/{name:string min(1) else 504}", userNameHandler)
app.Handle("GET", "/user/{name:string min(1) else 504}/profile", userProfileHandler)
app.Handle("GET", "/user/{id:uuid}/{name}/profile", userProfileHandler)
app.Handle("GET", "/api/{version}/users", apiUsersHandler)
app.Handle("GET", "/api/{version}/users/{id:uint64}", apiUserByIDHandler)
app.Handle("GET", "/api/{version}/users/{id:uint64}/friends", apiUserFriendsHandler)
app.Handle("GET", "/api/{version}/users/{id:uint64}/friends/{friendID:uint64}", apiUserFriendByIDHandler)
app.Handle("GET", "/api/{version}/users/{id:uint64}/friends/{friendID:uint64}/messages", apiUserFriendMessagesHandler)
app.Handle("GET", "/api/{version}/users/{id:uint64}/friends/{friendID:uint64}/messages/{messageID:uint64}", apiUserFriendMessageByIDHandler)
app.Handle("POST", "/api/{version}/users/{id:uint64}/friends/{friendID:uint64}/messages/{messageID:uint64}/reply", apiUserFriendMessageReplyHandler)
app.Handle("POST", "/api/{version}/users/{id:uint64}/friends/{friendID:uint64}/messages/{messageID:uint64}/forward", apiUserFriendMessageForwardHandler)
app.Handle("DELETE", "/api/{version}/users/{id:uint64}/friends/{friendID:uint64}/messages/{messageID:uint64}/delete", apiUserFriendMessageDeleteHandler)
app.Handle("PUT", "/api/{version}/users/{id:uint64}/friends/{friendID:uint64}/messages/{messageID:uint64}/edit", apiUserFriendMessageEditHandler)
app.Handle("POST", "/api/{version}/users/{id:uint64}/friends/{friendID:uint64}/messages/{messageID:uint64}/report", apiUserFriendMessageReportHandler)
app.Handle("GET", "/api/{version}/users/{id:uint64}/friends/{friendID:uint64}/messages/{messageID:uint64}/report/{reportID:uint64}", apiUserFriendMessageReportByIDHandler)

Please refer to the _examples directory for even more productive code samples for almost every use case you can imagine. The _examples/02-routing/path-parameters/main.go is the main example file you could navigate to.

func (*RouterBuilder) HandleNoMethod

func (router *RouterBuilder) HandleNoMethod(handlers ...context.Handler)

HandleNoMethod registers one or more handlers for the case when the request's method is not allowed. The 405 status code and the Allow header are set by the serve mux before these handlers run; the default handler writes the stored public error, if any, otherwise the status text ("Method Not Allowed").

func (*RouterBuilder) HandleNoRoute

func (router *RouterBuilder) HandleNoRoute(handlers ...context.Handler)

HandleNoRoute registers one or more handlers for the case when no route is found. The 404 status code is set by the serve mux before these handlers run; the default handler writes the stored public error, if any, otherwise the status text ("Not Found").

func (*RouterBuilder) HandleServer

func (router *RouterBuilder) HandleServer(relativePath string, server ServerHandler)

HandleServer registers a route for all HTTP methods which forwards the requests to the given server.

Usage:

app.HandleServer("/api/identity/{first:string}/orgs/{second:string}/{p:path}", otherApp)

OR

app.HandleServer("/api/identity", otherApp)

func (*RouterBuilder) HandlerFunc

func (router *RouterBuilder) HandlerFunc(fn any) context.Handler

HandlerFunc resolves a function which returns a Handler as a Handler. It accepts a function with arguments that are resolved by the registered dependencies and returns a Handler (and an optional error). If the returned error is not nil then it panics with that specific error. It panics if the given function returns nil or a different type than Handler.

Example:

app.RegisterDependency(func(otherDependnecies...) *MyService {
	return &MyService{...}
})

handler := app.HandlerFunc(func(service *MyService) iris.Handler {
	return func(ctx iris.Context) {
		ctx.WriteString(service.Get())
	}
})

app.Get("/", handler)

Or as middleware:

app.Use("/", app.HandlerFunc(func(service *MyService) iris.Handler {
	return func(ctx iris.Context) {
		// [middleware action...] before the main handler.
		ctx.Next()
	}
}))

func (*RouterBuilder) HandlerFuncs

func (router *RouterBuilder) HandlerFuncs(fns ...any) context.Handlers

HandlerFuncs resolves a list of functions which return functions with dependencies as Handlers. Read the `HandlerFunc` documentation for more information.

func (*RouterBuilder) Handlers

func (router *RouterBuilder) Handlers() *context.HandlerList

Handlers returns the list of this Router's registered middleware handlers information. The returned value is the original one, any changes made to the returned value will affect the next registered route handlers.

func (*RouterBuilder) Head

func (router *RouterBuilder) Head(relativePath string, handlers ...context.Handler) *Route

Head registers a route for the Head HTTP Method.

Returns the registered route or nil on failure.

func (*RouterBuilder) IsRoot

func (router *RouterBuilder) IsRoot() bool

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

func (*RouterBuilder) ListRoutesReadOnly

func (router *RouterBuilder) ListRoutesReadOnly() []context.RouteReadOnly

ListRoutesReadOnly returns a read-only version of the registered routes.

func (*RouterBuilder) Macros

func (router *RouterBuilder) 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/main/_examples/02-routing/custom-macro

func (*RouterBuilder) NoMethodHandlers

func (router *RouterBuilder) NoMethodHandlers() *context.HandlerList

NoMethodHandlers returns the list the registered no method handlers information. The returned value is the original one, any changes made to the returned value will affect all the registered no method handlers.

func (*RouterBuilder) NoRouteHandlers

func (router *RouterBuilder) NoRouteHandlers() *context.HandlerList

NoRouteHandlers returns the list the registered no route handlers information. The returned value is the original one, any changes made to the returned value will affect all the registered no route handlers.

func (*RouterBuilder) None

func (router *RouterBuilder) None(relativePath string, handlers ...context.Handler) *Route

None registers an "offline" route, under the virtual `MethodNone` ("NONE") method. The route is stored in the registry and is listed like any other one, but the serve mux never matches an incoming request against it, as no request carries a "NONE" method. Its handlers only run when something executes them explicitly.

Returns the registered route or nil on failure.

func (*RouterBuilder) Options

func (router *RouterBuilder) Options(relativePath string, handlers ...context.Handler) *Route

Options registers a route for the Options HTTP Method.

Returns the registered route or nil on failure.

func (*RouterBuilder) Patch

func (router *RouterBuilder) Patch(relativePath string, handlers ...context.Handler) *Route

Patch registers a route for the Patch HTTP Method.

Returns the registered route or nil on failure.

func (*RouterBuilder) Post

func (router *RouterBuilder) Post(relativePath string, handlers ...context.Handler) *Route

Post registers a route for the Post HTTP Method.

Returns the registered route or nil on failure.

func (*RouterBuilder) PrependRouterWrapper

func (router *RouterBuilder) 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 (*RouterBuilder) Properties

func (router *RouterBuilder) Properties() context.Map

Properties returns the original Router's properties map, it can be modified before server startup but not afterwards.

func (*RouterBuilder) Put

func (router *RouterBuilder) Put(relativePath string, handlers ...context.Handler) *Route

Put registers a route for the Put HTTP Method.

Returns the registered route or nil on failure.

func (*RouterBuilder) Query

func (router *RouterBuilder) Query(relativePath string, handlers ...context.Handler) *Route

Query registers a route for the QUERY HTTP Method (RFC 10008): a safe, idempotent request that carries a body, e.g. a list filter.

Returns the registered route or nil on failure.

func (*RouterBuilder) RegisterDependency

func (router *RouterBuilder) RegisterDependency(deps ...any) error

RegisterDependency registers a single or multiple dependencies to the router's DI Container. It's a shortcut of `router.DI().RegisterDependency`. It's useful when you want to register static dependencies upfront before the controllers' registration.

func (*RouterBuilder) RemoveRoute

func (router *RouterBuilder) RemoveRoute(routeName string) bool

RemoveRoute deletes a registered route by its name before `Application.Listen`. The default naming for newly created routes is: method + subdomain + path. Reports whether a route with that name was found and removed successfully.

Note that this method applies to all Parties (sub routers) even if each of the Parties have access to this method, as the route name is unique per Iris Application.

func (*RouterBuilder) Reset

func (router *RouterBuilder) Reset()

Reset removes all the middleware and error code handlers.

func (*RouterBuilder) Resource

func (router *RouterBuilder) Resource(relativePath string, handlers ...context.Handler) *RouteRegistry

Resource registers a route for the Get and Head HTTP Methods. It's a shortcut for router.Handle("GET HEAD", relativePath, handlers...).

func (*RouterBuilder) Router

func (router *RouterBuilder) Router(relativePath string, controllers ...any) Router

Router creates and returns a new child Router based on a prefix path. It accepts a relative path and one or more handlers or controllers and returns the child group.

Simple group usage: It accepts one or more handlers as middlewares. If the function is a handler, then it's registered as a middleware to the child router only for matched routes.

usersAPI := app.Router("/users", authMiddleware, logMiddleware)
usersAPI.Handle("GET", ...)

Router func usage: It accepts a function that receives this created child Router.

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

Routing interface usage: It accepts a pointer to a struct value which implements the Routing interface: Routing(r Router) method. Useful when the api's dependencies amount are too much to pass on a function.

app.Router("/users", &api.UserController{UserRepository: ..., ...})

Where UserController looks like:

type UserController struct { Users UserRepository }
func(c *UserController) Routing(r iris.Router) {
 r.Get("/{id:uuid}", c.getUser)
 [...]
}

Usage with (static) dependencies:

app.RegisterDependency(userRepo, ...)
app.Router("/users", new(router.UserController))

Controller usage: A controller can be any type of the following:

  • A struct which implements the Controller interface.
  • A ptr to struct which implements the Controller interface and its exported fields are binded based on the registered dependencies.
  • A function which returns a struct which implements the Controller interface.
  • A function which accepts a Router and returns nothing.
  • A function which accepts a Router and returns a struct which implements the Controller interface.
  • A function which returns a struct which implements the Controller interface and accepts a Router.
  • A function which returns a struct which implements the Controller interface and accepts a Router and a pointer to a struct which its fields are binded based on the registered dependencies.

func (*RouterBuilder) RouterHandlers

func (router *RouterBuilder) RouterHandlers() *context.HandlerList

RouterHandlers returns the list of all registered router middleware handlers information. The returned value is the original one, any changes made to the returned value will affect the Router's handlers.

func (*RouterBuilder) Routes

func (router *RouterBuilder) Routes() *RouteRegistry

Routes returns the route repository. It's been used by the `ServeMux` and `Application` to register the routes on Handle, Get, Post and so on.

func (*RouterBuilder) RoutesHandlers

func (router *RouterBuilder) RoutesHandlers() *context.HandlerList

RoutesHandlers returns the list of this Router's registered route handlers information. The returned value is a cloned one, any changes made to the returned value will NOT affect the next registered route handlers.

func (*RouterBuilder) SetRoutesNoLog

func (router *RouterBuilder) SetRoutesNoLog(disable bool)

SetRoutesNoLog disables (true) the verbose logging for the next registered routes under this Router and its children.

It covers the controllers registered through Router too.

Defaults to false when log level is "debug".

func (*RouterBuilder) StaticContent

func (router *RouterBuilder) 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 (*RouterBuilder) Subdomain

func (router *RouterBuilder) Subdomain(subdomain string, middleware ...context.Handler) Router

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

If called from a child Router 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 (*RouterBuilder) Trace

func (router *RouterBuilder) Trace(relativePath string, handlers ...context.Handler) *Route

Trace registers a route for the Trace HTTP Method.

Returns the registered route or nil on failure.

func (*RouterBuilder) Use

func (router *RouterBuilder) Use(handlers ...context.Handler)

Use registers middlewares on all routes, including 404 and 405 requests for the root application and just matched routes for child routers (subdomains and group routers).

func (*RouterBuilder) UseOnce

func (router *RouterBuilder) UseOnce(handlers ...context.Handler)

UseOnce either inserts a middleware or on the basis of the middleware already existing, replace that existing middleware instead. The given "handlers" will be executed on all routes, including 404 and 405 requests.

func (*RouterBuilder) UseRelevant

func (router *RouterBuilder) UseRelevant(handlers ...context.Handler)

UseRelevant registers middlewares on matched routes only.

func (*RouterBuilder) UseRelevantOnce

func (router *RouterBuilder) UseRelevantOnce(handlers ...context.Handler)

UseRelevantOnce either inserts a middleware or on the basis of the middleware already existing, replace that existing middleware instead. The given "handlers" will be executed on matched routes only.

func (*RouterBuilder) UseRouter

func (router *RouterBuilder) UseRouter(handlers ...context.Handler)

UseRouter appends one or more middlewares to the Application. The given "handlers" will be executed before the routing logic itself. So before any route, no match routes and no method allowed requests. The handlers are registered to the top-level router, even on 404s. Useful when you want to log all incoming requests or change the path before mux or add a global rate limiter.

func (*RouterBuilder) WildcardSubdomain

func (router *RouterBuilder) WildcardSubdomain(middleware ...context.Handler) Router

WildcardSubdomain returns a new Router 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 Router.

func (*RouterBuilder) WrapRouter

func (router *RouterBuilder) 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 RouterOptions

type RouterOptions struct {
	// Host is the server's host, including the port (not required if 80 or 443).
	// If empty then this field is set to Server's options Host by default.
	Host string `ini:"host" json:"host,omitempty" yaml:"Host" toml:"Host"`
	// DisablePathCorrection disables the correcting
	// and redirecting or executing directly the handler of
	// the requested path to the registered path
	// for example, if /home/ path is requested but no handler for this Route found,
	// then the Router checks if /home handler exists, if yes,
	// (permanent)redirects the client to the correct path /home.
	//
	// See `DisablePathCorrectionRedirection` to enable direct handler execution instead of redirection.
	//
	// Defaults to false.
	DisablePathCorrection bool `` /* 127-byte string literal not displayed */
	// DisablePathCorrectionRedirection works whenever configuration.DisablePathCorrection is set to false
	// and if DisablePathCorrectionRedirection set to true then it will fire the handler of the matching route without
	// the trailing slash ("/") instead of send a redirection status.
	//
	// Defaults to false.
	DisablePathCorrectionRedirection bool `` /* 173-byte string literal not displayed */
	// EnablePathIntelligence if set to true,
	// the router will redirect HTTP "GET" not found pages to the most closest one path(if any). For example
	// you register a route at "/contact" path -
	// a client tries to reach it by "/cont", the path will be automatic fixed
	// and the client will be redirected to the "/contact" path
	// instead of getting a 404 not found response back.
	//
	// Defaults to false.
	EnablePathIntelligence bool `` /* 131-byte string literal not displayed */
	// EnablePathEscape enables path and parameter escaping. Disable it if parameters with slashes are expected.
	// Example: A request to http://localhost:8080/details/Project%2FDelta will retain the encoded slash.
	// Defaults to false.
	EnablePathEscape bool `ini:"enable_path_escape" json:"enable_path_escape,omitzero" yaml:"EnablePathEscape" toml:"EnablePathEscape"`
	// ForceLowercaseRouting if enabled, converts all registered routes paths to lowercase
	// and it does lowercase the request path too for matching.
	//
	// Defaults to false.
	ForceLowercaseRouting bool `` /* 127-byte string literal not displayed */
	// AllowQuerySemicolons if true adds a router wrapper that serves requests by converting any
	// unescaped semicolons(;) in the URL query to ampersands(&).
	//
	// This restores the pre-Go 1.17 behavior of splitting query parameters on both semicolons and ampersands.
	// See golang.org/issue/25192 and https://github.com/kataras/iris/issues/1875.
	// Note that this behavior doesn't match that of many proxies,
	// and the mismatch can lead to security issues.
	AllowQuerySemicolons bool `` /* 143-byte string literal not displayed */

	// EnableDynamicHandler enables the dynamic request handler.
	// It gives the router the feature to add routes while in serve-time,
	// when `BuildRouter` is called again.
	// If this setting is set to true, the request handler will use a mutex for data(trie routing) protection,
	// hence the performance cost.
	//
	// Defaults to false.
	EnableDynamicHandler bool `ini:"enable_dynamic_handler" json:"enable_dynamic_handler,omitzero" yaml:"EnableDynamicHandler" toml:"EnableDynamicHandler"`
	// FireMethodNotAllowed if it's true router checks for StatusMethodNotAllowed(405) and
	//  fires the 405 error instead of 404
	// Defaults to false.
	FireMethodNotAllowed bool `ini:"fire_method_not_allowed" json:"fire_method_not_allowed,omitzero" yaml:"FireMethodNotAllowed" toml:"FireMethodNotAllowed"`
}

RouterOptions is the configuration for the Router.

The json keys are snake_case, matching the ini ones and context.ContextOptions; the yaml and toml keys are the Go field names.

Note: root-domain to "www" redirection is not a field here; the "rewrite" middleware's PrimarySubdomain option does that and more.

type Routing

type Routing func(Router)

Routing is a type which can be used to convert a function to a Controller.

func (Routing) Routing

func (f Routing) Routing(r Router)

Routing implements the Controller interface.

type ServeMux

type ServeMux interface {
	// RouteExists(ctx *context.Context, method, path string) (exists bool)
	FindClosestPaths(subdomain, searchPath string, n int) []string

	HandleRequest(ctx *context.Context)

	Build(noRoute, noMethod *Route, routes *RouteRegistry) error
}

ServeMux is the interface that wraps the FindClosestPaths, HandleRequest and Build methods. It's used to build the router and serve the incoming requests.

See `BuildServeMux` package-level function to construct the default ServeMux.

func BuildServeMux

func BuildServeMux(
	options *RouterOptions,
	logger *golog.Logger,
	preRoute, noRoute, noMethod *Route,
	routes *RouteRegistry,

) (ServeMux, error)

BuildServeMux returns a new ServeMux built from the given router options, logger, the pre-routing, no-route and no-method routes and the route registry. It's used to construct the default ServeMux. Used internally by the `core/router` package.

type ServerHandler

type ServerHandler interface {
	HandleRequest(*context.Context)
}

ServerHandler is the interface which all server handlers should implement. The Iris Application implements it. See `Router.HandleServer` method for more.

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.

Directories

Path Synopsis
internal
handler
Package handler is the highest level module of the macro package which makes use the rest of the macro package, it is mainly used, internally, by the router package.
Package handler is the highest level module of the macro package which makes use the rest of the macro package, it is mainly used, internally, by the router package.

Jump to

Keyboard shortcuts

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