mux

package module
v1.2.4 Latest Latest
Warning

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

Go to latest
Published: Sep 29, 2019 License: MIT Imports: 6 Imported by: 0

README

danikarik/mux

Is a small wrapper around gorilla/mux with few additions:

  • r.HandleFunc accepts custom HandlerFunc or you can use http.HandlerFunc using r.HandleFuncBypass
  • r.Use accepts custom MiddlewareFunc or you can use func(http.Handler) http.Handler using r.UseBypass
  • NewRouter() accepts Options

HandlerFunc

type HandlerFunc func(w http.ResponseWriter, r *http.Request) error

Example:

func userHandler(w http.ResponseWriter, r *http.Request) error {
    id := mux.Vars(r)["id"]
    user, err := loadUser(id)
    if err != nil {
        return err
    }
    return sendJSON(w, http.StatusOK, user)
}

r := mux.NewRouter()
r.HandleFunc("/", userHandler)

MiddlewareFunc

type MiddlewareFunc func(w http.ResponseWriter, r *http.Request) (context.Context, error)

Example:

func authMiddleware(w http.ResponseWriter, r *http.Request) (context.Context, error) {
    sess, err := store.Session(r)
    if err != nil {
        return nil, httpError(http.StatusUnauthorized, "Unauthorized")
    }
    id, err := sess.Value(userIDKey)
    if err != nil {
        return nil, httpError(http.StatusUnauthorized, "Unauthorized")
    }
    return context.WithValue(r.Context(), userIDContextKey, id)
}

r := mux.NewRouter()
r.Use(authMiddleware)
r.HandleFunc("/me", meHandler)

Options

With custom error handler:

func withCustomErrorHandler(r *mux.Router) {
    r.ErrorHandlerFunc = func(err error, w http.ResponseWriter, r *http.Request) {
        switch e := err.(type) {
        case *HTTPError:
            sendJSON(w, e.Code, e)
            break
        case *database.Error:
            http.Error(w, e.Message, http.StatusInternalServerError)
        default:
            http.Error(w, err.Error(), http.StatusInternalServerError)
            break
        }
    }
}

r := mux.NewRouter(withCustomErrorHandler)

With custom not found handler:

func withNotFound(r *mux.Router) {
    r.NotFoundHandler = func(w http.ResponseWriter, r *http.Request) error {
        // some stuff...
        http.Error(w, "Not Found", http.StatusNotFound)
        return nil
    }
}

r := mux.NewRouter(withNotFound)

With custom method not allowed handler:

func withMethodNotAllowed(r *mux.Router) {
    r.MethodNotAllowedHandler = func(w http.ResponseWriter, r *http.Request) error {
        // some stuff...
        http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
        return nil
    }
}

r := mux.NewRouter(withMethodNotAllowed)

Documentation

Overview

Package mux wraps gorilla/mux router with custom HandlerFunc and MiddlewareFunc.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Vars

func Vars(r *http.Request) map[string]string

Vars returns the route variables for the current request, if any.

Types

type ErrorHandlerFunc

type ErrorHandlerFunc func(err error, w http.ResponseWriter, r *http.Request)

ErrorHandlerFunc handles error returned by `Handler`.

type HTTPError added in v1.2.0

type HTTPError struct {
	Code            int
	Message         string
	InternalError   error
	InternalMessage string
	ErrorID         string
	ShowError       bool
}

HTTPError holds http error info.

Example
package main

import (
	"encoding/json"
	"errors"
	"fmt"
	"net/http"

	"github.com/danikarik/mux"
)

func main() {
	err := mux.NewHTTPError(http.StatusBadRequest, "Bad Request")
	data, _ := json.Marshal(err)
	fmt.Println(string(data))

	opts := []func(e *mux.HTTPError){
		func(e *mux.HTTPError) { e.ShowError = true },
		func(e *mux.HTTPError) { e.InternalError = errors.New("Unexpected Error") },
		func(e *mux.HTTPError) { e.InternalMessage = "Failed" },
		func(e *mux.HTTPError) { e.ErrorID = "123" },
	}
	err = mux.NewHTTPError(http.StatusInternalServerError, "Server Error", opts...)
	data, _ = json.Marshal(err)
	fmt.Println(string(data))

	err = mux.NewHTTPError(http.StatusUnauthorized, "Unauthorized").
		WithInternalMessage("Failed").
		WithErrorID("456").
		WithShowError(true)
	data, _ = json.Marshal(err)
	fmt.Println(string(data))

}
Output:

{"code":400,"message":"Bad Request"}
{"code":500,"message":"Server Error","internalError":"Unexpected Error","internalMessage":"Failed","id":"123"}
{"code":401,"message":"Unauthorized","internalMessage":"Failed","id":"456"}

func NewHTTPError added in v1.2.0

func NewHTTPError(code int, message string, opts ...func(e *HTTPError)) *HTTPError

NewHTTPError returns a new instance of `HTTPError`.

func (*HTTPError) Error added in v1.2.1

func (e *HTTPError) Error() string

Error implements error interface.

func (*HTTPError) MarshalJSON added in v1.2.0

func (e *HTTPError) MarshalJSON() ([]byte, error)

MarshalJSON implemenets `json.Marshal`.

func (*HTTPError) UnmarshalJSON added in v1.2.0

func (e *HTTPError) UnmarshalJSON(b []byte) error

UnmarshalJSON implements `json.Unmarshal`.

func (*HTTPError) WithErrorID added in v1.2.0

func (e *HTTPError) WithErrorID(id string) *HTTPError

WithErrorID updates `ErrorID` field.

func (*HTTPError) WithInternalError added in v1.2.0

func (e *HTTPError) WithInternalError(err error) *HTTPError

WithInternalError updates `InternalError` field.

func (*HTTPError) WithInternalMessage added in v1.2.0

func (e *HTTPError) WithInternalMessage(message string) *HTTPError

WithInternalMessage updates `InternalMessage` field.

func (*HTTPError) WithShowError added in v1.2.0

func (e *HTTPError) WithShowError(flag bool) *HTTPError

WithShowError updates `ShowError` field.

type HandlerFunc

type HandlerFunc func(w http.ResponseWriter, r *http.Request) error

HandlerFunc wraps standard `http.HandlerFunc` with `error` return value.

type MiddlewareFunc

type MiddlewareFunc func(w http.ResponseWriter, r *http.Request) (context.Context, error)

MiddlewareFunc wraps standard `http.Handler` middleware style with context and error.

type Route added in v1.1.0

type Route struct {
	Wrapper Wrapper
	// contains filtered or unexported fields
}

Route stores information to match a request and build URLs.

func CurrentRoute

func CurrentRoute(r *http.Request) *Route

CurrentRoute returns the matched route for the current request, if any.

func NewRoute added in v1.1.0

func NewRoute(r *gorillamux.Route, opts ...func(*Route)) *Route

NewRoute returns a new route instance.

func (*Route) BuildOnly added in v1.1.0

func (r *Route) BuildOnly() *Route

BuildOnly sets the route to never match: it is only used to build URLs.

func (*Route) BuildVarsFunc added in v1.1.0

func (r *Route) BuildVarsFunc(f gorillamux.BuildVarsFunc) *Route

BuildVarsFunc adds a custom function to be used to modify build variables before a route's URL is built.

func (*Route) GetError added in v1.1.0

func (r *Route) GetError() error

GetError returns an error resulted from building the route, if any.

func (*Route) GetHandler added in v1.1.0

func (r *Route) GetHandler() http.Handler

GetHandler returns the handler for the route, if any.

func (*Route) GetHostTemplate added in v1.1.0

func (r *Route) GetHostTemplate() (string, error)

GetHostTemplate returns the template used to build the route match.

func (*Route) GetMethods added in v1.1.0

func (r *Route) GetMethods() ([]string, error)

GetMethods returns the methods the route matches against.

func (*Route) GetName added in v1.1.0

func (r *Route) GetName() string

GetName returns the name for the route, if any.

func (*Route) GetPathRegexp added in v1.1.0

func (r *Route) GetPathRegexp() (string, error)

GetPathRegexp returns the expanded regular expression used to match route path.

func (*Route) GetPathTemplate added in v1.1.0

func (r *Route) GetPathTemplate() (string, error)

GetPathTemplate returns the template used to build the route match.

func (*Route) GetQueriesRegexp added in v1.1.0

func (r *Route) GetQueriesRegexp() ([]string, error)

GetQueriesRegexp returns the expanded regular expressions used to match the route queries.

func (*Route) GetQueriesTemplates added in v1.1.0

func (r *Route) GetQueriesTemplates() ([]string, error)

GetQueriesTemplates returns the templates used to build the query matching.

func (*Route) Handler added in v1.1.0

func (r *Route) Handler(h http.Handler) *Route

Handler sets a handler for the route.

func (*Route) HandlerFunc added in v1.1.0

func (r *Route) HandlerFunc(fn HandlerFunc) *Route

HandlerFunc sets a handler function for the route.

func (*Route) HandlerFuncBypass added in v1.1.0

func (r *Route) HandlerFuncBypass(fn func(http.ResponseWriter, *http.Request)) *Route

HandlerFuncBypass sets a handler function for the route.

func (*Route) Headers added in v1.1.0

func (r *Route) Headers(pairs ...string) *Route

Headers adds a matcher for request header values.

func (*Route) HeadersRegexp added in v1.1.0

func (r *Route) HeadersRegexp(pairs ...string) *Route

HeadersRegexp accepts a sequence of key/value pairs, where the value has regex support.

func (*Route) Host added in v1.1.0

func (r *Route) Host(tpl string) *Route

Host adds a matcher for the URL host.

func (*Route) Match added in v1.1.0

func (r *Route) Match(req *http.Request, match *gorillamux.RouteMatch) bool

Match matches the route against the request.

func (*Route) MatcherFunc added in v1.1.0

func (r *Route) MatcherFunc(f gorillamux.MatcherFunc) *Route

MatcherFunc adds a custom function to be used as request matcher.

func (*Route) Methods added in v1.1.0

func (r *Route) Methods(methods ...string) *Route

Methods adds a matcher for HTTP methods.

func (*Route) Name added in v1.1.0

func (r *Route) Name(name string) *Route

Name sets the name for the route, used to build URLs. It is an error to call Name more than once on a route.

func (*Route) Path added in v1.1.0

func (r *Route) Path(tpl string) *Route

Path adds a matcher for the URL path.

func (*Route) PathPrefix added in v1.1.0

func (r *Route) PathPrefix(tpl string) *Route

PathPrefix adds a matcher for the URL path prefix. This matches if the given template is a prefix of the full URL path. See Route.Path() for details on the tpl argument.

func (*Route) Queries added in v1.1.0

func (r *Route) Queries(pairs ...string) *Route

Queries adds a matcher for URL query values.

func (*Route) Schemes added in v1.1.0

func (r *Route) Schemes(schemes ...string) *Route

Schemes adds a matcher for URL schemes.

func (*Route) SkipClean added in v1.1.0

func (r *Route) SkipClean() bool

SkipClean reports whether path cleaning is enabled for this route via Router.SkipClean.

func (*Route) Subrouter added in v1.1.0

func (r *Route) Subrouter() *Router

Subrouter creates a subrouter for the route.

func (*Route) URL added in v1.1.0

func (r *Route) URL(pairs ...string) (*url.URL, error)

URL builds a URL for the route.

func (*Route) URLHost added in v1.1.0

func (r *Route) URLHost(pairs ...string) (*url.URL, error)

URLHost builds the host part of the URL for a route. See Route.URL().

func (*Route) URLPath added in v1.1.0

func (r *Route) URLPath(pairs ...string) (*url.URL, error)

URLPath builds the path part of the URL for a route. See Route.URL().

type Router

type Router struct {
	Wrapper                 Wrapper
	NotFoundHandler         HandlerFunc
	MethodNotAllowedHandler HandlerFunc
	// contains filtered or unexported fields
}

Router wraps `github.com/gorilla/mux` with custom `mux.Handler`.

func NewRouter

func NewRouter(opts ...func(*Router)) *Router

NewRouter returns a new router instance.

func NewRouterWithMux added in v1.1.0

func NewRouterWithMux(mux *gorillamux.Router, opts ...func(*Router)) *Router

NewRouterWithMux returns a new router instance with input mux.

func (*Router) BuildVarsFunc

func (r *Router) BuildVarsFunc(f gorillamux.BuildVarsFunc) *Route

BuildVarsFunc registers a new route with a custom function for modifying route variables before building a URL.

func (*Router) Get

func (r *Router) Get(name string) *Route

Get returns a route registered with the given name.

func (*Router) Handle

func (r *Router) Handle(path string, h http.Handler) *Route

Handle registers a new route with a matcher for the URL path. See Route.Path() and Route.Handler().

func (*Router) HandleFunc

func (r *Router) HandleFunc(path string, fn HandlerFunc) *Route

HandleFunc registers a new route with a matcher for the URL path. See Route.Path() and Route.HandlerFunc().

func (*Router) HandleFuncBypass

func (r *Router) HandleFuncBypass(path string, fn http.HandlerFunc) *Route

HandleFuncBypass registers a new route with a matcher for the URL path. See Route.Path() and Route.HandlerFunc().

func (*Router) Headers

func (r *Router) Headers(pairs ...string) *Route

Headers registers a new route with a matcher for request header values. See Route.Headers().

func (*Router) Host

func (r *Router) Host(tpl string) *Route

Host registers a new route with a matcher for the URL host. See Route.Host().

func (*Router) MatcherFunc

func (r *Router) MatcherFunc(f gorillamux.MatcherFunc) *Route

MatcherFunc registers a new route with a custom matcher function. See Route.MatcherFunc().

func (*Router) Methods

func (r *Router) Methods(methods ...string) *Route

Methods registers a new route with a matcher for HTTP methods. See Route.Methods().

func (*Router) Name

func (r *Router) Name(name string) *Route

Name registers a new route with a name. See Route.Name().

func (*Router) NewRoute

func (r *Router) NewRoute() *Route

NewRoute registers an empty route.

func (*Router) Path

func (r *Router) Path(tpl string) *Route

Path registers a new route with a matcher for the URL path. See Route.Path().

func (*Router) PathPrefix

func (r *Router) PathPrefix(tpl string) *Route

PathPrefix registers a new route with a matcher for the URL path prefix. See Route.PathPrefix().

func (*Router) Queries

func (r *Router) Queries(pairs ...string) *Route

Queries registers a new route with a matcher for URL query values. See Route.Queries().

func (*Router) Schemes

func (r *Router) Schemes(schemes ...string) *Route

Schemes registers a new route with a matcher for URL schemes. See Route.Schemes().

func (*Router) ServeHTTP

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

ServeHTTP dispatches the handler registered in the matched route.

func (*Router) SkipClean

func (r *Router) SkipClean(value bool) *Router

SkipClean defines the path cleaning behaviour for new routes. The initial value is false.

func (*Router) StrictSlash

func (r *Router) StrictSlash(value bool) *Router

StrictSlash defines the trailing slash behavior for new routes. The initial value is false.

func (*Router) Use

func (r *Router) Use(mwf ...MiddlewareFunc)

Use appends a MiddlewareFunc to the chain.

func (*Router) UseBypass

func (r *Router) UseBypass(mwf ...gorillamux.MiddlewareFunc)

UseBypass appends a gorilla's `mux.MiddlewareFunc` to the chain.

func (*Router) UseEncodedPath

func (r *Router) UseEncodedPath() *Router

UseEncodedPath tells the router to match the encoded original path to the routes.

func (*Router) Walk

func (r *Router) Walk(walkFn gorillamux.WalkFunc) error

Walk walks the router and all its sub-routers, calling walkFn for each route in the tree. The routes are walked in the order they were added. Sub-routers are explored depth-first.

type Wrapper added in v1.1.0

type Wrapper interface {
	ServeHandler(HandlerFunc) func(http.ResponseWriter, *http.Request)
	HandlerFunc(HandlerFunc) http.HandlerFunc
	ServeMiddleware(MiddlewareFunc) func(http.Handler) http.Handler
	MiddlewareFunc(MiddlewareFunc) func(http.Handler) http.Handler
	HandleError(error, http.ResponseWriter, *http.Request)
}

Wrapper defines route wrapping methods and error handling for `Router` and `Route`.

func NewDefaultWrapper added in v1.1.0

func NewDefaultWrapper(fn ErrorHandlerFunc) Wrapper

NewDefaultWrapper returns a new default wrapper.

Jump to

Keyboard shortcuts

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