package module
v0.12.1 Latest Latest

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

Go to latest
Published: Jul 28, 2018 License: MIT Imports: 20 Imported by: 9


Router by aah framework

Build Status Code Coverage Go Report Card Release Version Godoc

HTTP Router brings domain and sub-domains routing, it internally uses customized version of radix tree implementation from developer by @julienschmidt.


  • v0.12.1 released and tagged on Jul 27, 2018.


go get -u

Visit official website to learn more about aah framework.



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

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



View Source
const (
	// SlashString const for comparison use
	SlashString = "/"
View Source
const Version = "0.12.1"

Version no. of aah framework router library


View Source
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

View Source
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")


func CleanPath

func CleanPath(p string) string

CleanPath is the URL version of path.Clean, it returns a canonical URL path for p, eliminating . and .. elements.

The following rules are applied iteratively until no further processing can be done:

  1. Replace multiple slashes with a single slash.
  2. Eliminate each . path name element (the current directory).
  3. Eliminate each inner .. path name element (the parent directory) along with the non-.. element that precedes it.
  4. Eliminate .. elements that begin a rooted path: that is, replace "/.." by "/" at the beginning of a path.

If the result of this process is an empty string, "/" is returned

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.


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: Friendly Read:

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
	// 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.PathParams, 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) DomainAddresses

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

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

func (*Router) FindDomain

func (r *Router) FindDomain(req *ahttp.Request) *Domain

FindDomain returns domain routes configuration based on http request otherwise nil.

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.:,, * Root Domain is ``.

Jump to

Keyboard shortcuts

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