xmux: github.com/rs/xmux Index | Examples | Files

package xmux

import "github.com/rs/xmux"

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

Examples

Package Files

group.go mux.go path.go testing.go tree.go

func CleanPath Uses

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

func Param Uses

func Param(ctx context.Context, name string) string

Param picks one URL parameters stored in context by its name.

This is a shortcut for:

xmux.Params(ctx).Get("name")

func TestSetParamContext Uses

func TestSetParamContext(ctx context.Context, p ParamHolder) context.Context

TestSetParamContext sets ParamHolder to context.Context for testing

type Group Uses

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) DELETE Uses

func (g *Group) DELETE(path string, handler xhandler.HandlerC)

DELETE is a shortcut for g.Handle("DELETE", path, handler)

func (*Group) GET Uses

func (g *Group) GET(path string, handler xhandler.HandlerC)

GET is a shortcut for g.Handle("GET", path, handler)

func (*Group) HEAD Uses

func (g *Group) HEAD(path string, handler xhandler.HandlerC)

HEAD is a shortcut for g.Handle("HEAD", path, handler)

func (*Group) Handle Uses

func (g *Group) Handle(method, path string, handler http.Handler)

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 Uses

func (g *Group) HandleC(method, path string, handler xhandler.HandlerC)

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 Uses

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 Uses

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 Uses

func (g *Group) NewGroup(path string) *Group

NewGroup creates a new sub routes group with the provided path prefix. All routes added to the returned group will have the path prepended.

func (*Group) OPTIONS Uses

func (g *Group) OPTIONS(path string, handler xhandler.HandlerC)

OPTIONS is a shortcut for g.Handle("OPTIONS", path, handler)

func (*Group) PATCH Uses

func (g *Group) PATCH(path string, handler xhandler.HandlerC)

PATCH is a shortcut for g.Handle("PATCH", path, handler)

func (*Group) POST Uses

func (g *Group) POST(path string, handler xhandler.HandlerC)

POST is a shortcut for g.Handle("POST", path, handler)

func (*Group) PUT Uses

func (g *Group) PUT(path string, handler xhandler.HandlerC)

PUT is a shortcut for g.Handle("PUT", path, handler)

type Mux Uses

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

Code:

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)
}

func New Uses

func New() *Mux

New returns a new muxer instance

func (*Mux) DELETE Uses

func (mux *Mux) DELETE(path string, handler xhandler.HandlerC)

DELETE is a shortcut for mux.Handle("DELETE", path, handler)

func (*Mux) GET Uses

func (mux *Mux) GET(path string, handler xhandler.HandlerC)

GET is a shortcut for mux.Handle("GET", path, handler)

func (*Mux) HEAD Uses

func (mux *Mux) HEAD(path string, handler xhandler.HandlerC)

HEAD is a shortcut for mux.Handle("HEAD", path, handler)

func (*Mux) Handle Uses

func (mux *Mux) Handle(method, path string, handler http.Handler)

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 Uses

func (mux *Mux) HandleC(method, path string, handler xhandler.HandlerC)

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 Uses

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 Uses

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 Uses

func (mux *Mux) Lookup(method, path string) (xhandler.HandlerC, ParamHolder, bool)

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 Uses

func (mux *Mux) NewGroup(path string) *Group

NewGroup creates a new routes group with the provided path prefix. All routes added to the returned group will have the path prepended.

Code:

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)
}

func (*Mux) OPTIONS Uses

func (mux *Mux) OPTIONS(path string, handler xhandler.HandlerC)

OPTIONS is a shortcut for mux.Handle("OPTIONS", path, handler)

func (*Mux) PATCH Uses

func (mux *Mux) PATCH(path string, handler xhandler.HandlerC)

PATCH is a shortcut for mux.Handle("PATCH", path, handler)

func (*Mux) POST Uses

func (mux *Mux) POST(path string, handler xhandler.HandlerC)

POST is a shortcut for mux.Handle("POST", path, handler)

func (*Mux) PUT Uses

func (mux *Mux) PUT(path string, handler xhandler.HandlerC)

PUT is a shortcut for mux.Handle("PUT", path, handler)

func (*Mux) ServeHTTPC Uses

func (mux *Mux) ServeHTTPC(ctx context.Context, w http.ResponseWriter, r *http.Request)

ServeHTTPC implements xhandler.HandlerC interface

type ParamHolder Uses

type ParamHolder []Parameter

ParamHolder holds URL parameters.

func Params Uses

func Params(ctx context.Context) ParamHolder

Params returns URL parameters stored in context

func (ParamHolder) Get Uses

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.

type Parameter Uses

type Parameter struct {
    Name  string
    Value string
}

Parameter holds URL parameter.

Package xmux imports 6 packages (graph) and is imported by 10 packages. Updated 2017-06-10. Refresh now. Tools for package owners.