handlers: github.com/kevinburke/handlers Index | Examples | Files

package handlers

import "github.com/kevinburke/handlers"

Package handlers implements a number of useful HTTP middlewares.

The general format of the middlewares in this package is to wrap an existing http.Handler in another one. So if you have a ServeMux, you can simply do:

mux := http.NewServeMux()
h := handlers.Log(handlers.Debug(mux))
http.ListenAndServe(":5050", h)

And wrap as many handlers as you'd like using that idiom.

Code:

mux := http.NewServeMux()
h := handlers.Duration(handlers.Server(mux, "custom-server"))
req := httptest.NewRequest("GET", "/", nil)
w := httptest.NewRecorder()
h.ServeHTTP(w, req)
fmt.Println(w.Header().Get("Server"))

Output:

custom-server

Index

Examples

Package Files

ctx.go gzip.go lib.go logger.go regex_handler.go

Constants

const Version = "0.39"

Variables

var Logger log15.Logger

Logger is a logger configured to avoid the 40-char spacing gap between the message and the first key, and to write timestamps with full nanosecond precision.

func All Uses

func All(h http.Handler, serverName string) http.Handler

All wraps h with every handler in this file.

func BasicAuth Uses

func BasicAuth(h http.Handler, realm string, users map[string]string) http.Handler

BasicAuth protects all requests to the given handler, unless the request has basic auth with a username and password in the users map.

func Debug Uses

func Debug(h http.Handler) http.Handler

Debug prints debugging information about the request to stdout if the DEBUG_HTTP_TRAFFIC environment variable is set to true.

func Duration Uses

func Duration(h http.Handler) http.Handler

Duration sets the start time in the context and sets a X-Request-Duration header on the response, from the time this handler started executing to the time of the first WriteHeader() or Write() call.

func GZip Uses

func GZip(h http.Handler) http.Handler

GZip gzip compresses HTTP responses for clients that support it via the 'Accept-Encoding' header.

Compressing TLS traffic may leak the page contents to an attacker if the page contains user input, known as the CRIME/BEAST attacks: http://security.stackexchange.com/a/102015/12208. Only use the GZip handler with unencrypted traffic, static pages, or pages that only contain public data.

func GetDuration Uses

func GetDuration(ctx context.Context) time.Duration

GetDuration returns the amount of time since the Duration handler ran, or 0 if no Duration was set for this context.

func GetRequestID Uses

func GetRequestID(ctx context.Context) (uuid.UUID, bool)

GetRequestID returns a UUID (if it exists in the context) or false if none could be found.

func GetStartTime Uses

func GetStartTime(ctx context.Context) time.Time

GetStartTime returns the time the Duration handler ran.

func JSON Uses

func JSON(h http.Handler) http.Handler

JSON sets the Content-Type to application/json; charset=utf-8.

func Log Uses

func Log(h http.Handler) http.Handler

Log serves the http request and writes information about the request/response using the default Logger (handlers.Logger). Any errors writing to the Logger are ignored.

func NewLogger Uses

func NewLogger() log15.Logger

NewLogger returns a new customizable Logger, with the same initial settings as the package Logger. Compared with a default log15.Logger, the 40-char spacing gap between the message and the first key is omitted, and timestamps are written with more precision.

func NewLoggerLevel Uses

func NewLoggerLevel(lvl log15.Lvl) log15.Logger

NewLoggerLevel returns a Logger with our customized settings, set to log messages at or more critical than the given level.

func RedirectProto Uses

func RedirectProto(h http.Handler) http.Handler

RedirectProto redirects requests with an "X-Forwarded-Proto: http" header to their HTTPS equivalent.

func STS Uses

func STS(h http.Handler) http.Handler

STS sets a Strict-Transport-Security header on the response.

func Server Uses

func Server(h http.Handler, serverName string) http.Handler

Server attaches a Server header to the response.

func SetRequestID Uses

func SetRequestID(r *http.Request, u uuid.UUID) *http.Request

SetRequestID sets the given UUID on the request context and returns the modified HTTP request.

func TrailingSlashRedirect Uses

func TrailingSlashRedirect(h http.Handler) http.Handler

TrailingSlashRedirect redirects any path that ends with a "/" - say, "/messages/" - to the stripped version, say "/messages".

func UUID Uses

func UUID(h http.Handler) http.Handler

UUID attaches a X-Request-Id header to the request, and sets one on the request context, unless one already exists.

func WithLogger Uses

func WithLogger(h http.Handler, logger log.Logger) http.Handler

WithLogger logs information about HTTP requests and responses to the provided Logger, including a detailed timestamp, the user agent, the response time, the number of bytes written, and more. Any errors writing log information to the Logger are ignored.

func WithTimeout Uses

func WithTimeout(h http.Handler, timeout time.Duration) http.Handler

WithTimeout sets the given timeout in the Context of every incoming request before passing it to the next handler.

WithTimeout is only available for Go 1.7 and above.

type Regexp Uses

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

A RegexpHandler is a simple http.Handler that can match regular expressions for routes.

Code:

// GET /v1/jobs/:job-name
route := regexp.MustCompile(`^/v1/jobs/(?P<JobName>[^\s\/]+)$`)

h := new(handlers.Regexp)
h.HandleFunc(route, []string{"GET", "POST"}, func(w http.ResponseWriter, r *http.Request) {
    io.WriteString(w, "Hello World!")
})

func (*Regexp) Handle Uses

func (h *Regexp) Handle(pattern *regexp.Regexp, methods []string, handler http.Handler)

Handle calls the provided handler for requests whose URL matches the given pattern and HTTP method. The first matching route will get called. If methods is nil, all HTTP methods will be allowed. If GET is in the list of methods, HEAD requests will also be allowed.

func (*Regexp) HandleFunc Uses

func (h *Regexp) HandleFunc(pattern *regexp.Regexp, methods []string, handler func(http.ResponseWriter, *http.Request))

HandleFunc calls the provided HandlerFunc for requests whose URL matches the given pattern and HTTP method. The first matching route will get called. If methods is nil, all HTTP methods are allowed. If GET is in the list of methods, HEAD requests will also be allowed.

func (*Regexp) ServeHTTP Uses

func (h *Regexp) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP checks all registered routes in turn for a match, and calls handler.ServeHTTP on the first matching handler. If no routes match, StatusMethodNotAllowed will be rendered.

Package handlers imports 22 packages (graph) and is imported by 8 packages. Updated 2018-04-17. Refresh now. Tools for package owners.