mux

package module
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Oct 22, 2018 License: MIT Imports: 5 Imported by: 0

README

mux (HTTP multiplexer for Go)

Build Status Sourcegraph GoDoc Minimal version

About

This package is a fast HTTP multiplexer.

It uses a radix tree to match URLs. When matching simple routes, it's a zero allocation search. It's fast, simple and supports middlewares in an elegant way.

Usage

Full documentation [here].

Installing
Go 1.10

vgo get -u github.com/gbrlsnchs/mux

Go 1.11 or after

go get -u github.com/gbrlsnchs/mux

Importing
import (
	// ...

	"github.com/gbrlsnchs/mux"
)
Setting a handler (or handler function)
First, set a context key
type key uint8

const ctxKey key = 0
Then, create a new router and set an endpoint handler
rt := mux.NewRouter("/api", ctxKey)
rt.HandleFunc(http.MethodGet, "/ping", func(w http.ResponseWriter, _ *http.Request) {
	w.WriteHeader(http.StatusOK)
	w.Write([]byte("pong"))
})
Setting a common middleware for every endpoint
First, define a middleware
func loggingFunc(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		log.Printf("%s %s", r.Method, r.URL.Path)
		next.ServeHTTP(w, r)
	})
}
Then, create a router and use the middleware in all requests
rt := mux.NewRouter("/api")
rt.Use(loggingFunc)
rt.Handle(http.MethodGet, "/ping", func(w http.ResponseWriter, _ *http.Request) {
	w.WriteHeader(http.StatusOK)
	w.Write([]byte("pong"))
})
Setting isolated middlewares
First, define a handler and some middlewares
func handler(w http.ResponseWriter, _ *http.Request) {
	w.WriteHeader(http.StatusOK)
})

func authFunc(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if mux.Params(r.Context(), ctxKey)["secret"] != "my_secret" {
			w.WriteHeader(http.StatusUnauthorized)
			return
		}
		next.ServeHTTP(w, r)
	})
}

func permissionFunc(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if !userIsAdmin(r) { // hypothetical function
			w.WriteHeader(http.StatusForbidden)
			return
		}
		next.ServeHTTP(w, r)
	})
}
Then, create a middleware chain and add it to the router
rt := mux.NewRouter("/", ctxKey)
guard := mux.NewChain(authFunc, permissionFunc)

rt.Handle(http.MethodPost, "/unprotected", handler)
rt.Handle(http.MethodPost, "/protected/:secret", guard(handler))

Contributing

How to help

Documentation

Overview

Package mux is an HTTP multiplexer that uses a radix tree as its backbone.

Example
package main

import (
	"net/http"

	"github.com/gbrlsnchs/mux"
)

func main() {
	type key uint8
	const ctxKey key = 0

	handler := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
		w.WriteHeader(http.StatusOK)
	})

	m := mux.NewRouter("/api", ctxKey)
	m.Handle(http.MethodGet, "/ping", handler)
}
Output:

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Params

func Params(ctx context.Context, ctxKey interface{}) map[string]string

Params is a helper to access URL parameters.

Types

type MiddlewareFunc

type MiddlewareFunc func(next http.Handler) http.Handler

MiddlewareFunc is a middleware adapter.

func NewChain added in v0.3.0

func NewChain(fns ...MiddlewareFunc) MiddlewareFunc

NewChain creates a middleware chain, which is a middleware itself.

Example
package main

import (
	"log"
	"net/http"

	"github.com/gbrlsnchs/mux"
)

func main() {
	type key uint8
	const ctxKey key = 0

	m := mux.NewRouter("/api", ctxKey)
	guard := mux.NewChain(
		func(next http.Handler) http.Handler {
			return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
				log.Printf("%s %s", r.Method, r.URL.Path)
				next.ServeHTTP(w, r)
			})
		},
		func(next http.Handler) http.Handler {
			return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
				if mux.Params(r.Context(), ctxKey)["secret"] != "my_secret" {
					w.WriteHeader(http.StatusUnauthorized)
					return
				}
				next.ServeHTTP(w, r)
			})
		},
	)

	handler := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
		w.WriteHeader(http.StatusOK)
	})

	m.Handle(http.MethodPost, "/unprotected", handler)
	m.Handle(http.MethodPost, "/protected/:secret", guard(handler))
}
Output:

type Router added in v0.2.0

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

Router is an HTTP multiplexer.

func NewRouter added in v0.3.0

func NewRouter(path string, ctxKey interface{}) *Router

NewRouter creates a new HTTP router.

func (*Router) Handle added in v0.2.0

func (rt *Router) Handle(method, path string, handler http.Handler)

Handle sets an HTTP request handler.

func (*Router) HandleFunc added in v0.3.0

func (rt *Router) HandleFunc(method, path string, handler http.HandlerFunc)

HandleFunc sets an HTTP request handler function.

func (*Router) Router added in v0.3.0

func (rt *Router) Router(path string) *Router

Router creates a subrouter.

func (*Router) ServeHTTP added in v0.3.0

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

ServeHTTP implements the http.Handler interface by finding an endpoint in the trie. If there are any parameters, they are set to the request's context.

func (*Router) SetDebug added in v0.3.0

func (rt *Router) SetDebug(debug bool)

SetDebug sets the debug flag.

func (*Router) SetPlaceholder added in v0.3.0

func (rt *Router) SetPlaceholder(c byte)

SetPlaceholder sets a different placeholder to be used in dynamic paths.

func (*Router) String added in v0.3.0

func (rt *Router) String() string

func (*Router) Use added in v0.3.0

func (rt *Router) Use(fns ...MiddlewareFunc)

Use set middleware functions to run before each request.

Jump to

Keyboard shortcuts

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