mux: code.soquee.net/mux Index | Examples | Files

package mux

import "code.soquee.net/mux"

Package mux is a fast and safe HTTP request multiplexer.

The multiplexer in this package is capable of routing based on request method and a fixed rooted path (/favicon.ico) or subtree (/images/) which may include typed path parameters and wildcards (see "URL Parameters").

m := mux.New(
	mux.HandleFunc(http.MethodGet, "/profile/{username string}", http.NotFoundHandler())
	mux.HandleFunc(http.MethodGet, "/profile", http.RedirectHandler("/profile/me", http.StatusPermanentRedirect))
	mux.HandleFunc(http.MethodPost, "/logout", logoutHandler())
)

URL Parameters

Routes registered on the multiplexer may contain variable path parameters that comprise an optional name, followed by a type.

/user/{id int}/edit

Valid types include:

int    eg. -1, 1 (int64 in Go)
uint   eg. 0, 1 (uint64 in Go)
float  eg. 1, 1.123, -1.123 (float64 in Go)
string eg. anything ({string} is the same as {})
path   eg. files/123.png (must be the last path component)

All numeric types are 64 bits wide. Parameters of type "path" match the remainder of the input path and therefore may only appear as the final component of a route:

/file/{p path}

To retrieve the value of named path parameters see the Param function and the examples.

Two paths with different typed variable parameters (including static routes) in the same position are not allowed. Attempting to register any two of the following routes will panic:

/user/{a int}/new
/user/{b int}/edit
/user/{float}/edit
/user/{b string}/edit
/user/me

Code:

m := mux.New(
    mux.HandleFunc("GET", "/profile/{username string}/personal", func(w http.ResponseWriter, r *http.Request) {
        username, _ := mux.Param(r, "username")
        // You probably want to use the Username Case Mapped profile from the
        // golang.org/x/text/secure/precis package instead of lowercasing.
        normalized := strings.ToLower(username.Raw)

        // If the username had any capital letters, redirect to the canonical
        // username.
        if normalized != username.Raw {
            newPath := r.URL.Path[:username.Offset] + normalized + r.URL.Path[username.Offset+uint(len(username.Raw)):]
            http.Redirect(w, r, newPath, http.StatusPermanentRedirect)
            return
        }

        // Show the users profile.
        fmt.Fprintf(w, "Profile for the user %q", username.Raw)
    }),
)

server := httptest.NewServer(m)
resp, err := http.Get(server.URL + "/profile/Me/personal")
if err != nil {
    panic(err)
}
defer resp.Body.Close()

io.Copy(os.Stdout, resp.Body)

Output:

Profile for the user "me"

Code:

m := mux.New(
    mux.HandleFunc("GET", "/sha256/{wildcard path}", func(w http.ResponseWriter, r *http.Request) {
        val, _ := mux.Param(r, "wildcard")
        sum := sha256.Sum256([]byte(val.Raw))
        fmt.Fprintf(w, "the hash of %q is %x", val.Raw, sum)
    }),
)

server := httptest.NewServer(m)
resp, err := http.Get(server.URL + "/sha256/a/b")
if err != nil {
    panic(err)
}
defer resp.Body.Close()

io.Copy(os.Stdout, resp.Body)

Output:

the hash of "a/b" is c14cddc033f64b9dea80ea675cf280a015e672516090a5626781153dc68fea11

Index

Examples

Package Files

handlers.go mux.go node.go options.go params.go

type Option Uses

type Option func(*ServeMux)

Option is used to configure a ServeMux.

func Handle Uses

func Handle(method, r string, h http.Handler) Option

Handle registers the handler for the given pattern. If a handler already exists for pattern, Handle panics.

func HandleFunc Uses

func HandleFunc(method, r string, h http.HandlerFunc) Option

HandleFunc registers the handler for the given pattern. If a handler already exists for pattern, Handle panics.

func MethodNotAllowed Uses

func MethodNotAllowed(h http.Handler) Option

MethodNotAllowed sets the default handler to call when a path is matched to a route, but there is no handler registered for the specific method.

By default, http.Error with http.StatusMethodNotAllowed is used.

func NotFound Uses

func NotFound(h http.Handler) Option

NotFound sets the handler to use when a request does not have a registered route.

If the provided handler does not set the status code, it is set to 404 (Page Not Found) by default instead of 200. If the provided handler explicitly sets the status by calling "http.ResponseWriter".WriteHeader, that status code is used instead.

func Options Uses

func Options(f func([]string) http.Handler) Option

Options changes the ServeMux's default OPTIONS request handling behavior. If you do not want options handling by default, set f to "nil".

Registering handlers for OPTIONS requests on a specific path always overrides the default handler.

type ParamInfo Uses

type ParamInfo struct {
    // The parsed value of the parameter (for example int64(10))
    Value interface{}
    // The raw value of the parameter (for example "10")
    Raw string
    // The name of the route component that the parameter was matched against (for
    // example "name" in "{name int}")
    Name string
    // Type type of the route component that the parameter was matched against
    // (for example "int" in "{name int}")
    Type string
    // The offset in the path where this parameter was found (for example if "10"
    // is parsed out of the path "/10" the offset is 1)
    Offset uint
}

ParamInfo represents a route parameter and related metadata.

func Param Uses

func Param(r *http.Request, name string) (pinfo ParamInfo, ok bool)

Param returns the named route parameter from the requests context.

type ServeMux Uses

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

ServeMux is an HTTP request multiplexer. It matches the URL of each incoming request against a list of registered patterns and calls the handler for the pattern that most closely matches the URL.

func New Uses

func New(opts ...Option) *ServeMux

New allocates and returns a new ServeMux.

func (*ServeMux) Handler Uses

func (mux *ServeMux) Handler(r *http.Request) (http.Handler, *http.Request)

Handler returns the handler to use for the given request, consulting r.URL.Path. It always returns a non-nil handler.

The path used is unchanged for CONNECT requests.

If there is no registered handler that applies to the request, Handler returns a “page not found” handler and an empty pattern. The new request uses a context that contains any route parameters that were matched against the request path.

func (*ServeMux) ServeHTTP Uses

func (mux *ServeMux) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP dispatches the request to the handler whose pattern most closely matches the request URL.

Package mux imports 6 packages (graph). Updated 2019-11-06. Refresh now. Tools for package owners.