Documentation ¶
Overview ¶
Package httpdispatch is a trie based high performance HTTP request dispatcher.
A trivial example is:
package main import ( "fmt" "net/http" "log" "github.com/dolab/httpdispatch" ) func Index(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "Welcome!\n") } func Hello(w http.ResponseWriter, r *http.Request) { params := httpdispatch.ContextParams(r) fmt.Fprintf(w, "hello, %s!\n", params.ByName("name")) } func main() { router := httpdispatch.New() router.GET("/", http.HandlerFunc(Index)) router.GET("/hello/:name", http.HandlerFunc(Hello)) log.Fatal(http.ListenAndServe(":8080", router)) }
The router matches incoming requests by the request method and the path. If a handler is registered for this path and method, the router delegates the request to that function. For the methods OPTIONS, GET, POST, PUT, PATCH and DELETE shortcut functions exist to register handlers, for all other methods *dispatcher.Handler can be used.
The registered path, against which the router matches incoming requests, can contain two types of parameters:
Syntax Type :name named parameter *name wildcard parameter
Named parameters are dynamic path segments. They match anything until the next '/' or the path end:
Path: /blog/:category/:post Requests: /blog/go/request-routers match: category="go", post="request-routers" /blog/go/request-routers/ no match, but the router would redirect to /blog/go/request-routers /blog/go/ no match /blog/go/request-routers/comments no match
Wildcard parameters match anything until the path end, including the directory index (the '/' before the wildcard). Since they match anything until the end, wildcard parameters must always be the final path element.
Path: /files/*filepath Requests: /files/ match: filepath="/" /files/LICENSE match: filepath="/LICENSE" /files/templates/article.html match: filepath="/templates/article.html" /files no match, but the router would redirect
The value of parameters is saved as a slice of the Param struct, consisting each of a key and a value. The slice is passed to the Handle func as a third parameter. There are two ways to retrieve the value of a parameter:
// by the name of the parameter user := ps.ByName("user") // defined by :user or *user // by the index of the parameter. This way you can also get the name (key) thirdKey := ps[2].Key // the name of the 3rd parameter thirdValue := ps[2].Value // the value of the 3rd parameter
Index ¶
- func Normalize(p string) string
- type ContextHandle
- type Dispatcher
- func (dp *Dispatcher) DELETE(uripath string, handler http.Handler)
- func (dp *Dispatcher) GET(uripath string, handler http.Handler)
- func (dp *Dispatcher) HEAD(uripath string, handler http.Handler)
- func (dp *Dispatcher) Handle(method, uripath string, handler Handler)
- func (dp *Dispatcher) Handler(method, uripath string, handler http.Handler)
- func (dp *Dispatcher) HandlerFunc(method, uripath string, handler http.HandlerFunc)
- func (dp *Dispatcher) Lookup(method, uripath string) (Handler, Params, bool)
- func (dp *Dispatcher) OPTIONS(uripath string, handler http.Handler)
- func (dp *Dispatcher) PATCH(uripath string, handler http.Handler)
- func (dp *Dispatcher) POST(uripath string, handler http.Handler)
- func (dp *Dispatcher) PUT(uripath string, handler http.Handler)
- func (dp *Dispatcher) ServeFiles(filename string, fs http.FileSystem)
- func (dp *Dispatcher) ServeHTTP(w http.ResponseWriter, r *http.Request)
- type FileHandle
- type Handler
- type Param
- type Params
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Normalize ¶
Normalize 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:
- Replace multiple slashes with a single slash.
- Eliminate each . path name element (the current directory).
- Eliminate each inner .. path name element (the parent directory) along with the non-.. element that precedes it.
- 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
Types ¶
type ContextHandle ¶
type ContextHandle struct {
// contains filtered or unexported fields
}
ContextHandle defines container of registered http.Handler with useful context, such as package name, controller name and action name of handle.
func NewContextHandle ¶
func NewContextHandle(handler http.Handler, useContext bool) *ContextHandle
NewContextHandle returns *ContextHandle with handler info
func (*ContextHandle) Handle ¶
func (ch *ContextHandle) Handle(w http.ResponseWriter, r *http.Request, ps Params)
Handle hijacks http.Handler with request params
type Dispatcher ¶
type Dispatcher struct { // If enabled, the router tries to inject parsed params within http.Request. RequestContext bool // Enables automatic redirection if the current route can't be matched but a // handler for the path with (without) the trailing slash exists. // For example if /foo/ is requested but a route only exists for /foo, the // client is redirected to /foo with http status code 301 for GET requests // and 307 for all other request methods. RedirectTrailingSlash bool // If enabled, the router tries to fix the current request path, if no // handle is registered for it. // First superfluous path elements like ../ or // are removed. // Afterwards the router does a case-insensitive lookup of the cleaned path. // If a handle can be found for this route, the router makes a redirection // to the corrected path with status code 301 for GET requests and 307 for // all other request methods. // For example /FOO and /..//Foo could be redirected to /foo. // RedirectTrailingSlash is independent of this option. RedirectFixedPath bool // If enabled, the router checks if another method is allowed for the // current route, if the current request can not be routed. // If this is the case, the request is answered with 'Method Not Allowed' // and HTTP status code 405. // If no other Method is allowed, the request is delegated to the NotFound // handler. HandleMethodNotAllowed bool // If enabled, the router automatically replies to OPTIONS requests. // Custom OPTIONS handlers take priority over automatic replies. HandleMethodOPTIONS bool // Configurable http.Handler which is called when no matching route is // found. If it is not set, http.NotFound is used. NotFound http.Handler // Configurable http.Handler which is called when a request // cannot be routed and HandleMethodNotAllowed is true. // If it is not set, http.Error with http.StatusMethodNotAllowed is used. // The "Allow" header with allowed request methods is set before the handler // is called. MethodNotAllowed http.Handler // Configurable http.Handler which is called for OPTIONS request. // The "Allow" header with allowed request methods is set before the handler // is called. MethodOptions http.Handler // Function to handle panics recovered from http handlers. // It should be used to generate an error page and return the http error code // 500 (Internal Server Error). // The handler can be used to keep your server from crashing because of // unrecovered panics. PanicHandler func(http.ResponseWriter, *http.Request, interface{}) // contains filtered or unexported fields }
Dispatcher is a http.Handler which can be used to dispatch requests to different handler functions via configurable routes
func New ¶
func New() *Dispatcher
New returns a new initialized Dispatcher. Path auto-correction, including trailing slashes, is enabled by default.
func (*Dispatcher) DELETE ¶
func (dp *Dispatcher) DELETE(uripath string, handler http.Handler)
DELETE is a shortcut for dispatcher.Handler("GET", path, http.Handler)
func (*Dispatcher) GET ¶
func (dp *Dispatcher) GET(uripath string, handler http.Handler)
GET is a shortcut for dispatcher.Handler("GET", path, http.Handler)
func (*Dispatcher) HEAD ¶
func (dp *Dispatcher) HEAD(uripath string, handler http.Handler)
HEAD is a shortcut for dispatcher.Handler("GET", path, http.Handler)
func (*Dispatcher) Handle ¶
func (dp *Dispatcher) Handle(method, uripath string, handler Handler)
Handle registers a new request handler with the given path and method. This is e.g. useful to build a framework around the dispatcher.
For OPTIONS, GET, POST, PUT, PATCH and DELETE requests the respective shortcut funcs can be used.
This func is intended for bulk loading and to allow the usage of less frequently used, non-standardized or custom methods (e.g. for internal communication with a proxy).
func (*Dispatcher) Handler ¶
func (dp *Dispatcher) Handler(method, uripath string, handler http.Handler)
Handler is an adapter which allows the usage of a http.Handler as a request handle.
func (*Dispatcher) HandlerFunc ¶
func (dp *Dispatcher) HandlerFunc(method, uripath string, handler http.HandlerFunc)
HandlerFunc is an adapter which allows the usage of an http.HandlerFunc as a request handler.
func (*Dispatcher) Lookup ¶
func (dp *Dispatcher) Lookup(method, uripath string) (Handler, Params, bool)
Lookup allows the manual lookup of a method + path combo. This is e.g. useful to build a framework around the dispatcher. If the path was found, it returns the handler func and the captured parameter values.
NOTE: It returns handler when the third returned value indicates a redirection to the same path with / without the trailing slash should be performed.
func (*Dispatcher) OPTIONS ¶
func (dp *Dispatcher) OPTIONS(uripath string, handler http.Handler)
OPTIONS is a shortcut for dispatcher.Handler("GET", path, http.Handler)
func (*Dispatcher) PATCH ¶
func (dp *Dispatcher) PATCH(uripath string, handler http.Handler)
PATCH is a shortcut for dispatcher.Handler("GET", path, http.Handler)
func (*Dispatcher) POST ¶
func (dp *Dispatcher) POST(uripath string, handler http.Handler)
POST is a shortcut for dispatcher.Handler("GET", path, http.Handler)
func (*Dispatcher) PUT ¶
func (dp *Dispatcher) PUT(uripath string, handler http.Handler)
PUT is a shortcut for dispatcher.Handler("GET", path, http.Handler)
func (*Dispatcher) ServeFiles ¶
func (dp *Dispatcher) ServeFiles(filename string, fs http.FileSystem)
ServeFiles serves files from the given file system root. The path must end with "/*filepath", files are then served from the local path /path/to/*filepath. For example if root is "/etc" and *filepath is "passwd", the local file "/etc/passwd" would be served. Internally a http.FileServer is used, therefore http.NotFound is used instead of the Dispatcher's NotFound handler. To use the operating system's file system implementation, use http.Dir:
router.ServeFiles("/static/*filepath", http.Dir("/var/www"))
func (*Dispatcher) ServeHTTP ¶
func (dp *Dispatcher) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP makes the router implement the http.Handler interface.
type FileHandle ¶
type FileHandle struct {
*ContextHandle
}
FileHandle defines static files server context
func NewFileHandle ¶
func NewFileHandle(fs http.FileSystem) *FileHandle
NewFileHandle returns *FileHandle with passed http.HandlerFunc
func (*FileHandle) Handle ¶
func (fh *FileHandle) Handle(w http.ResponseWriter, r *http.Request, ps Params)
Handle hijacks request path with filepath by overwrite
type Handler ¶
type Handler interface {
Handle(http.ResponseWriter, *http.Request, Params)
}
Handler is an interface that can be registered to a route to handle HTTP requests. Like http.HandlerFunc, but has a third parameter for the values of wildcards (variables).
type Params ¶
type Params []Param
Params is a Param-slice, as returned by the dispatcher. The slice is ordered, the first URL parameter is also the first slice value. It is therefore safe to read values by the index.
func ContextParams ¶
ContextParams pulls the URL parameters from a request context, or returns nil if none are present.
This is only present from go 1.7.