handlers

package module
v0.0.0-...-bda0c62 Latest Latest
Warning

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

Go to latest
Published: Sep 4, 2019 License: BSD-3-Clause Imports: 13 Imported by: 8

README

httphandlers

GoDoc Build Status Go Report Card Coverage Status

A collection of small utility http.Handler's for Golang.

Documentation

Overview

Package handlers is a collection of small utility http.Handler's for Golang.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Handler

type Handler = http.Handler

Handler is an alias to http.Handler for godoc.

func AccessLog

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

AccessLog wraps a http.Handler and logs all HTTP requests to an io.Writer that defaults to os.Stderr.

The log format is intended for human debugging and may not be stable.

func AddHeader

func AddHeader(h http.Handler, name, value string) Handler

AddHeader adds a header with a given value to the response.

func DeleteHeader

func DeleteHeader(h http.Handler, name string) Handler

DeleteHeader removes a header from the response.

func ErrorCode

func ErrorCode(code int) Handler

ErrorCode calls http.Error with the given HTTP status code. It uses http.StatusText for the message.

func ErrorMessage

func ErrorMessage(msg string, code int) Handler

ErrorMessage calls http.Error with the given HTTP status code and message.

func HostRedirect

func HostRedirect(host string, code int) Handler

HostRedirect returns a request handler that redirects each request it receives to the same url, but with a different host, using the given status code.

The provided code should be in the 3xx range and is usually http.StatusMovedPermanently.

func InternalRedirect

func InternalRedirect(h http.Handler, url string) Handler

InternalRedirect replaces the requests url with the given string. It is like http.Redirect but is handled internally.

func Must

func Must(h Handler, err error) Handler

Must is a helper that wraps a call to a function returning (Handler, error) and panics if the error is non-nil. It is intended for use in variable initializations such as

var h = handlers.Must(handlers.ServeTemplate("index.html", time.Now(), indexTmpl, indexData))

func NeverModified

func NeverModified(h http.Handler) Handler

NeverModified wraps a http.Handler and returns a 304 Not Modified HTTP status code to the browser for all If-Modified-Since conditional requests.

It is intended for resources that are guaranteed to never change, primarily content addressable resources.

See the article

'This browser tweak saved 60% of requests to Facebook'
 https://code.facebook.com/posts/557147474482256/

for an overview of how this method works.

func SNIHost

func SNIHost(h http.Handler) Handler

SNIHost sets (*http.Request).Host to the TLS SNI extension value if the request is TLS and the HTTP Host header was absent.

func SNIMatch

func SNIMatch(h http.Handler, mismatch http.Handler) Handler

SNIMatch verifies that the TLS SNI extension matches the HTTP Host header.

It does nothing for HTTP/2.0 to allow for connection coalescing.

mismatch is invoked on requests that contain a mismatch between the TLS SNI extension and the HTTP Host header.

If Mismatch is nil, a 400 Bad Request error will be returned instead.

func ServeBytes

func ServeBytes(name string, modtime time.Time, content []byte) Handler

ServeBytes returns a http.Handler that calls http.ServeContent with a bytes.Reader.

func ServeError

func ServeError(code int, content []byte, mimeType string) Handler

ServeError returns a http.Handler that serves content with a given HTTP status code.

If mimeType is empty, it will be sniffed from content.

func ServeErrorTemplate

func ServeErrorTemplate(code int, tmpl Template, data interface{}, mimeType string) (Handler, error)

ServeErrorTemplate returns a http.Handler that serves the executed template with a given HTTP status code.

If mimeType is empty, it will be sniffed from content.

func ServeString

func ServeString(name string, modtime time.Time, content string) Handler

ServeString returns a http.Handler that calls http.ServeContent with a strings.Reader.

func ServeTemplate

func ServeTemplate(name string, modtime time.Time, tmpl Template, data interface{}) (Handler, error)

ServeTemplate returns a http.Handler that calls http.ServeContent with the executed template.

func SetHeader

func SetHeader(h http.Handler, name, value string) Handler

SetHeader sets a header to a given value in the response.

func SetHeaders

func SetHeaders(h http.Handler, headers map[string]string) Handler

SetHeaders sets multiple response headers.

func StatusCodeSwitch

func StatusCodeSwitch(h http.Handler, handlers map[int]http.Handler) Handler

StatusCodeSwitch intercepts calls to http.ResponseWriter.WriteHeader and redirects the request to a http.Handler based on the response status code.

handlers is a map of HTTP status code (for example http.StatusNotFound) to a http.Handler to use for the response.

It can be used with ServeError to statically render pretty error pages.

type HostSwitch

type HostSwitch struct {

	// NotFound is invoked for hosts
	// that have not been added to the
	// host switch.
	NotFound http.Handler
	// contains filtered or unexported fields
}

HostSwitch is a http.Handler that routes the request based on the Host header.

func (*HostSwitch) Add

func (hs *HostSwitch) Add(host string, h http.Handler)

Add adds a http.Handler to the host switch.

It panics if the host has already been added.

func (*HostSwitch) ServeHTTP

func (hs *HostSwitch) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements http.Handler.

type Middleware

type Middleware = func(http.Handler) http.Handler

Middleware represents a function that wraps an http.Handler.

func AccessLogWrap

func AccessLogWrap(out io.Writer) Middleware

AccessLogWrap returns a Middleware that calls AccessLog.

func AddHeaderWrap

func AddHeaderWrap(name, value string) Middleware

AddHeaderWrap returns a Middleware that calls AddHeader.

func DeleteHeaderWrap

func DeleteHeaderWrap(name string) Middleware

DeleteHeaderWrap returns a Middleware that calls DeleteHeader.

func InternalRedirectWrap

func InternalRedirectWrap(url string) Middleware

InternalRedirectWrap returns a Middleware that calls InternalRedirect.

func SNIMatchWrap

func SNIMatchWrap(mismatch http.Handler) Middleware

SNIMatchWrap returns a Middleware that calls SNIMatch.

func SecurityHeadersWrap

func SecurityHeadersWrap(c *SecurityHeaders) Middleware

SecurityHeadersWrap returns a Middleware that produces a *SecurityHeaders handler.

func SetHeaderWrap

func SetHeaderWrap(name, value string) Middleware

SetHeaderWrap returns a Middleware that calls SetHeader.

func SetHeadersWrap

func SetHeadersWrap(headers map[string]string) Middleware

SetHeadersWrap returns a Middleware that calls SetHeaders.

func StatusCodeSwitchWrap

func StatusCodeSwitchWrap(handlers map[int]http.Handler) Middleware

StatusCodeSwitchWrap returns a Middleware that calls StatusCodeSwitch.

type RedirectToHTTPS

type RedirectToHTTPS struct {
	// Optionally specifies a host to
	// redirect to for clients that do
	// not set the HTTP Host header.
	//
	// If Host is an empty string, a 400
	// Bad Request error will be returned
	// instead.
	Host string

	// Optionally specifies a port to
	// add to the URL.
	Port string

	// The HTTP status code to use when
	// redirecting, defaults to 301 Moved
	// Permanently.
	Code int
}

RedirectToHTTPS redirects clients to the same URL but with the scheme set to https.

func (*RedirectToHTTPS) ServeHTTP

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

ServeHTTP implements http.Handler.

type SafeHostSwitch

type SafeHostSwitch struct {

	// NotFound is invoked for hosts
	// that have not been added to the
	// host switch.
	NotFound http.Handler
	// contains filtered or unexported fields
}

SafeHostSwitch is a http.Handler that routes the request based on the Host header. It is thread safe and requites no external locks.

func (*SafeHostSwitch) Add

func (hs *SafeHostSwitch) Add(host string, h http.Handler) error

Add adds a http.Handler to the host switch.

It returns an error if the host has already been added.

func (*SafeHostSwitch) Remove

func (hs *SafeHostSwitch) Remove(host string)

Remove removes a http.Handler from the host switch.

func (*SafeHostSwitch) ServeHTTP

func (hs *SafeHostSwitch) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements http.Handler.

type SecurityHeaders

type SecurityHeaders struct {
	Handler http.Handler

	// The value of the Content-Security-Policy
	// header to set.
	//
	// It is recommended to set this to
	//  default-src 'none'; sandbox
	// and use less restrictive policies for each
	// resource as needed.
	//
	// This header may require caution to use safely,
	// but it is strongly recommend for all sites.
	//
	// See the article
	//  'Content Security Policy - An Introduction'
	//   https://scotthelme.co.uk/content-security-policy-an-introduction/
	// for more information.
	ContentSecurityPolicy string

	// The value of the Strict-Transport-Security
	// header to set.
	//
	// It takes a max-age directive, with time in
	// seconds, which indicate how long browsers
	// should cache the policy. It should be set to
	// at least six months, like so:
	//  max-age=15768000
	//
	// It also optionally takes two other directives:
	//  - includeSubDomains, which applies the policy
	//    to all subdomains, and
	//  - preload, which signals to browser
	//    manufacturers that this policy may be
	//    preloaded into the browser to prevent
	//    them from ever connecting to the site
	//    without TLS. Visit https://hstspreload.org/
	//    to request preloading.
	//
	// This header may require caution to use safely,
	// but it is strongly recommend for all HTTPS
	// only sites.
	//
	// See the article
	//  'HSTS - The missing link in Transport Layer Security'
	//   https://scotthelme.co.uk/hsts-the-missing-link-in-tls/
	// for more information.
	StrictTransportSecurity string

	// The value of the Expect-CT header to set.
	//
	// It takes a max-age directive, with time in
	// seconds, which indicate how long browsers
	// should cache the policy.
	//
	// It also optionally takes two other directives:
	//  - enforce, which indicates that browsers
	//    should enforce the policy or treat it as
	//    a report-only policy, and
	//  - report-uri, which specifies a URI that
	//    a browser should send a report to, if it
	//    doesn't receive valid CT information.
	//
	// See the article
	//  'A new security header: Expect-CT'
	//   https://scotthelme.co.uk/a-new-security-header-expect-ct/
	// for more information.
	ExpectCT string

	// The value of the Report-To header to set.
	//
	// It should be a json object containing a group,
	// max_age, endpoints and include_subdomains fields.
	//
	// See the article
	//  'Introducing the Reporting API, Network Error Logging and other major upgrades to Report URI'
	//   https://scotthelme.co.uk/introducing-the-reporting-api-nel-other-major-changes-to-report-uri/
	// for more information.
	ReportTo string

	// The value of the NEL header to set.
	//
	// It should be a json object containing a report_to,
	// max_age and include_subdomains fields.
	//
	// See the article
	//  'Network Error Logging: Deep Dive'
	//   https://scotthelme.co.uk/network-error-logging-deep-dive/
	// for more information.
	NEL string

	// The value of the Feature-Policy header to set.
	//
	// This header allows a site to control what browser
	// features are allowed to be used.
	//
	// See the article
	//  'A new security header: Feature Policy'
	//   https://scotthelme.co.uk/a-new-security-header-feature-policy/
	// for more information.
	FeaturePolicy string
}

SecurityHeaders sets several recommended security related headers to sane defaults.

It sets:

  • X-Frame-Options: SAMEORIGIN,
  • X-XSS-Protection: 1; mode=block,
  • X-Content-Type-Options: nosniff, and
  • Referrer-Policy: strict-origin-when-cross-origin.

It also optionally sets the Content-Security-Policy, Strict-Transport-Security and Expect-CT to user specified values.

func (*SecurityHeaders) ServeHTTP

func (sh *SecurityHeaders) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements http.Handler.

type Template

type Template interface {
	Execute(wr io.Writer, data interface{}) error
}

Template is an interface that represents both text/template and html/template for use with ServeTemplate and ServeErrorTemplate.

Jump to

Keyboard shortcuts

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