hroute

package module
v0.0.0-...-583ecab Latest Latest
Warning

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

Go to latest
Published: Dec 12, 2016 License: BSD-3-Clause Imports: 5 Imported by: 0

Documentation

Overview

Package hroute implements yet another HTTP route multiplexer. The design is strongly influenced by Julien Schmidt's httprouter package but the matching algorithm is more general and although httprouter was used to start the implementation, there is very little code left in common between the two.

Specific differences from httprouter:

- a specific pattern may override a more general pattern. For example, it will allow both "/:id" and "/debug" patterns to be registered. This applies to catch-all *name patterns too - the longest explicit match wins. Note that the pattern matching algorithm is not order dependent - no matter what order the patterns are registered in, the result will be the same.

- it provides a facility for subroute handling - a Router can be used to serve a set of subroutes within a larger superstructure.

- it provides a way to build paths from routes - the *Pattern value returned from Handle allows the reconstruction of a path from a registered route.

- the handler type is an interface not a function, allowing clients to store and retrieve extra information from the router tree if needed.

- it is possible to register a handler that will handle all methods by registering with the "*" method. This will be overridden be more specific method handlers.

- much of the naming has also been changed to be more consistent with the net/http and its ServeMux type.

- there is no case-insensitive path lookup.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

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

Types

type Handler

type Handler interface {
	ServeRoute(http.ResponseWriter, *http.Request, Params)
}

Handler is the interface implemented by hroute HTTP handlers. See HTTPHandler for an adaptor that will put the parameters into the request context (only available on Go 1.7 and later).

type HandlerFunc

type HandlerFunc func(http.ResponseWriter, *http.Request, Params)

HandlerFunc implements Handler for a function.

func (HandlerFunc) ServeRoute

func (r HandlerFunc) ServeRoute(w http.ResponseWriter, req *http.Request, p Params)

ServeRoute implements Handler by calling r with the given arguments.

type MethodNotAllowed

type MethodNotAllowed struct{}

MethodNotAllowed is used as the default handler when an implementation for a method is not found.

func (MethodNotAllowed) ServeRoute

func (h MethodNotAllowed) ServeRoute(w http.ResponseWriter, req *http.Request, _ Params)

ServeRoute implements Handler.ServeRoute by returning an StatusMethodNotAllowed response.

type NotFound

type NotFound struct{}

NotFound is used as the default hander when a route is not found in the router.

func (NotFound) ServeRoute

func (h NotFound) ServeRoute(w http.ResponseWriter, req *http.Request, _ Params)

ServeRoute implements Handler.ServeRoute by calling http.NotFound.

type Param

type Param struct {
	// Key holds the key of the parameter.
	Key string

	// Value holds its value. When the wildcard is a "*",
	// the value will always hold a leading slash.
	Value string
}

Param holds a path parameter that represents the value of a wildcard parameter.

type Params

type Params []Param

Params represents the values for a set of wildcard parameters. There will only be one instance of any given key.

func (Params) Get

func (ps Params) Get(key string) string

Get returns the first value with the given key, or the empty string if it is not found.

type Pattern

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

Pattern holds a parsed path pattern.

func ParsePattern

func ParsePattern(p string) (*Pattern, error)

ParsePattern parses the given router pattern from the given path. A valid pattern always starts with a leading "/". Named portions of the path are dynamic path segments, of the form :param. They match a segment of the path, so they must be preceded by a "/" and followed by a "/" or appear at the end of the string.

For example:

/:name/info

would match /foo/info but not /foo/bar/info.

A catch-all pattern of the form *param may appear at the end of the path and matches any number of path segments at the end of the pattern. It must be preceded by a "/". The value of a catch-all parameter will include a leading "/".

For example:

/foo/*name

would match /foo/info and /foo/bar/info.

func (*Pattern) CatchAll

func (p *Pattern) CatchAll() bool

CatchAll reports whether the pattern has a :* suffix which will catch all paths unde+

func (*Pattern) Keys

func (p *Pattern) Keys() []string

Keys returns all the parameter keys specified in the pattern. The caller must not change the elements of the returned slice.

func (*Pattern) Path

func (p *Pattern) Path(vals ...string) (string, error)

Path returns a path constructed by interpolating the given parameter values. All the parameter values must be non-empty. Each value corresponds to the parameter at the same position in the slice returned by Keys.

For example, if the original pattern path was /foo/:name/*rest then Keys would return {"name", "rest"} and Path("a", "/b/c") would return /foo/a/b/c.

func (*Pattern) PathWithParams

func (p *Pattern) PathWithParams(Params) (string, error)

PathWithParams returns a path constructed by interpolating the parameter values in p, which must contain elements with all the keys returned by p.Keys.

func (*Pattern) String

func (p *Pattern) String() string

String returns the string representation of the pattern.

type Redirect

type Redirect struct {
	Path string
	Code int
}

Redirect is used as the handler when the router requires a redirection.

func (Redirect) ServeRoute

func (r Redirect) ServeRoute(w http.ResponseWriter, req *http.Request, _ Params)

ServeRoute implements Handler by redirecting to r.Path with the response status r.Code.

type Router

type Router struct {

	// NotFoundHandler is the handler used when no matching route is found.
	// If it is nil, NotFound{} is used.
	NotFound Handler

	// MethodNotAllowedHandler is the handler used when a handler
	// cannot be found for a given method but there is a handler
	// for the requested path. If it is nil, MethodNotAllowed{} will be
	// used.
	MethodNotAllowed Handler

	// When Panic is not nil, panics in handlers will be
	// recovered and PanicHandler will be called with the HTTP
	// handler parameters, the Handler responsible for the panic and
	// any parameters it was passed, and the recovered panic value.
	//
	// It should be used to generate a 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.
	Panic func(w http.ResponseWriter, req *http.Request, h Handler, p Params, err interface{})
	// contains filtered or unexported fields
}

Router represents an HTTP router. Its exported variables should not be changed while HTTP requests are being served.

func New

func New() *Router

New returns a new Router. Path auto-correction, including trailing slashes, is enabled by default.

func (*Router) Handle

func (r *Router) Handle(method, pattern string, handler Handler) *Pattern

Handle registers the handler for the given pattern and methods. If a handler is already registered for the given pattern or the pattern is invalid, Handle panics.

It returns the parsed pattern, suitable for recreating the path.

func (*Router) HandleFunc

func (r *Router) HandleFunc(method, pattern string, handler func(http.ResponseWriter, *http.Request, Params)) *Pattern

HandleFunc a convenience method that calls Handle with HandlerFunc(handler).

func (*Router) Handler

func (r *Router) Handler(method, path string) (Handler, Params, *Pattern)

Handler returns the handler to use for the given method and path, the parameters appropriate for passing to the handler, and the pattern associated with the route. If there is no handler found, it returns zero results.

func (*Router) HandlerToUse

func (r *Router) HandlerToUse(method, path string) (Handler, Params, *Pattern)

HandlerToUse returns the handler that will be used to handle a request with the given method and path. It never returns a nil handler. If a handler has not been registered with the given path, one of r.NotFound, r.MethodNotAllowed or a value of type Redirect will be returned. If a handler was registered, the returned pattern will hold the pattern it was registered with.

func (*Router) ServeHTTP

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

ServeHTTP implements http.Handler by consulting req.URL.Method and req.URL.Path and calling the registered handler that most closely matches.

func (*Router) ServeRoute

func (r *Router) ServeRoute(w http.ResponseWriter, req *http.Request, p Params)

ServeRoute implements Handler by calling ServeSubroute with path set to the value of the last element in p. This allows a Router to be registered directly as a subroute handler for a subpath.

func (*Router) ServeSubroute

func (r *Router) ServeSubroute(w http.ResponseWriter, req *http.Request, path string)

ServeSubroute is like ServeHTTP except that instead of using req.URL.Path to route requests, it uses the given path parameter.

This is useful when the router is being used to serve a subtree but it is desired to keep the request URL intact.

Jump to

Keyboard shortcuts

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