Documentation

Overview

Package router provides routing implementation for aah framework. Routes config file format is similar to HOCON syntax aka typesafe config it gets parsed by `aahframework.org/config`.

aah router internally uses customized version of radix tree implementation from `github.com/julienschmidt/httprouter` developer by `@julienschmidt`.

Index

Constants

const (
	// SlashString const for comparison use
	SlashString = "/"
)

Variables

var (
	ErrCORSOriginIsInvalid       = errors.New("cors: invalid origin")
	ErrCORSMethodNotAllowed      = errors.New("cors: method not allowed")
	ErrCORSHeaderNotAllowed      = errors.New("cors: header not allowed")
	ErrCORSContentTypeNotAllowed = errors.New("cors: content-type not allowed")
)

CORS errors


var (
	// HTTPMethodActionMap is default Controller Action name for corresponding
	// HTTP Method. If it's not provided in the route configuration.
	HTTPMethodActionMap = map[string]string{
		ahttp.MethodGet:     "Index",
		ahttp.MethodPost:    "Create",
		ahttp.MethodPut:     "Update",
		ahttp.MethodPatch:   "Update",
		ahttp.MethodDelete:  "Delete",
		ahttp.MethodOptions: "Options",
		ahttp.MethodHead:    "Head",
		ahttp.MethodTrace:   "Trace",
	}

	// ErrNoDomainRoutesConfigFound returned when routes config file not found or doesn't
	// have `domains { ... }` config information.
	ErrNoDomainRoutesConfigFound = errors.New("router: no domain routes config found")

	// ErrRouteConstraintFailed returned when request route constraints failed.
	ErrRouteConstraintFailed = errors.New("router: route constraints failed")
)

Functions

func IsDefaultAction

func IsDefaultAction(action string) bool

IsDefaultAction method is to identify given action name is defined by aah framework in absence of user configured route action name.

Types

type CORS

type CORS struct {
	AllowCredentials bool

	MaxAge string

	AllowOrigins  []string
	AllowMethods  []string
	AllowHeaders  []string
	ExposeHeaders []string
	// contains filtered or unexported fields
}

CORS struct holds Cross-Origin Resource Sharing (CORS) configuration values and verification methods for the route.

Spec: https://www.w3.org/TR/cors/ Friendly Read: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

func (*CORS) AddAllowHeaders

func (c *CORS) AddAllowHeaders(hdrs []string) *CORS

AddAllowHeaders method adds the given HTTP header into allow headers list.

func (*CORS) AddAllowMethods

func (c *CORS) AddAllowMethods(methods []string) *CORS

AddAllowMethods method adds the given HTTP verb into allow methods list.

func (*CORS) AddExposeHeaders

func (c *CORS) AddExposeHeaders(hdrs []string) *CORS

AddExposeHeaders method adds the given HTTP header into expose headers list.

func (*CORS) AddOrigins

func (c *CORS) AddOrigins(origins []string) *CORS

AddOrigins method adds the given origin into allow origin list.

func (*CORS) IsHeadersAllowed

func (c *CORS) IsHeadersAllowed(hdrs string) bool

IsHeadersAllowed method returns true if preflight headers are allowed otherwise false.

func (*CORS) IsMethodAllowed

func (c *CORS) IsMethodAllowed(method string) bool

IsMethodAllowed method returns true if preflight method is allowed otherwise false.

func (*CORS) IsOriginAllowed

func (c *CORS) IsOriginAllowed(origin string) bool

IsOriginAllowed method check given origin is allowed or not.

func (*CORS) SetAllowCredentials

func (c *CORS) SetAllowCredentials(b bool) *CORS

SetAllowCredentials method sets the given boolean into allow credentials.

func (*CORS) SetMaxAge

func (c *CORS) SetMaxAge(age string) *CORS

SetMaxAge method parses the given duration string into seconds and adds to CORS. `time.ParseDuration` method time units are supported.

func (CORS) String

func (c CORS) String() string

String method returns string representation of CORS configuration values.

type Domain

type Domain struct {
	IsSubDomain           bool
	MethodNotAllowed      bool
	RedirectTrailingSlash bool
	AutoOptions           bool
	AntiCSRFEnabled       bool
	CORSEnabled           bool
	Key                   string
	Name                  string
	Host                  string
	Port                  string
	DefaultAuth           string
	CORS                  *CORS
	CatchAllRoute         *Route
	// contains filtered or unexported fields
}

Domain is used to hold domain related routes and it's route configuration

func (*Domain) AddRoute

func (d *Domain) AddRoute(route *Route) error

AddRoute method adds the given route into domain routing tree.

func (*Domain) Allowed

func (d *Domain) Allowed(requestMethod, path string) (allowed string)

Allowed method returns the value for header `Allow` otherwise empty string.

func (*Domain) Lookup

func (d *Domain) Lookup(req *http.Request) (*Route, ahttp.URLParams, bool)

Lookup method looks up route if found it returns route, path parameters, redirect trailing slash indicator for given `ahttp.Request` by domain and request URI otherwise returns nil and false.

func (*Domain) LookupByName

func (d *Domain) LookupByName(name string) *Route

LookupByName method returns the route for given route name otherwise nil.

func (*Domain) RouteURL

func (d *Domain) RouteURL(routeName string, args ...interface{}) string

RouteURL method composes route reverse URL for given route and arguments based on index order. If error occurs then method logs it and returns empty string.

func (*Domain) RouteURLNamedArgs

func (d *Domain) RouteURLNamedArgs(routeName string, args map[string]interface{}) string

RouteURLNamedArgs composes reverse URL by route name and key-value pair arguments. Additional key-value pairs composed as URL query string. If error occurs then method logs it and returns empty string.

type Route

type Route struct {
	IsAntiCSRFCheck bool
	IsStatic        bool
	ListDir         bool
	MaxBodySize     int64
	Name            string
	Path            string
	Method          string
	Target          string
	Action          string
	ParentName      string
	Auth            string
	Dir             string
	File            string
	CORS            *CORS
	Constraints     map[string]string
	// contains filtered or unexported fields
}

Route holds the single route details.

func (*Route) HasAccess

func (r *Route) HasAccess(subject *security.Subject) (bool, []*authz.Reason)

HasAccess method does authorization check based on configured values at route level. TODO: the appropriate place for this method would be `security` package.

func (*Route) IsDir

func (r *Route) IsDir() bool

IsDir method returns true if serving directory otherwise false.

func (*Route) IsFile

func (r *Route) IsFile() bool

IsFile method returns true if serving single file otherwise false.

func (*Route) String

func (r *Route) String() string

String method is Stringer interface.

type Router

type Router struct {
	Domains []*Domain
	// contains filtered or unexported fields
}

Router is used to register all application routes and finds the appropriate route information for incoming request path.

func New

func New(configPath string, appCfg *config.Config) *Router

New method returns the Router instance.

func NewWithApp

func NewWithApp(app interface{}, configPath string) (*Router, error)

NewWithApp method creates router instance with aah application instance.

func (*Router) CreateRouteURL

func (r *Router) CreateRouteURL(host, routeName string, margs map[string]interface{}, args ...interface{}) string

CreateRouteURL ...

func (*Router) DomainAddresses

func (r *Router) DomainAddresses() []string

DomainAddresses method returns domain addresses (host:port) from routes configuration.

func (*Router) Load

func (r *Router) Load() (err error)

Load method loads a configuration from given file e.g. `routes.conf` and applies env profile override values if available.

func (*Router) Lookup

func (r *Router) Lookup(host string) *Domain

Lookup method returns domain for given host otherwise nil.

func (*Router) RegisteredActions

func (r *Router) RegisteredActions() map[string]map[string]uint8

RegisteredActions method returns all the controller name and it's actions configured in the "routes.conf".

func (*Router) RegisteredWSActions

func (r *Router) RegisteredWSActions() map[string]map[string]uint8

RegisteredWSActions method returns all the WebSocket name and it's actions configured in the "routes.conf".

func (*Router) RootDomain

func (r *Router) RootDomain() *Domain

RootDomain method returns the root domain registered in the routes.conf. For e.g.: sample.com, admin.sample.com, *.sample.com. Root Domain is `sample.com`.