handlers
packagemoduleThis package is not in the latest version of its module.
Details
Validgo.mod file
The Go module system was introduced in Go 1.11 and is the official dependency management solution for Go.
Redistributable license
Redistributable licenses place minimal restrictions on how software can be used, modified, and redistributed.
Tagged version
Modules with tagged versions give importers more predictable builds.
Stable version
When a project reaches major version v1 it is considered stable.
- Learn more about best practices
Repository
Links
README¶
gorilla/handlers
Package handlers is a collection of handlers (aka "HTTP middleware") for usewith Go'snet/http package (or any framework supportinghttp.Handler), including:
- LoggingHandler for logging HTTP requests in the ApacheCommon LogFormat.
- CombinedLoggingHandler for logging HTTP requests in the ApacheCombined LogFormat commonly used byboth Apache and nginx.
- CompressHandler for gzipping responses.
- ContentTypeHandler for validating requests against a list of acceptedcontent types.
- MethodHandler for matching HTTP methods against handlers in a
map[string]http.Handler - ProxyHeaders for populating
r.RemoteAddrandr.URL.Schemebased on theX-Forwarded-For,X-Real-IP,X-Forwarded-Protoand RFC7239Forwardedheaders when running a Go server behind a HTTP reverse proxy. - CanonicalHost for re-directing to the preferred host when handling multipledomains (i.e. multiple CNAME aliases).
- RecoveryHandler for recovering from unexpected panics.
Other handlers are documentedon the Gorillawebsite.
Example
A simple example usinghandlers.LoggingHandler andhandlers.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 usewith Go's net/http package (or any framework supporting http.Handler).
The package includes handlers for logging in standardised formats, compressingHTTP responses, validating content types and other useful tools for manipulatingrequests and responses.
Index¶
- Constants
- func CORS(opts ...CORSOption) func(http.Handler) http.Handler
- func CanonicalHost(domain string, code int) func(h http.Handler) http.Handler
- func CombinedLoggingHandler(out io.Writer, h http.Handler) http.Handler
- func CompressHandler(h http.Handler) http.Handler
- func CompressHandlerLevel(h http.Handler, level int) http.Handler
- func ContentTypeHandler(h http.Handler, contentTypes ...string) http.Handler
- func CustomLoggingHandler(out io.Writer, h http.Handler, f LogFormatter) http.Handler
- func HTTPMethodOverrideHandler(h http.Handler) http.Handler
- func LoggingHandler(out io.Writer, h http.Handler) http.Handler
- func ProxyHeaders(h http.Handler) http.Handler
- func RecoveryHandler(opts ...RecoveryOption) func(h http.Handler) http.Handler
- type CORSOption
- func AllowCredentials() CORSOption
- func AllowedHeaders(headers []string) CORSOption
- func AllowedMethods(methods []string) CORSOption
- func AllowedOriginValidator(fn OriginValidator) CORSOption
- func AllowedOrigins(origins []string) CORSOption
- func ExposedHeaders(headers []string) CORSOption
- func IgnoreOptions() CORSOption
- func MaxAge(age int) CORSOption
- func OptionStatusCode(code int) CORSOption
- type LogFormatter
- type LogFormatterParams
- type MethodHandler
- type OriginValidator
- type RecoveryHandlerLogger
- type RecoveryOption
Constants¶
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¶
funcCORS¶
func CORS(opts ...CORSOption) func(http.Handler)http.Handler
CORS provides Cross-Origin Resource Sharing middleware.Example:
import ( "net/http" "github.com/gorilla/handlers" "github.com/gorilla/mux")func main() { r := mux.NewRouter() r.HandleFunc("/users", UserEndpoint) r.HandleFunc("/projects", ProjectEndpoint) // Apply the CORS middleware to our top-level router, with the defaults. http.ListenAndServe(":8000", handlers.CORS()(r))}funcCanonicalHost¶
CanonicalHost is HTTP middleware that re-directs requests to the canonicaldomain. It accepts a domain and a status code (e.g. 301 or 302) andre-directs clients to this domain. The existing request path is maintained.
Note: If the provided domain is considered invalid by url.Parse or otherwisereturns an empty scheme or host, clients are 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)))funcCombinedLoggingHandler¶
CombinedLoggingHandler return a http.Handler that wraps h and logs requests to out inApache Combined Log Format.
Seehttp://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 -.
funcCompressHandler¶
CompressHandler gzip compresses HTTP responses for clients that support itvia the 'Accept-Encoding' header.
Compressing TLS traffic may leak the page contents to an attacker if thepage contains user input:http://security.stackexchange.com/a/102015/12208
funcCompressHandlerLevel¶
CompressHandlerLevel gzip compresses HTTP responses with specified compression levelfor clients that support it via the 'Accept-Encoding' header.
The compression level should be gzip.DefaultCompression, gzip.NoCompression,or any integer value between gzip.BestSpeed and gzip.BestCompression inclusive.gzip.DefaultCompression is used in case of invalid compression level.
funcContentTypeHandler¶
ContentTypeHandler wraps and returns a http.Handler, validating the requestcontent type is compatible with the contentTypes list. It writes a HTTP 415error if that fails.
Only PUT, POST, and PATCH requests are considered.
funcCustomLoggingHandler¶added inv1.4.0
CustomLoggingHandler provides a way to supply a custom log formatterwhile taking advantage of the mechanisms in this package.
funcHTTPMethodOverrideHandler¶
HTTPMethodOverrideHandler wraps and returns a http.Handler which checks forthe X-HTTP-Method-Override header or the _method form key, and overrides (ifvalid) 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 areconsidered. Likewise, the override method can only be a "write" method: PUT,PATCH or DELETE.
Form method takes precedence over header method.
funcLoggingHandler¶
LoggingHandler return a http.Handler that wraps h and logs requests to out inApache Common Log Format (CLF).
Seehttp://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 -
Example:
r := mux.NewRouter()r.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {w.Write([]byte("This is a catch-all route"))})loggedRouter := handlers.LoggingHandler(os.Stdout, r)http.ListenAndServe(":1123", loggedRouter)funcProxyHeaders¶
ProxyHeaders inspects common reverse proxy headers and sets the correspondingfields in the HTTP request struct. These are X-Forwarded-For and X-Real-IPfor the remote (client) IP address, X-Forwarded-Proto or X-Forwarded-Schemefor the scheme (http|https), X-Forwarded-Host for the host and the RFC7239Forwarded header, which may include both client IPs and schemes.
NOTE: This middleware should only be used when behind a reverseproxy like nginx, HAProxy or Apache. Reverse proxies that don't (or areconfigured not to) strip these headers from client requests, or where theseheaders are accepted "as is" from a remote client (e.g. when Go is not behinda proxy), can manifest as a vulnerability if your application uses theseheaders for validating the 'trustworthiness' of a request.
funcRecoveryHandler¶
func RecoveryHandler(opts ...RecoveryOption) func(hhttp.Handler)http.Handler
RecoveryHandler is HTTP middleware that recovers from a panic,logs the panic, writes http.StatusInternalServerError, andcontinues to the next handler.
Example:
r := mux.NewRouter()r.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {panic("Unexpected error!")})http.ListenAndServe(":1123", handlers.RecoveryHandler()(r))Types¶
typeCORSOption¶
type CORSOption func(*cors)error
CORSOption represents a functional option for configuring the CORS middleware.
funcAllowCredentials¶
func AllowCredentials()CORSOption
AllowCredentials can be used to specify that the user agent may passauthentication details along with the request.
funcAllowedHeaders¶
func AllowedHeaders(headers []string)CORSOption
AllowedHeaders adds the provided headers to the list of allowed headers in aCORS request.This is an append operation so the headers Accept, Accept-Language,and Content-Language are always allowed.Content-Type must be explicitly declared if accepting Content-Types other thanapplication/x-www-form-urlencoded, multipart/form-data, or text/plain.
funcAllowedMethods¶
func AllowedMethods(methods []string)CORSOption
AllowedMethods can be used to explicitly allow methods in theAccess-Control-Allow-Methods header.This is a replacement operation so you must alsopass GET, HEAD, and POST if you wish to support those methods.
funcAllowedOriginValidator¶
func AllowedOriginValidator(fnOriginValidator)CORSOption
AllowedOriginValidator sets a function for evaluating allowed origins in CORS requests, represented by the'Allow-Access-Control-Origin' HTTP header.
funcAllowedOrigins¶
func AllowedOrigins(origins []string)CORSOption
AllowedOrigins sets the allowed origins for CORS requests, as used in the'Allow-Access-Control-Origin' HTTP header.Note: Passing in a []string{"*"} will allow any domain.
funcExposedHeaders¶
func ExposedHeaders(headers []string)CORSOption
ExposedHeaders can be used to specify headers that are availableand will not be stripped out by the user-agent.
funcIgnoreOptions¶
func IgnoreOptions()CORSOption
IgnoreOptions causes the CORS middleware to ignore OPTIONS requests, insteadpassing them through to the next handler. This is useful when your applicationor framework has a pre-existing mechanism for responding to OPTIONS requests.
funcMaxAge¶
func MaxAge(ageint)CORSOption
MaxAge determines the maximum age (in seconds) between preflight requests. Amaximum of 10 minutes is allowed. An age above this value will default to 10minutes.
funcOptionStatusCode¶added inv1.4.1
func OptionStatusCode(codeint)CORSOption
OptionStatusCode sets a custom status code on the OPTIONS requests.Default behaviour sets it to 200 to reflect best practices. This is option is not mandatoryand can be used if you need a custom status code (i.e 204).
More informations on the spec:https://fetch.spec.whatwg.org/#cors-preflight-fetch
typeLogFormatter¶added inv1.4.0
type LogFormatter func(writerio.Writer, paramsLogFormatterParams)
LogFormatter gives the signature of the formatter function passed to CustomLoggingHandler.
typeLogFormatterParams¶added inv1.4.0
type LogFormatterParams struct {Request *http.RequestURLurl.URLTimeStamptime.TimeStatusCodeintSizeint}LogFormatterParams is the structure any formatter will be handed when time to log comes.
typeMethodHandler¶
MethodHandler is an http.Handler that dispatches to a handler whose key in theMethodHandler'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 thenthe handler responds with a status of 200 and sets the Allow header to acomma-separated list of available methods.
If the request's method doesn't match any of its keys the handler respondswith a status of HTTP 405 "Method Not Allowed" and sets the Allow header to acomma-separated list of available methods.
func (MethodHandler)ServeHTTP¶
func (hMethodHandler) ServeHTTP(whttp.ResponseWriter, req *http.Request)
typeOriginValidator¶
OriginValidator takes an origin string and returns whether or not that origin is allowed.
typeRecoveryHandlerLogger¶
type RecoveryHandlerLogger interface {Println(...interface{})}RecoveryHandlerLogger is an interface used by the recovering handler to print logs.
typeRecoveryOption¶
RecoveryOption provides a functional approach to defineconfiguration for a handler; such as setting the loggingwhether or not to print stack traces on panic.
funcPrintRecoveryStack¶
func PrintRecoveryStack(shouldPrintbool)RecoveryOption
PrintRecoveryStack is a functional option to enableor disable printing stack traces on panic.
funcRecoveryLogger¶
func RecoveryLogger(loggerRecoveryHandlerLogger)RecoveryOption
RecoveryLogger is a functional option to overridethe default logger.