Documentation ¶
Overview ¶
This is inspired by Julien Schmidt's httprouter, in that it uses a patricia tree, but the implementation is rather different. Specifically, the routing rules are relaxed so that a single path segment may be a wildcard in one route and a static token in another. This gives a nice combination of high performance with a lot of convenience in designing the routing patterns.
Index ¶
- func Clean(p string) string
- func JSON(w http.ResponseWriter, value interface{}) error
- func Version() string
- type CompatGroup
- func (g CompatGroup) DELETE(path string, handler http.HandlerFunc)
- func (g CompatGroup) GET(path string, handler http.HandlerFunc)
- func (g CompatGroup) HEAD(path string, handler http.HandlerFunc)
- func (g CompatGroup) Handle(method string, path string, handler http.HandlerFunc)
- func (g CompatGroup) NewGroup(path string, opts ...GroupOption) *CompatGroup
- func (g CompatGroup) OPTIONS(path string, handler http.HandlerFunc)
- func (g CompatGroup) PATCH(path string, handler http.HandlerFunc)
- func (g CompatGroup) POST(path string, handler http.HandlerFunc)
- func (g CompatGroup) PUT(path string, handler http.HandlerFunc)
- func (g CompatGroup) WithGroup(path string, fn func(g *CompatGroup))
- func (g CompatGroup) WithMiddleware(middleware MiddlewareFunc) *CompatGroup
- type CompatRouter
- type Group
- func (g *Group) Compat() *CompatGroup
- func (g *Group) DELETE(path string, handler HandlerFunc)
- func (g *Group) GET(path string, handler HandlerFunc)
- func (g *Group) HEAD(path string, handler HandlerFunc)
- func (g *Group) Handle(method string, path string, handler HandlerFunc)
- func (g *Group) NewGroup(path string, opts ...GroupOption) *Group
- func (g *Group) OPTIONS(path string, handler HandlerFunc)
- func (g *Group) PATCH(path string, handler HandlerFunc)
- func (g *Group) POST(path string, handler HandlerFunc)
- func (g *Group) PUT(path string, handler HandlerFunc)
- func (g *Group) WithGroup(path string, fn func(g *Group))
- func (g *Group) WithMiddleware(middleware MiddlewareFunc) *Group
- type GroupOption
- type H
- type HandlerFunc
- type MiddlewareFunc
- type Option
- func UseURLPath() Option
- func WithHeadCanUseGet(on bool) Option
- func WithMethodNotAllowedHandler(handler HandlerFunc) Option
- func WithNotFoundHandler(handler HandlerFunc) Option
- func WithRedirectBehavior(value RedirectBehavior) Option
- func WithRedirectCleanPath(on bool) Option
- func WithRedirectMethodBehavior(value map[string]RedirectBehavior) Option
- func WithRedirectTrailingSlash(on bool) Option
- func WithRemoveCatchAllTrailingSlash(on bool) Option
- type Param
- type Params
- func (ps Params) Get(name string) (string, bool)
- func (ps Params) Int32(name string) (int32, error)
- func (ps Params) Int64(name string) (int64, error)
- func (ps Params) Map() map[string]string
- func (ps Params) Text(name string) string
- func (ps Params) Uint32(name string) (uint32, error)
- func (ps Params) Uint64(name string) (uint64, error)
- type RedirectBehavior
- type Request
- type RouteInfo
- type Router
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Clean ¶
Clean 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
func JSON ¶
func JSON(w http.ResponseWriter, value interface{}) error
JSON marshals the value as JSON and writes it to the response writer.
Don't hesitate to copy-paste this function to your project and customize it as necessary.
Types ¶
type CompatGroup ¶
type CompatGroup struct {
// contains filtered or unexported fields
}
CompatGroup is like Group, but it works with http.HandlerFunc instead of treemux handler.
func (CompatGroup) DELETE ¶
func (g CompatGroup) DELETE(path string, handler http.HandlerFunc)
func (CompatGroup) GET ¶
func (g CompatGroup) GET(path string, handler http.HandlerFunc)
func (CompatGroup) HEAD ¶
func (g CompatGroup) HEAD(path string, handler http.HandlerFunc)
func (CompatGroup) Handle ¶
func (g CompatGroup) Handle(method string, path string, handler http.HandlerFunc)
func (CompatGroup) NewGroup ¶
func (g CompatGroup) NewGroup(path string, opts ...GroupOption) *CompatGroup
func (CompatGroup) OPTIONS ¶
func (g CompatGroup) OPTIONS(path string, handler http.HandlerFunc)
func (CompatGroup) PATCH ¶
func (g CompatGroup) PATCH(path string, handler http.HandlerFunc)
func (CompatGroup) POST ¶
func (g CompatGroup) POST(path string, handler http.HandlerFunc)
func (CompatGroup) PUT ¶
func (g CompatGroup) PUT(path string, handler http.HandlerFunc)
func (CompatGroup) WithGroup ¶
func (g CompatGroup) WithGroup(path string, fn func(g *CompatGroup))
func (CompatGroup) WithMiddleware ¶
func (g CompatGroup) WithMiddleware(middleware MiddlewareFunc) *CompatGroup
type CompatRouter ¶
type CompatRouter struct { *Router *CompatGroup }
type Group ¶
type Group struct {
// contains filtered or unexported fields
}
Group is a group of routes and middlewares.
func (*Group) Compat ¶
func (g *Group) Compat() *CompatGroup
func (*Group) DELETE ¶
func (g *Group) DELETE(path string, handler HandlerFunc)
Syntactic sugar for Handle("DELETE", path, handler)
func (*Group) GET ¶
func (g *Group) GET(path string, handler HandlerFunc)
Syntactic sugar for Handle("GET", path, handler)
func (*Group) HEAD ¶
func (g *Group) HEAD(path string, handler HandlerFunc)
Syntactic sugar for Handle("HEAD", path, handler)
func (*Group) Handle ¶
func (g *Group) Handle(method string, path string, handler HandlerFunc)
Path elements starting with : indicate a wildcard in the path. A wildcard will only match on a single path segment. That is, the pattern `/post/:postid` will match on `/post/1` or `/post/1/`, but not `/post/1/2`.
A path element starting with * is a catch-all, whose value will be a string containing all text in the URL matched by the wildcards. For example, with a pattern of `/images/*path` and a requested URL `images/abc/def`, path would contain `abc/def`.
Routing Rule Priority ¶
The priority rules in the router are simple.
1. Static path segments take the highest priority. If a segment and its subtree are able to match the URL, that match is returned.
2. Wildcards take second priority. For a particular wildcard to match, that wildcard and its subtree must match the URL.
3. Finally, a catch-all rule will match when the earlier path segments have matched, and none of the static or wildcard conditions have matched. Catch-all rules must be at the end of a pattern.
So with the following patterns, we'll see certain matches:
router = treemux.New() router.GET("/:page", pageHandler) router.GET("/:year/:month/:post", postHandler) router.GET("/:year/:month", archiveHandler) router.GET("/images/*path", staticHandler) router.GET("/favicon.ico", staticHandler) /abc will match /:page /2014/05 will match /:year/:month /2014/05/really-great-blog-post will match /:year/:month/:post /images/CoolImage.gif will match /images/*path /images/2014/05/MayImage.jpg will also match /images/*path, with all the text after /images stored in the variable path. /favicon.ico will match /favicon.ico
Trailing Slashes ¶
The router has special handling for paths with trailing slashes. If a pattern is added to the router with a trailing slash, any matches on that pattern without a trailing slash will be redirected to the version with the slash. If a pattern does not have a trailing slash, matches on that pattern with a trailing slash will be redirected to the version without.
The trailing slash flag is only stored once for a pattern. That is, if a pattern is added for a method with a trailing slash, all other methods for that pattern will also be considered to have a trailing slash, regardless of whether or not it is specified for those methods too.
This behavior can be turned off by setting TreeMux.RedirectTrailingSlash to false. By default it is set to true. The specifics of the redirect depend on RedirectBehavior.
One exception to this rule is catch-all patterns. By default, trailing slash redirection is disabled on catch-all patterns, since the structure of the entire URL and the desired patterns can not be predicted. If trailing slash removal is desired on catch-all patterns, set TreeMux.RemoveCatchAllTrailingSlash to true.
router = treemux.New() router.GET("/about", pageHandler) router.GET("/posts/", postIndexHandler) router.POST("/posts", postFormHandler) GET /about will match normally. GET /about/ will redirect to /about. GET /posts will redirect to /posts/. GET /posts/ will match normally. POST /posts will redirect to /posts/, because the GET method used a trailing slash.
func (*Group) NewGroup ¶
func (g *Group) NewGroup(path string, opts ...GroupOption) *Group
NewGroup adds a sub-group to this group.
func (*Group) OPTIONS ¶
func (g *Group) OPTIONS(path string, handler HandlerFunc)
Syntactic sugar for Handle("OPTIONS", path, handler)
func (*Group) PATCH ¶
func (g *Group) PATCH(path string, handler HandlerFunc)
Syntactic sugar for Handle("PATCH", path, handler)
func (*Group) POST ¶
func (g *Group) POST(path string, handler HandlerFunc)
Syntactic sugar for Handle("POST", path, handler)
func (*Group) PUT ¶
func (g *Group) PUT(path string, handler HandlerFunc)
Syntactic sugar for Handle("PUT", path, handler)
func (*Group) WithMiddleware ¶
func (g *Group) WithMiddleware(middleware MiddlewareFunc) *Group
type GroupOption ¶
type GroupOption interface { Option // contains filtered or unexported methods }
func WithGroup ¶
func WithGroup(fn func(g *Group)) GroupOption
WithGroup calls the fn with the current Group.
func WithHandler ¶
func WithHandler(fn HandlerFunc) GroupOption
WithHandler is like WithMiddleware, but the handler can't modify the request.
func WithMiddleware ¶
func WithMiddleware(fn MiddlewareFunc) GroupOption
WithMiddleware adds a middleware handler to the Group's middleware stack.
type HandlerFunc ¶
type HandlerFunc func(http.ResponseWriter, Request) error
func HTTPHandler ¶
func HTTPHandler(handler http.Handler) HandlerFunc
func HTTPHandlerFunc ¶
func HTTPHandlerFunc(handler http.HandlerFunc) HandlerFunc
type MiddlewareFunc ¶
type MiddlewareFunc func(next HandlerFunc) HandlerFunc
type Option ¶
type Option interface {
// contains filtered or unexported methods
}
func UseURLPath ¶
func UseURLPath() Option
UseURLPath determines from where the router gets its path to search. By default it pulls the data from the RequestURI member, but this can be overridden to use URL.Path instead.
There is a small tradeoff here. Using RequestURI allows the router to handle encoded slashes (i.e. %2f) in the URL properly, while URL.Path provides better compatibility with some utility functions in the http library that modify the Request before passing it to the router.
func WithHeadCanUseGet ¶
WithHeadCanUseGet allows the router to use the GET handler to respond to HEAD requests if no explicit HEAD handler has been added for the matching pattern. This is true by default.
func WithMethodNotAllowedHandler ¶
func WithMethodNotAllowedHandler(handler HandlerFunc) Option
MethodNotAllowedHandler is called when a pattern matches, but that pattern does not have a handler for the requested method. The default handler just writes the status code http.StatusMethodNotAllowed.
func WithNotFoundHandler ¶
func WithNotFoundHandler(handler HandlerFunc) Option
WithNotFoundHandler is called when there is no a matching pattern. The default NotFoundHandler is http.NotFound.
func WithRedirectBehavior ¶
func WithRedirectBehavior(value RedirectBehavior) Option
WithRedirectBehavior sets the default redirect behavior when RedirectTrailingSlash or RedirectCleanPath are true. The default value is Redirect301.
func WithRedirectCleanPath ¶
WithRedirectCleanPath allows the router to try clean the current request path, if no handler is registered for it, using CleanPath from github.com/dimfeld/httppath. This is true by default.
func WithRedirectMethodBehavior ¶
func WithRedirectMethodBehavior(value map[string]RedirectBehavior) Option
WithRedirectMethodBehavior overrides the default behavior for a particular HTTP method. The key is the method name, and the value is the behavior to use for that method.
func WithRedirectTrailingSlash ¶
WithRedirectTrailingSlash enables automatic redirection in case router doesn't find a matching route for the current request path but a handler for the path with or without the trailing slash exists. This is true by default.
func WithRemoveCatchAllTrailingSlash ¶
WithRemoveCatchAllTrailingSlash removes the trailing slash when a catch-all pattern is matched, if set to true. By default, catch-all paths are never redirected.
type RedirectBehavior ¶
type RedirectBehavior int
RedirectBehavior sets the behavior when the router redirects the request to the canonical version of the requested URL using RedirectTrailingSlash or RedirectClean. The default behavior is to return a 301 status, redirecting the browser to the version of the URL that matches the given pattern.
On a POST request, most browsers that receive a 301 will submit a GET request to the redirected URL, meaning that any data will likely be lost. If you want to handle and avoid this behavior, you may use Redirect307, which causes most browsers to resubmit the request using the original method and request body.
Since 307 is supposed to be a temporary redirect, the new 308 status code has been proposed, which is treated the same, except it indicates correctly that the redirection is permanent. The big caveat here is that the RFC is relatively recent, and older browsers will not know what to do with it. Therefore its use is not recommended unless you really know what you're doing.
Finally, the UseHandler value will simply call the handler function for the pattern.
const ( Redirect301 RedirectBehavior = iota // Return 301 Moved Permanently Redirect307 // Return 307 HTTP/1.1 Temporary Redirect Redirect308 // Return a 308 RFC7538 Permanent Redirect UseHandler // Just call the handler function )
type RouteInfo ¶
type RouteInfo struct {
// contains filtered or unexported fields
}
func RouteFromContext ¶
Source Files ¶
Directories ¶
Path | Synopsis |
---|---|
example
|
|
basic
Module
|
|
basic-compat
Module
|
|
error-handling
Module
|
|
rate-limiting
Module
|
|
extra
|
|
reqlog
Module
|
|
treemuxgzip
Module
|
|
treemuxotel
Module
|