goro

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Jul 16, 2016 License: BSD-3-Clause Imports: 11 Imported by: 0

README

Goro is a mighty fine routing toolkit for Go web applications. It is designed to be fast, yet flexible.

Build Status

Features

Goro is LOADED with features, but no bloat.

  • Built in Context support while maintaining standard Go http.Handler interfaces
  • Flexible routing options with wildcards and variables
  • Prioritized route definitions with caching
  • Handler Filters that allow for pre-execution Request or Context modification
  • Static asset mapping
  • Support for subdomains
  • Handler chaining built-in

Installing

Goro requires Go 1.7+. Goro requires the new Context functionality of the Go 1.7 standard library. Its an inconvenience but its a great base for the future.

To install, run:

go get -u github.com/goposse/goro

You can then import goro using:

import github.com/goposse/goro

Getting started

The basic code breakdown looks something like this:

router := goro.NewRouter()
router.Add("GET", "/").HandleFunc(rootHandler)
http.ListenAndServe(":8080", router)

Pretty standard for most routers in Go. But Goro has so much more going for it. Rather than try to describe it all here, you should check out The Goro Guide.

FAQ

Why should I use this and not ____?

I'm not going to make any claims that Goro is the fastest router on the market or that it'll make you a million bucks. The likelihood is that even if those were true for you, they might not be for others.

What we will say is that here at Posse we have tried A LOT of web frameworks over many languages and that we invested in making Goro out of unhappiness with what we saw generally. If you're here, then maybe you have also.

Goro was designed from the ground up as a Router that we wanted to use and not to copy anyone else. It has the features we think are important, and is architected in a way that we think makes managing all this stuff super simple.

Give it a try and if you like it, let us know! Either way, we love feedback.

Has it been tested in production? Can I use it in production?

The code here has been written based on Posse's experiences with clients of all sizes. It has been production tested. That said, code is always evolving. We plan to keep on using it in production but we also plan to keep on improving it. If you find a bug, let us know!

Who the f*ck is Posse?

We're the best friggin mobile shop in NYC that's who. Hey, but we're biased. Our stuff is at http://goposse.com. Go check it out.

Outro

Credits

Goro is sponsored, owned and maintained by Posse Productions LLC. Follow us on Twitter @goposse. Feel free to reach out with suggestions, ideas or to say hey.

Security

If you believe you have identified a serious security vulnerability or issue with Goro, please report it as soon as possible to apps@goposse.com. Please refrain from posting it to the public issue tracker so that we have a chance to address it and notify everyone accordingly.

License

Goro is released under a modified MIT license. See LICENSE for details.

Documentation

Index

Constants

View Source
const (
	// HTTPMethodGET - GET http method
	HTTPMethodGET string = "GET"
	// HTTPMethodPOST - POST http method
	HTTPMethodPOST string = "POST"
	// HTTPMethodPUT - PUT http method
	HTTPMethodPUT string = "PUT"
	// HTTPMethodDELETE - DELETE http method
	HTTPMethodDELETE string = "DELETE"
)
View Source
const (
	// RouteInfoKeyIsRoot - does the route have wildcard parts
	RouteInfoKeyIsRoot string = "is_root"

	// RouteInfoKeyDescription - does the route have a catch all part
	RouteInfoKeyDescription string = "description"
)
View Source
const RootPath = "/"

RootPath - string representation of the root path

Variables

This section is empty.

Functions

func Log

func Log(v ...interface{})

Log - logging wrapper for standard output to log

Types

type CacheEntry

type CacheEntry struct {
	Params map[string]interface{}
	Route  *Route
	// contains filtered or unexported fields
}

CacheEntry - an entry in the route cache

func NotFoundCacheEntry

func NotFoundCacheEntry() CacheEntry

NotFoundCacheEntry - represents the inability to find an entry in the cache

type Chain

type Chain struct {
	// Handlers - the handlers in the Chain
	Handlers []http.Handler
}

Chain allows for chaining of Handlers

func NewChain

func NewChain() Chain

NewChain creates a new Chain instance

func (*Chain) Add

func (ch *Chain) Add(v ...http.Handler) *Chain

Add adds one or more Handlers to the end of the chain

func (*Chain) AddFunc

func (ch *Chain) AddFunc(v ...http.HandlerFunc) *Chain

AddFunc adds one or more HandlerFuncs to the end of the chain

func (*Chain) ServeHTTP

func (ch *Chain) ServeHTTP(w http.ResponseWriter, req *http.Request)

func (*Chain) Then

func (ch *Chain) Then(handler http.Handler) *Chain

Then calls the chain and then the designated Handler

func (*Chain) ThenFunc

func (ch *Chain) ThenFunc(handlerFunc http.HandlerFunc) *Chain

ThenFunc calls the chain and then the designated HandlerFunc

type DebugLevel

type DebugLevel int

DebugLevel - debug information output level

const (
	// DebugLevelNone - debugging is off
	DebugLevelNone DebugLevel = 1 << iota
	// DebugLevelTimings - show timings only
	DebugLevelTimings
	// DebugLevelFull - show all debugging information
	DebugLevelFull
)

type DomainMap

type DomainMap struct {

	// NotFoundHandler - if the (sub)domain is not mapped, call this handler
	NotFoundHandler http.Handler
	// contains filtered or unexported fields
}

DomainMap - maps (sub)domains to routers

func NewDomainMap

func NewDomainMap() *DomainMap

NewDomainMap - creates a new domain map

func (*DomainMap) AddRouter

func (domainMap *DomainMap) AddRouter(subdomain string, router *Router)

AddRouter - Register a router for a domain pattern (regex)

func (*DomainMap) InvalidateMatchedHosts

func (domainMap *DomainMap) InvalidateMatchedHosts()

InvalidateMatchedHosts - resets any matched (sub)domains that have been cached

func (*DomainMap) NewRouter

func (domainMap *DomainMap) NewRouter(subdomain string) *Router

NewRouter - Creates a new Router, registers it in the domain map and returns it for use

func (*DomainMap) ServeHTTP

func (domainMap *DomainMap) ServeHTTP(w http.ResponseWriter, req *http.Request)

type Filter

type Filter interface {
	ExecuteFilter(req **http.Request)
}

Filter is an interface that can be registered on the Router to apply custom logic to modify the Request or calling Context

type Match

type Match struct {
	Node          *Node
	Params        map[string][]string
	CatchAllValue string
	ParentMatch   *Match
}

Match represents a matched node in the tree

func NewMatch

func NewMatch(node *Node) *Match

NewMatch creates a new Match instance

func NewMatchWithParent

func NewMatchWithParent(node *Node, parentMatch *Match) *Match

NewMatchWithParent creates a new instance of a match that passes down the values from the parent match

func (*Match) String

func (match *Match) String() string

type MatchCandidate

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

MatchCandidate is a helper class for matching path components

func NewMatchCandidate

func NewMatchCandidate(path string) MatchCandidate

NewMatchCandidate creates a new match candidate instance and initializes if for the first part

func NoMatchCandidate

func NoMatchCandidate() MatchCandidate

NoMatchCandidate represents an empty MatchCandidate

func (MatchCandidate) HasRemainingCandidates

func (mc MatchCandidate) HasRemainingCandidates() bool

HasRemainingCandidates returns true if the MatchCandidate has more candidate parts

func (MatchCandidate) IsNoMatch

func (mc MatchCandidate) IsNoMatch() bool

IsNoMatch returns true if the MatchCandidate equals the NoMatchCandidate value

func (MatchCandidate) NextCandidate

func (mc MatchCandidate) NextCandidate() MatchCandidate

NextCandidate returns the next MatchCandidate in the full path

type Matcher

type Matcher struct {
	LogMatchTime bool
	// contains filtered or unexported fields
}

Matcher is the global matching engine

func NewMatcher

func NewMatcher(router *Router) *Matcher

NewMatcher creates a new instance of the Matcher

func (*Matcher) MatchPathToRoute

func (m *Matcher) MatchPathToRoute(method string, path string, req *http.Request) *Match

MatchPathToRoute attempts to match the given path to a registered Route

type Node

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

Node - tree node to store route information

func (*Node) HasChildren

func (node *Node) HasChildren() bool

HasChildren returns true if the Node has 1 or more sub-Nodes

func (*Node) RouteForMethod

func (node *Node) RouteForMethod(method string) *Route

RouteForMethod returns the route that was defined for the method or nil if no route is defined

func (*Node) String

func (node *Node) String() string

String is the string representation of the object when printing

type Route

type Route struct {
	Method     string
	Path       string
	PathFormat string
	Handler    http.Handler
	Meta       map[string]interface{}
	Info       map[string]interface{}
}

Route stores all the information about a route

func NewRoute

func NewRoute(method string, path string) *Route

NewRoute creates a new Route instance

func NewRouteWithMeta

func NewRouteWithMeta(method string, path string, meta map[string]interface{}) *Route

NewRouteWithMeta creates a new Route instance with meta values

func (*Route) Describe

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

Describe allows you to add a description of the route for other developers

func (*Route) Handle

func (rte *Route) Handle(handler http.Handler) *Route

Handle adds a ContextHandler to the Route

func (*Route) HandleFunc

func (rte *Route) HandleFunc(handlerFunc http.HandlerFunc) *Route

HandleFunc adds a wrapped ContextHandlerFunc (to ContextHandler) to the Route

func (*Route) IsRoot

func (rte *Route) IsRoot() bool

IsRoot returns true if the Route path is '/'

type RouteCache

type RouteCache struct {

	// Entries - ordered list of cache entries
	Entries []CacheEntry

	// MaxEntries - maximum number of items permitted in the cache
	MaxEntries int

	// ReorderOnAccess - move the last accessed item to the top
	ReorderOnAccess bool
	// contains filtered or unexported fields
}

RouteCache - temporary storage for routes

func NewRouteCache

func NewRouteCache() *RouteCache

NewRouteCache - creates a new default RouteCache

func (*RouteCache) Clear

func (rc *RouteCache) Clear()

Clear - reset the cache

func (*RouteCache) Get

func (rc *RouteCache) Get(path string) CacheEntry

Get - fetch a cache entry (if exists)

func (*RouteCache) Put

func (rc *RouteCache) Put(path string, entry CacheEntry)

Put - add an item to the route cache

func (*RouteCache) PutRoute

func (rc *RouteCache) PutRoute(path string, route *Route)

PutRoute - add a route into the route cache

type RouteComponentType

type RouteComponentType int

RouteComponentType - route component types NOTE: variables will be stripped out / replaced so we dont track them

const (
	// ComponentTypeFixed - a fixed path component
	ComponentTypeFixed RouteComponentType = 1 << iota
	// ComponentTypeWildcard - a wildcard path component
	ComponentTypeWildcard
	// ComponentTypeCatchAll - catch all route component
	ComponentTypeCatchAll
)

type Router

type Router struct {

	// ErrorHandler - generic error handler
	ErrorHandler http.Handler

	// ShouldCacheMatchedRoutes - if true then any matched routes should be cached
	// according to the path they were matched to
	ShouldCacheMatchedRoutes bool

	// BeforeChain - a Chain of handlers that will always be executed before the Route handler
	BeforeChain Chain
	// contains filtered or unexported fields
}

Router is the main routing class

func NewRouter

func NewRouter() *Router

NewRouter - creates a new default instance of the Router type

func (*Router) Add

func (r *Router) Add(method string, path string) *Route

Add creates a new Route and registers the instance within the Router

func (*Router) AddFilter

func (r *Router) AddFilter(filter Filter)

AddFilter adds a filter to the list of pre-process filters

func (*Router) AddStatic

func (r *Router) AddStatic(staticRoot string)

AddStatic registers a directory to serve static files

func (*Router) AddStaticWithPrefix

func (r *Router) AddStaticWithPrefix(staticRoot string, prefix string)

AddStaticWithPrefix registers a directory to serve static files. prefix value will be added at matching

func (*Router) NewMatcher

func (r *Router) NewMatcher() *Matcher

NewMatcher returns a new matcher for the given Router

func (*Router) PrintRoutes

func (r *Router) PrintRoutes()

PrintRoutes prints route registration information

func (*Router) PrintTreeInfo

func (r *Router) PrintTreeInfo()

PrintTreeInfo prints debugging information about all registered Routes

func (*Router) ServeHTTP

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

func (*Router) SetDebugLevel

func (r *Router) SetDebugLevel(debugLevel DebugLevel)

SetDebugLevel - enables or disables debug mode

func (*Router) SetErrorHandler

func (r *Router) SetErrorHandler(statusCode int, handler http.Handler)

SetErrorHandler configures a ContextHandler to handle all errors for the supplied status code

func (*Router) SetErrorHandlerFunc

func (r *Router) SetErrorHandlerFunc(statusCode int, handler http.HandlerFunc)

SetErrorHandlerFunc configures a ContextHandlerFunc to handle all errors for the supplied status code

func (*Router) SetGlobalHandler

func (r *Router) SetGlobalHandler(method string, handler http.Handler)

SetGlobalHandler configures a ContextHandler to handle all requests for a given method

func (*Router) SetGlobalHandlerFunc

func (r *Router) SetGlobalHandlerFunc(method string, handlerFunc http.HandlerFunc)

SetGlobalHandlerFunc configures a ContextHandlerFunc to handle all requests for a given method

func (*Router) SetStringVariable

func (r *Router) SetStringVariable(variable string, value string)

SetStringVariable adds a string variable value for substitution

func (*Router) Use

func (r *Router) Use(route *Route) *Route

Use registers a Route instance within the Router

type StaticLocation

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

StaticLocation is a holder for static location information

type Tree

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

Tree - storage for routes

func NewTree

func NewTree() *Tree

NewTree creates a new Tree instance

func (*Tree) AddRouteToTree

func (t *Tree) AddRouteToTree(route *Route, variables map[string]string)

AddRouteToTree splits the route into Nodes and adds them to the tree

func (*Tree) NewNode

func (t *Tree) NewNode(part string, parent *Node) *Node

NewNode creates a new Node instance and appends it to the tree

Jump to

Keyboard shortcuts

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