Documentation ¶
Overview ¶
Package httprouter is a trie based high performance HTTP request router.
A trivial example is:
package main import ( "fmt" "github.com/julienschmidt/httprouter" "net/http" "log" ) func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) { fmt.Fprint(w, "Welcome!\n") } func Hello(w http.ResponseWriter, r *http.Request, ps httprouter.Params) { fmt.Fprintf(w, "hello, %s!\n", ps.ByName("name")) } func main() { router := httprouter.New() router.GET("/", Index) router.GET("/hello/:name", Hello) log.Fatal(http.ListenAndServe(":8080", router)) }
The router matches incoming requests by the request method and the path. If a handle is registered for this path and method, the router delegates the request to that function. For the methods GET, POST, PUT, PATCH, DELETE and OPTIONS shortcut functions exist to register handles, for all other methods router.Handle 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 catch-all 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 /blog/go/ no match /blog/go/request-routers/comments no match
Catch-all parameters match anything until the path end, including the directory index (the '/' before the catch-all). Since they match anything until the end, catch-all 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 ¶
- Variables
- type Handle
- type Param
- type Params
- type RouteGroup
- func (r *RouteGroup) DELETE(path string, handle Handle)
- func (r *RouteGroup) GET(path string, handle Handle)
- func (r *RouteGroup) HEAD(path string, handle Handle)
- func (r *RouteGroup) Handle(method, path string, handle Handle, name ...string)
- func (r *RouteGroup) Handler(method, path string, handler http.Handler, name ...string)
- func (r *RouteGroup) HandlerFunc(method, path string, handler http.HandlerFunc, name ...string)
- func (r *RouteGroup) NewGroup(path string) *RouteGroup
- func (r *RouteGroup) OPTIONS(path string, handle Handle)
- func (r *RouteGroup) PATCH(path string, handle Handle)
- func (r *RouteGroup) POST(path string, handle Handle)
- func (r *RouteGroup) PUT(path string, handle Handle)
- func (r *RouteGroup) SubPath(path string) string
- type Router
- func (r *Router) DELETE(path string, handle Handle)
- func (r *Router) GET(path string, handle Handle)
- func (r *Router) HEAD(path string, handle Handle)
- func (r *Router) Handle(method, path string, handle Handle, name ...string)
- func (r *Router) Handler(method, path string, handler http.Handler, name ...string)
- func (r *Router) HandlerFunc(method, path string, handler http.HandlerFunc, name ...string)
- func (r *Router) NewGroup(path string) *RouteGroup
- func (r *Router) OPTIONS(path string, handle Handle)
- func (r *Router) PATCH(path string, handle Handle)
- func (r *Router) POST(path string, handle Handle)
- func (r *Router) PUT(path string, handle Handle)
- func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request)
Constants ¶
This section is empty.
Variables ¶
var MatchedRouteNameParam = "$matchedRouteName"
MatchedRouteNameParam is the Param name under which the name of the matched route is stored, if Router.SaveMatchedRoutePath is set.
var ParamsKey = paramsKey{}
ParamsKey is the request context key under which URL params are stored.
Functions ¶
This section is empty.
Types ¶
type Handle ¶
type Handle func(http.ResponseWriter, *http.Request, Params)
Handle is a function that can be registered to a route to handle HTTP requests. Like http.HandlerFunc, but has a third parameter for the values of wildcards (path variables).
type Params ¶
type Params []Param
Params is a Param-slice, as returned by the router. 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 ParamsFromContext ¶
ParamsFromContext pulls the URL parameters from a request context, or returns nil if none are present.
func (Params) ByName ¶
ByName returns the value of the first Param which key matches the given name. If no matching Param is found, an empty string is returned.
func (Params) MatchedRouteName ¶
MatchedRouteName retrieves the name of the matched route. Router.SaveMatchedRoutePath must have been enabled when the respective handler was added, otherwise this function always returns an empty string.
type RouteGroup ¶
type RouteGroup struct {
// contains filtered or unexported fields
}
func (*RouteGroup) DELETE ¶
func (r *RouteGroup) DELETE(path string, handle Handle)
func (*RouteGroup) GET ¶
func (r *RouteGroup) GET(path string, handle Handle)
func (*RouteGroup) HEAD ¶
func (r *RouteGroup) HEAD(path string, handle Handle)
func (*RouteGroup) Handle ¶
func (r *RouteGroup) Handle(method, path string, handle Handle, name ...string)
func (*RouteGroup) Handler ¶
func (r *RouteGroup) Handler(method, path string, handler http.Handler, name ...string)
func (*RouteGroup) HandlerFunc ¶
func (r *RouteGroup) HandlerFunc(method, path string, handler http.HandlerFunc, name ...string)
func (*RouteGroup) NewGroup ¶
func (r *RouteGroup) NewGroup(path string) *RouteGroup
func (*RouteGroup) OPTIONS ¶
func (r *RouteGroup) OPTIONS(path string, handle Handle)
func (*RouteGroup) PATCH ¶
func (r *RouteGroup) PATCH(path string, handle Handle)
func (*RouteGroup) POST ¶
func (r *RouteGroup) POST(path string, handle Handle)
func (*RouteGroup) PUT ¶
func (r *RouteGroup) PUT(path string, handle Handle)
func (*RouteGroup) SubPath ¶ added in v2.3.4
func (r *RouteGroup) SubPath(path string) string
type Router ¶
type Router struct { // If enabled, adds the matched route path onto the http.Request context // before invoking the handler. // The matched route path is only added to handlers of routes that were // registered when this option was enabled. SaveMatchedRoutePath 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. HandleOPTIONS bool // An optional http.Handler that is called on automatic OPTIONS requests. // The handler is only called if HandleOPTIONS is true and no OPTIONS // handler for the specific path was set. // The "Allowed" header is set before calling the handler. GlobalOPTIONS http.Handler // 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 // Function to handle panics recovered from http handlers. // 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. PanicHandler func(http.ResponseWriter, *http.Request, interface{}) // contains filtered or unexported fields }
Router is a http.Handler which can be used to dispatch requests to different handler functions via configurable routes
func New ¶
func New() *Router
New returns a new initialized Router. Path auto-correction, including trailing slashes, is enabled by default.
func (*Router) Handle ¶
Handle registers a new request handle with the given path and method.
For GET, POST, PUT, PATCH and DELETE requests the respective shortcut functions can be used.
This function 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 (*Router) Handler ¶
Handler is an adapter which allows the usage of an http.Handler as a request handle. The Params are available in the request context under ParamsKey.
func (*Router) HandlerFunc ¶
func (r *Router) HandlerFunc(method, path string, handler http.HandlerFunc, name ...string)
HandlerFunc is an adapter which allows the usage of an http.HandlerFunc as a request handle.
func (*Router) NewGroup ¶
func (r *Router) NewGroup(path string) *RouteGroup