handlers

package
v0.2.2 Latest Latest
Warning

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

Go to latest
Published: Dec 29, 2015 License: BSD-2-Clause, Apache-2.0 Imports: 14 Imported by: 0

README

gorilla/handlers

GoDoc Build Status

Package handlers is a collection of handlers (aka "HTTP middleware") for use with Go's net/http package (or any framework supporting http.Handler), including:

  • LoggingHandler for logging HTTP requests in the Apache Common Log Format.
  • CombinedLoggingHandler for logging HTTP requests in the Apache Combined Log Format commonly used by both Apache and nginx.
  • CompressHandler for gzipping responses.
  • ContentTypeHandler for validating requests against a list of accepted content types.
  • MethodHandler for matching HTTP methods against handlers in a map[string]http.Handler
  • ProxyHeaders for populating r.RemoteAddr and r.URL.Scheme based on the X-Forwarded-For, X-Real-IP, X-Forwarded-Proto and RFC7239 Forwarded headers when running a Go server behind a HTTP reverse proxy.
  • CanonicalHost for re-directing to the preferred host when handling multiple domains (i.e. multiple CNAME aliases).

Other handlers are documented on the Gorilla website.

Example

A simple example using handlers.LoggingHandler and handlers.CompressHandler:

import (
    "net/http"
    "github.com/gorilla/handlers"
)

func main() {
    r := http.NewServeMux()

    // Only log requests to our admin dashboard to stdout
    r.Handle("/admin", handlers.LoggingHandler(os.Stdout, http.HandlerFunc(ShowAdminDashboard)))
    r.HandleFunc("/", ShowIndex)

    // Wrap our server with our gzip handler to gzip compress all responses.
    http.ListenAndServe(":8000", handlers.CompressHandler(r))
}

License

BSD licensed. See the included LICENSE file for details.

Documentation

Overview

Package handlers is a collection of handlers (aka "HTTP middleware") for use with Go's net/http package (or any framework supporting http.Handler).

The package includes handlers for logging in standardised formats, compressing HTTP responses, validating content types and other useful tools for manipulating requests and responses.

Index

Constants

View Source
const (
	// HTTPMethodOverrideHeader is a commonly used
	// http header to override a request method.
	HTTPMethodOverrideHeader = "X-HTTP-Method-Override"
	// HTTPMethodOverrideFormKey is a commonly used
	// HTML form key to override a request method.
	HTTPMethodOverrideFormKey = "_method"
)

Variables

This section is empty.

Functions

func CanonicalHost

func CanonicalHost(domain string, code int) func(h http.Handler) http.Handler

CanonicalHost is HTTP middleware that re-directs requests to the canonical domain. It accepts a domain and a status code (e.g. 301 or 302) and re-directs clients to this domain. The existing request path is maintained.

Note: If the provided domain is considered invalid by url.Parse or otherwise returns an empty scheme or host, clients are not re-directed. not re-directed.

Example:

r := mux.NewRouter()
canonical := handlers.CanonicalHost("http://www.gorillatoolkit.org", 302)
r.HandleFunc("/route", YourHandler)

log.Fatal(http.ListenAndServe(":7000", canonical(r)))

func CombinedLoggingHandler

func CombinedLoggingHandler(out io.Writer, h http.Handler) http.Handler

CombinedLoggingHandler return a http.Handler that wraps h and logs requests to out in Apache Combined Log Format.

See http://httpd.apache.org/docs/2.2/logs.html#combined for a description of this format.

LoggingHandler always sets the ident field of the log to -

func CompressHandler

func CompressHandler(h http.Handler) http.Handler

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

func ContentTypeHandler

func ContentTypeHandler(h http.Handler, contentTypes ...string) http.Handler

ContentTypeHandler wraps and returns a http.Handler, validating the request content type is acompatible with the contentTypes list. It writes a HTTP 415 error if that fails.

Only PUT, POST, and PATCH requests are considered.

func HTTPMethodOverrideHandler

func HTTPMethodOverrideHandler(h http.Handler) http.Handler

HTTPMethodOverrideHandler wraps and returns a http.Handler which checks for the X-HTTP-Method-Override header or the _method form key, and overrides (if valid) request.Method with its value.

This is especially useful for http clients that don't support many http verbs. It isn't secure to override e.g a GET to a POST, so only POST requests are considered. Likewise, the override method can only be a "write" method: PUT, PATCH or DELETE.

Form method takes precedence over header method.

func LoggingHandler

func LoggingHandler(out io.Writer, h http.Handler) http.Handler

LoggingHandler return a http.Handler that wraps h and logs requests to out in Apache Common Log Format (CLF).

See http://httpd.apache.org/docs/2.2/logs.html#common for a description of this format.

LoggingHandler always sets the ident field of the log to -

func ProxyHeaders

func ProxyHeaders(h http.Handler) http.Handler

ProxyHeaders inspects common reverse proxy headers and sets the corresponding fields in the HTTP request struct. These are X-Forwarded-For and X-Real-IP for the remote (client) IP address, X-Forwarded-Proto for the scheme (http|https) and the RFC7239 Forwarded header, which may include both client IPs and schemes.

NOTE: This middleware should only be used when behind a reverse proxy like nginx, HAProxy or Apache. Reverse proxies that don't (or are configured not to) strip these headers from client requests, or where these headers are accepted "as is" from a remote client (e.g. when Go is not behind a proxy), can manifest as a vulnerability if your application uses these headers for validating the 'trustworthiness' of a request.

Types

type MethodHandler

type MethodHandler map[string]http.Handler

MethodHandler is an http.Handler that dispatches to a handler whose key in the MethodHandler's map matches the name of the HTTP request's method, eg: GET

If the request's method is OPTIONS and OPTIONS is not a key in the map then the handler responds with a status of 200 and sets the Allow header to a comma-separated list of available methods.

If the request's method doesn't match any of its keys the handler responds with a status of 405, Method not allowed and sets the Allow header to a comma-separated list of available methods.

func (MethodHandler) ServeHTTP

func (h MethodHandler) ServeHTTP(w http.ResponseWriter, req *http.Request)

Jump to

Keyboard shortcuts

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