Documentation ¶
Overview ¶
Package xmux is a net/context aware, tree based high performance HTTP request multiplexer forked from httprouter.
A trivial example is:
package main import ( "fmt" "net/http" "log" "github.com/rs/xhandler" "github.com/rs/xmux" "golang.org/x/net/context" ) func Index(ctx context.Context, w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "Welcome!\n") } func Hello(ctx context.Context, w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "hello, %s!\n", xmux.Param(ctx, "name")) } func main() { mux := xmux.New() mux.GET("/", Index) mux.GET("/hello/:name", Hello) log.Fatal(http.ListenAndServe(":8080", xhandler.New(context.Background(), mux))) }
The muxer 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 and DELETE shortcut functions exist to register handlers, for all other methods mux.Handle can be used.
The registered path, against which the muxer 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 aParams type saved into the context. Parameters can be retrieved by name using xhandler.Param(ctx, name) method:
user := xmux.Param(ctx, "user") // defined by :user or *user
Index ¶
- func CleanPath(p string) string
- func Param(ctx context.Context, name string) string
- func TestSetParamContext(ctx context.Context, p ParamHolder) context.Context
- type Group
- func (g *Group) DELETE(path string, handler xhandler.HandlerC)
- func (g *Group) GET(path string, handler xhandler.HandlerC)
- func (g *Group) HEAD(path string, handler xhandler.HandlerC)
- func (g *Group) Handle(method, path string, handler http.Handler)
- func (g *Group) HandleC(method, path string, handler xhandler.HandlerC)
- func (g *Group) HandleFunc(method, path string, handler http.HandlerFunc)
- func (g *Group) HandleFuncC(method, path string, handler xhandler.HandlerFuncC)
- func (g *Group) NewGroup(path string) *Group
- func (g *Group) OPTIONS(path string, handler xhandler.HandlerC)
- func (g *Group) PATCH(path string, handler xhandler.HandlerC)
- func (g *Group) POST(path string, handler xhandler.HandlerC)
- func (g *Group) PUT(path string, handler xhandler.HandlerC)
- type Mux
- func (mux *Mux) DELETE(path string, handler xhandler.HandlerC)
- func (mux *Mux) GET(path string, handler xhandler.HandlerC)
- func (mux *Mux) HEAD(path string, handler xhandler.HandlerC)
- func (mux *Mux) Handle(method, path string, handler http.Handler)
- func (mux *Mux) HandleC(method, path string, handler xhandler.HandlerC)
- func (mux *Mux) HandleFunc(method, path string, handler http.HandlerFunc)
- func (mux *Mux) HandleFuncC(method, path string, handler xhandler.HandlerFuncC)
- func (mux *Mux) Lookup(method, path string) (xhandler.HandlerC, ParamHolder, bool)
- func (mux *Mux) NewGroup(path string) *Group
- func (mux *Mux) OPTIONS(path string, handler xhandler.HandlerC)
- func (mux *Mux) PATCH(path string, handler xhandler.HandlerC)
- func (mux *Mux) POST(path string, handler xhandler.HandlerC)
- func (mux *Mux) PUT(path string, handler xhandler.HandlerC)
- func (mux *Mux) ServeHTTPC(ctx context.Context, w http.ResponseWriter, r *http.Request)
- type ParamHolder
- type Parameter
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func CleanPath ¶
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:
- 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 Param ¶
Param picks one URL parameters stored in context by its name.
This is a shortcut for:
xmux.Params(ctx).Get("name")
func TestSetParamContext ¶
func TestSetParamContext(ctx context.Context, p ParamHolder) context.Context
TestSetParamContext sets ParamHolder to context.Context for testing
Types ¶
type Group ¶
type Group struct {
// contains filtered or unexported fields
}
Group makes it simple to configure a group of routes with the same prefix. Use mux.NewGroup("/prefix") to create a group.
func (*Group) Handle ¶
Handle regiester a standard http.Handler request handler with the given path and method. With this adapter, your handler won't have access to the context and thus won't work with URL parameters.
func (*Group) HandleC ¶
HandleC registers a context aware request handler 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 (*Group) HandleFunc ¶
func (g *Group) HandleFunc(method, path string, handler http.HandlerFunc)
HandleFunc registers a standard http.HandlerFunc request handler with the given path and method. With this adapter, your handler won't have access to the context and thus won't work with URL parameters.
func (*Group) HandleFuncC ¶
func (g *Group) HandleFuncC(method, path string, handler xhandler.HandlerFuncC)
HandleFuncC registers a standard xhandler.HandlerFuncC request handler with the given path and method.
func (*Group) NewGroup ¶
NewGroup creates a new sub routes group with the provided path prefix. All routes added to the returned group will have the path prepended.
type Mux ¶
type Mux struct { // 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 // Configurable http.Handler which is called when no matching route is // found. If it is not set, http.Error with http.StatusNotFound is used. NotFound xhandler.HandlerC // 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. MethodNotAllowed xhandler.HandlerC // 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(context.Context, http.ResponseWriter, *http.Request, interface{}) // contains filtered or unexported fields }
Mux is a xhandler.HandlerC which can be used to dispatch requests to different handler functions via configurable routes
Example ¶
package main import ( "fmt" "log" "net/http" "time" "context" "github.com/rs/xhandler" "github.com/rs/xmux" ) func main() { c := xhandler.Chain{} // Append a context-aware middleware handler c.UseC(xhandler.CloseHandler) // Another context-aware middleware handler c.UseC(xhandler.TimeoutHandler(2 * time.Second)) mux := xmux.New() // Use c.Handler to terminate the chain with your final handler mux.GET("/welcome/:name", xhandler.HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, req *http.Request) { fmt.Fprintf(w, "Welcome %s!", xmux.Param(ctx, "name")) })) if err := http.ListenAndServe(":8080", c.Handler(mux)); err != nil { log.Fatal(err) } }
Output:
func (*Mux) Handle ¶
Handle regiester a standard http.Handler request handler with the given path and method. With this adapter, your handler won't have access to the context and thus won't work with URL parameters.
func (*Mux) HandleC ¶
HandleC registers a net/context aware request handler 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 (*Mux) HandleFunc ¶
func (mux *Mux) HandleFunc(method, path string, handler http.HandlerFunc)
HandleFunc regiester a standard http.HandlerFunc request handler with the given path and method. With this adapter, your handler won't have access to the context and thus won't work with URL parameters.
func (*Mux) HandleFuncC ¶
func (mux *Mux) HandleFuncC(method, path string, handler xhandler.HandlerFuncC)
HandleFuncC registers a standard xhandler.HandlerFuncC request handler with the given path and method.
func (*Mux) Lookup ¶
Lookup allows the manual lookup of a method + path combo. This is e.g. useful to build a framework around this router. If the path was found, it returns the handle function and the path parameter values. Otherwise the third return value indicates whether a redirection to the same path with an extra / without the trailing slash should be performed.
func (*Mux) NewGroup ¶
NewGroup creates a new routes group with the provided path prefix. All routes added to the returned group will have the path prepended.
Example ¶
package main import ( "fmt" "log" "net/http" "context" "github.com/rs/xhandler" "github.com/rs/xmux" ) func main() { mux := xmux.New() api := mux.NewGroup("/api") api.GET("/users/:name", xhandler.HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "GET /api/users/%s", xmux.Param(ctx, "name")) })) api.POST("/users/:name", xhandler.HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "POST /api/users/%s", xmux.Param(ctx, "name")) })) if err := http.ListenAndServe(":8080", xhandler.New(context.Background(), mux)); err != nil { log.Fatal(err) } }
Output:
func (*Mux) ServeHTTPC ¶
ServeHTTPC implements xhandler.HandlerC interface
type ParamHolder ¶
type ParamHolder []Parameter
ParamHolder holds URL parameters.
func Params ¶
func Params(ctx context.Context) ParamHolder
Params returns URL parameters stored in context
func (ParamHolder) Get ¶
func (ps ParamHolder) Get(name string) string
Get returns the value of the first Param which key matches the given name. If no matching Param is found, an empty string is returned.