webutil

package
v1.20210103.1 Latest Latest
Warning

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

Go to latest
Published: Jan 3, 2021 License: MIT Imports: 33 Imported by: 4

Documentation

Overview

Package webutil contains helpers for interacting with the standard library "net/http" package.

It includes things like a webhook sender and helpers to parse the remote address of incoming requests.

It is used by other packages in the repository like `web` and `r2`.

Index

Constants

View Source
const (
	MethodConnect = "CONNECT"
	MethodGet     = "GET"
	MethodDelete  = "DELETE"
	MethodHead    = "HEAD"
	MethodPatch   = "PATCH"
	MethodPost    = "POST"
	MethodPut     = "PUT"
	MethodOptions = "OPTIONS"
)

HTTP Method constants (also referred to as 'verbs')

View Source
const (
	SameSiteStrict  = "strict"
	SameSiteLax     = "lax"
	SameSiteDefault = "default"
)

SameSite prevents the browser from sending this cookie along with cross-site requests. The main goal is mitigate the risk of cross-origin information leakage. It also provides some protection against cross-site request forgery attacks. Possible values for the flag are "lax", "strict" or "default".

View Source
const (
	SchemeHTTP  = "http"
	SchemeHTTPS = "https"
	SchemeSPDY  = "spdy"
)

Well known schemes

View Source
const (
	HSTSMaxAgeFormat      = "max-age=%d"
	HSTSIncludeSubDomains = "includeSubDomains"
	HSTSPreload           = "preload"
)

HSTS Cookie Fields

View Source
const (
	// ContentTypeApplicationJSON is a content type for JSON responses.
	// We specify chartset=utf-8 so that clients know to use the UTF-8 string encoding.
	ContentTypeApplicationJSON = "application/json; charset=utf-8"

	// ContentTypeApplicationXML is a content type header value.
	ContentTypeApplicationXML = "application/xml"

	// ContentTypeApplicationFormEncoded is a content type header value.
	ContentTypeApplicationFormEncoded = "application/x-www-form-urlencoded"

	// ContentTypeApplicationOctetStream is a content type header value.
	ContentTypeApplicationOctetStream = "application/octet-stream"

	// ContentTypeHTML is a content type for html responses.
	// We specify chartset=utf-8 so that clients know to use the UTF-8 string encoding.
	ContentTypeHTML = "text/html; charset=utf-8"

	//ContentTypeXML is a content type for XML responses.
	// We specify chartset=utf-8 so that clients know to use the UTF-8 string encoding.
	ContentTypeXML = "text/xml; charset=utf-8"

	// ContentTypeText is a content type for text responses.
	// We specify chartset=utf-8 so that clients know to use the UTF-8 string encoding.
	ContentTypeText = "text/plain; charset=utf-8"

	// ContentEncodingIdentity is the identity (uncompressed) content encoding.
	ContentEncodingIdentity = "identity"

	// ContentEncodingGZIP is the gzip (compressed) content encoding.
	ContentEncodingGZIP = "gzip"
)
View Source
const (
	ErrInvalidSameSite        ex.Class = "invalid cookie same site string value"
	ErrParameterMissing       ex.Class = "parameter missing"
	ErrUnauthorized           ex.Class = "unauthorized"
	ErrInvalidSplitColonInput ex.Class = `split colon input string is not of the form "<first>:<second>"`
)

Errors

View Source
const (
	// ConnectionKeepAlive is a value for the "Connection" header and
	// indicates the server should keep the tcp connection open
	// after the last byte of the response is sent.
	ConnectionKeepAlive = "keep-alive"
)

Connection header values.

View Source
const (
	FlagHTTPRequest = "http.request"
)

Logger flags

View Source
const (
	// MaxPostBodySize is the maximum post body size we will typically consume.
	MaxPostBodySize = int64(1 << 26) //64mb
)
View Source
const (
	// TestURL can be used in tests for the URL passed to requests.
	//
	// The URL itself sets `https` as the scheme, `test.invalid` as the host,
	// `/test` as the path, and `query=value` as the querystring.
	//
	// Note: .invalid is a special top level domain that will _never_ be assigned
	// to a real registrant, it is always reserved for testing.
	// See: https://www.iana.org/domains/reserved
	TestURL = "https://test.invalid/test?query=value"
)

Variables

View Source
var (
	HeaderAccept                  = http.CanonicalHeaderKey("Accept")
	HeaderAcceptEncoding          = http.CanonicalHeaderKey("Accept-Encoding")
	HeaderAllow                   = http.CanonicalHeaderKey("Allow")
	HeaderAuthorization           = http.CanonicalHeaderKey("Authorization")
	HeaderCacheControl            = http.CanonicalHeaderKey("Cache-Control")
	HeaderConnection              = http.CanonicalHeaderKey("Connection")
	HeaderContentEncoding         = http.CanonicalHeaderKey("Content-Encoding")
	HeaderContentLength           = http.CanonicalHeaderKey("Content-Length")
	HeaderContentType             = http.CanonicalHeaderKey("Content-Type")
	HeaderCookie                  = http.CanonicalHeaderKey("Cookie")
	HeaderDate                    = http.CanonicalHeaderKey("Date")
	HeaderETag                    = http.CanonicalHeaderKey("etag")
	HeaderForwarded               = http.CanonicalHeaderKey("Forwarded")
	HeaderServer                  = http.CanonicalHeaderKey("Server")
	HeaderSetCookie               = http.CanonicalHeaderKey("Set-Cookie")
	HeaderStrictTransportSecurity = http.CanonicalHeaderKey("Strict-Transport-Security")
	HeaderUserAgent               = http.CanonicalHeaderKey("User-Agent")
	HeaderVary                    = http.CanonicalHeaderKey("Vary")
	HeaderXContentTypeOptions     = http.CanonicalHeaderKey("X-Content-Type-Options")
	HeaderXForwardedFor           = http.CanonicalHeaderKey("X-Forwarded-For")
	HeaderXForwardedHost          = http.CanonicalHeaderKey("X-Forwarded-Host")
	HeaderXForwardedPort          = http.CanonicalHeaderKey("X-Forwarded-Port")
	HeaderXForwardedProto         = http.CanonicalHeaderKey("X-Forwarded-Proto")
	HeaderXForwardedScheme        = http.CanonicalHeaderKey("X-Forwarded-Scheme")
	HeaderXFrameOptions           = http.CanonicalHeaderKey("X-Frame-Options")
	HeaderXRealIP                 = http.CanonicalHeaderKey("X-Real-IP")
	HeaderXServedBy               = http.CanonicalHeaderKey("X-Served-By")
	HeaderXXSSProtection          = http.CanonicalHeaderKey("X-Xss-Protection")
)

Header names in canonical form.

View Source
var (
	KnownExtensions = map[string]string{
		".html": "text/html; charset=utf-8",
		".xml":  "text/xml; charset",
		".json": "application/json; charset=utf-8",
		".css":  "text/css; charset=utf-8",
		".js":   "application/javascript",
		".jpg":  "image/jpeg",
		".jpeg": "image/jpeg",
		".png":  "image/png",
	}
)

KnownExtenions are known extenions mapped to their content types.

Functions

func ColorizeByStatusCode added in v1.20201204.1

func ColorizeByStatusCode(statusCode int, value string) string

ColorizeByStatusCode returns a value colored by an http status code.

func ColorizeByStatusCodeWithFormatter added in v1.20201204.1

func ColorizeByStatusCodeWithFormatter(tf logger.TextFormatter, statusCode int, value string) string

ColorizeByStatusCodeWithFormatter returns a value colored by an http status code with a given formatter.

func ColorizeStatusCode added in v1.20201204.1

func ColorizeStatusCode(statusCode int) string

ColorizeStatusCode colorizes a status code.

func ColorizeStatusCodeWithFormatter added in v1.20201204.1

func ColorizeStatusCodeWithFormatter(tf logger.TextFormatter, statusCode int) string

ColorizeStatusCodeWithFormatter colorizes a status code with a given formatter.

func DecodeBasicAuth added in v1.20201204.1

func DecodeBasicAuth(req *http.Request) (username, password string, err error)

DecodeBasicAuth pulls a basic auth header from a request and returns the username and password that were passed.

func DeserializeReaderAsJSON

func DeserializeReaderAsJSON(object interface{}, body io.ReadCloser) error

DeserializeReaderAsJSON deserializes a post body as json to a given object.

func DetectContentType added in v1.20201204.1

func DetectContentType(path string) (string, error)

DetectContentType generates the content type of a given file by path.

func ETag added in v1.20201204.1

func ETag(contents []byte) string

ETag creates an etag for a given blob.

func ErrIsInvalidSameSite added in v1.20201204.1

func ErrIsInvalidSameSite(err error) bool

ErrIsInvalidSameSite returns if an error is `ErrInvalidSameSite`

func ErrIsInvalidSplitColonInput added in v1.20201204.1

func ErrIsInvalidSplitColonInput(err error) bool

ErrIsInvalidSplitColonInput returns if an error is `ErrInvalidSplitColonInput`

func ErrIsParameterMissing added in v1.20201204.1

func ErrIsParameterMissing(err error) bool

ErrIsParameterMissing returns if an error is `ErrParameterMissing`

func ErrIsUnauthorized added in v1.20201204.1

func ErrIsUnauthorized(err error) bool

ErrIsUnauthorized returns if an error is `ErrUnauthorized`

func FormatHeaders added in v1.20201204.1

func FormatHeaders(tf logger.TextFormatter, keyColor ansi.Color, header http.Header) string

FormatHeaders formats headers for output. Header keys will be printed in alphabetic order.

func GetContentEncoding added in v1.20201204.1

func GetContentEncoding(header http.Header) string

GetContentEncoding gets the content type out of a header collection.

func GetContentType added in v1.20201204.1

func GetContentType(header http.Header) string

GetContentType gets the content type out of a header collection.

func GetHost

func GetHost(r *http.Request) string

GetHost returns the request host, omiting the port if specified.

func GetPort added in v1.1.1

func GetPort(r *http.Request) string

GetPort returns the port for a given request.

func GetProto

func GetProto(r *http.Request) (scheme string)

GetProto gets the request proto. X-FORWARDED-PROTO is checked first, then the original request proto is used.

func GetRemoteAddr

func GetRemoteAddr(r *http.Request) string

GetRemoteAddr gets the origin/client ip for a request. X-FORWARDED-FOR is checked. If multiple IPs are included the first one is returned X-REAL-IP is checked. If multiple IPs are included the last one is returned Finally r.RemoteAddr is used Only benevolent services will allow access to the real IP.

func GetUserAgent

func GetUserAgent(r *http.Request) string

GetUserAgent gets a user agent from a request.

func HTTPSRedirectFunc added in v1.20201204.1

func HTTPSRedirectFunc(rw http.ResponseWriter, req *http.Request)

HTTPSRedirectFunc redirects HTTP to HTTPS as an http.HandlerFunc.

func HeaderAny added in v1.20201204.1

func HeaderAny(headers http.Header, key, value string) bool

HeaderAny returns if any pieces of a header match a given value.

func HeaderLastValue added in v1.1.1

func HeaderLastValue(headers http.Header, key string) (string, bool)

HeaderLastValue returns the last value of a potential csv of headers.

func Headers added in v1.20210103.1

func Headers(from map[string]string) http.Header

Headers creates headers from a given map.

func HostHasPort added in v1.20201204.1

func HostHasPort(s string) bool

HostHasPort returns true if a string is in the form "host:port", or "[ipv6::address]:port".

func IsHTTPTokenRune added in v1.20201204.1

func IsHTTPTokenRune(r rune) bool

IsHTTPTokenRune returns if a rune is in the http valid rune table.

func IsValidMethod added in v1.20201204.1

func IsValidMethod(method string) bool

IsValidMethod returns if a http method is valid.

Method         = "OPTIONS"                ; Section 9.2
				| "GET"                    ; Section 9.3
				| "HEAD"                   ; Section 9.4
				| "POST"                   ; Section 9.5
				| "PUT"                    ; Section 9.6
				| "DELETE"                 ; Section 9.7
				| "TRACE"                  ; Section 9.8
				| "CONNECT"                ; Section 9.9
				| extension-method
extension-method = token
	token          = 1*<any CHAR except CTLs or separators>

func LocalIP

func LocalIP() string

LocalIP returns the local server ip.

func MustParseSameSite added in v1.20201204.1

func MustParseSameSite(sameSite string) http.SameSite

MustParseSameSite parses a string value for same site and panics on error.

func MustParseURL

func MustParseURL(rawURL string) *url.URL

MustParseURL parses a url and panics if there is an error.

func NestMiddleware added in v1.20201204.1

func NestMiddleware(action http.HandlerFunc, middleware ...Middleware) http.HandlerFunc

NestMiddleware nests middleware steps.

func NewHTTPRequestEventFilter added in v1.20201204.1

func NewHTTPRequestEventFilter(filter func(context.Context, HTTPRequestEvent) (HTTPRequestEvent, bool)) logger.Filter

NewHTTPRequestEventFilter returns a new http request event filter.

func NewHTTPRequestEventListener added in v1.20201204.1

func NewHTTPRequestEventListener(listener func(context.Context, HTTPRequestEvent)) logger.Listener

NewHTTPRequestEventListener returns a new web request event listener.

func NewMockRequest

func NewMockRequest(method, path string) *http.Request

NewMockRequest creates a mock request.

func NewMockRequestWithCookie

func NewMockRequestWithCookie(method, path, cookieName, cookieValue string) *http.Request

NewMockRequestWithCookie creates a mock request with a cookie attached to it.

func NoFollowRedirects added in v1.20201204.1

func NoFollowRedirects() func(req *http.Request, via []*http.Request) error

NoFollowRedirects returns an http client redirect delegate that returns the http.ErrUseLastResponse error. This prevents the net/http Client from following any redirects.

func ParseSameSite added in v1.20201204.1

func ParseSameSite(sameSite string) (http.SameSite, error)

ParseSameSite parses a string value for same site.

func PortFromBindAddr

func PortFromBindAddr(bindAddr string) (port int32)

PortFromBindAddr returns a port number as an integer from a bind addr.

func RemoveHostEmptyPort added in v1.20201204.1

func RemoveHostEmptyPort(host string) string

RemoveHostEmptyPort strips the empty port in ":port" to "" as mandated by RFC 3986 Section 6.2.3.

func SplitColon added in v1.20201204.1

func SplitColon(value string) (first, second string, err error)

SplitColon splits a string on a **single** colon. For example, for a basic auth header, we'd want to split a string of the form "<username>:<password>".

func TLSSecureCipherSuites added in v1.20201204.1

func TLSSecureCipherSuites(tlsConfig *tls.Config)

TLSSecureCipherSuites sets the tls config to use secure cipher suites.

func URLWithHost

func URLWithHost(u *url.URL, host string) *url.URL

URLWithHost returns a copy url with a given host.

func URLWithPath

func URLWithPath(u *url.URL, path string) *url.URL

URLWithPath returns a copy url with a given path.

func URLWithPort added in v0.2.0

func URLWithPort(u *url.URL, port string) *url.URL

URLWithPort returns a copy url with a given pprt attached to the host.

func URLWithQuery added in v0.2.0

func URLWithQuery(u *url.URL, key, value string) *url.URL

URLWithQuery returns a copy url with a given raw query.

func URLWithRawQuery

func URLWithRawQuery(u *url.URL, rawQuery string) *url.URL

URLWithRawQuery returns a copy url with a given raw query.

func URLWithScheme

func URLWithScheme(u *url.URL, scheme string) *url.URL

URLWithScheme returns a copy url with a given scheme.

func WithClientHTTPTrace added in v1.20210103.1

func WithClientHTTPTrace(req *http.Request, trace *HTTPTrace) *http.Request

WithClientHTTPTrace adds the http client trace to the request.

func WriteJSON

func WriteJSON(w http.ResponseWriter, statusCode int, response interface{}) error

WriteJSON marshalls an object to json.

func WriteNoContent

func WriteNoContent(w http.ResponseWriter) error

WriteNoContent writes http.StatusNoContent for a request.

func WriteRawContent

func WriteRawContent(w http.ResponseWriter, statusCode int, content []byte) error

WriteRawContent writes raw content for the request.

func WriteXML

func WriteXML(w http.ResponseWriter, statusCode int, response interface{}) error

WriteXML marshalls an object to json.

Types

type CertInfo added in v1.20201204.1

type CertInfo struct {
	SubjectCommonName string    `json:"subjectCommonName" yaml:"subjectCommonName"`
	IssuerCommonName  string    `json:"issuerCommonName" yaml:"issuerCommonName"`
	IssuerNames       []string  `json:"issuerNames" yaml:"issuerNames"`
	DNSNames          []string  `json:"dnsNames" yaml:"dnsNames"`
	NotAfter          time.Time `json:"notAfter" yaml:"notAfter"`
	NotBefore         time.Time `json:"notBefore" yaml:"notBefore"`
}

CertInfo is the information for a certificate.

func ParseCertInfo added in v1.20201204.1

func ParseCertInfo(res *http.Response) *CertInfo

ParseCertInfo returns a new cert info from a response from a check.

func (CertInfo) IsExpired added in v1.20201204.1

func (ci CertInfo) IsExpired() bool

IsExpired returns if the certificate is strictly expired and would not be accepted by browsers.

func (CertInfo) WillBeExpired added in v1.20201204.1

func (ci CertInfo) WillBeExpired(at time.Time) bool

WillBeExpired returns if the certificate is strictly expired and would not be accepted by browsers at a given time.

type DialOption added in v1.20201204.1

type DialOption func(*net.Dialer)

DialOption is a mutator for a net.Dialer

func OptDialKeepAlive added in v1.20201204.1

func OptDialKeepAlive(d time.Duration) DialOption

OptDialKeepAlive sets the dial keep alive duration. Only use this if you know what you're doing, the defaults are typically sufficient.

func OptDialTimeout added in v1.20201204.1

func OptDialTimeout(d time.Duration) DialOption

OptDialTimeout sets the dial timeout.

type EventSource added in v1.20201204.1

type EventSource struct {
	sync.Mutex
	// contains filtered or unexported fields
}

EventSource is a helper for writing event source info.

func NewEventSource added in v1.20201204.1

func NewEventSource(output http.ResponseWriter) *EventSource

NewEventSource returns a new event source. It is critical the response is *NOT* gzipped, as this will prevent `EventSource` from being able to effectively flush events.

func (*EventSource) Data added in v1.20201204.1

func (es *EventSource) Data(data string) error

Data writes a data segment. It will slit lines on newline across multiple data events.

func (*EventSource) Event added in v1.20201204.1

func (es *EventSource) Event(name string) error

Event writes an event.

func (*EventSource) EventData added in v1.20201204.1

func (es *EventSource) EventData(name, data string) error

EventData sends an event with a given set of data.

func (*EventSource) EventDataWithID added in v1.20201204.1

func (es *EventSource) EventDataWithID(name, data, id string) error

EventDataWithID sends a named event with a given set of data and message identifier.

func (*EventSource) Ping added in v1.20201204.1

func (es *EventSource) Ping() error

Ping sends the ping heartbeat event.

func (*EventSource) StartSession added in v1.20201204.1

func (es *EventSource) StartSession() error

StartSession starts an event source session.

type GZipResponseWriter added in v1.20201204.1

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

GZipResponseWriter is a response writer that compresses output.

func NewGZipResponseWriter added in v1.20201204.1

func NewGZipResponseWriter(w http.ResponseWriter) *GZipResponseWriter

NewGZipResponseWriter returns a new gzipped response writer.

func (*GZipResponseWriter) Close added in v1.20201204.1

func (crw *GZipResponseWriter) Close() error

Close closes any underlying resources.

func (*GZipResponseWriter) ContentLength added in v1.20201204.1

func (crw *GZipResponseWriter) ContentLength() int

ContentLength returns the content length for the request.

func (*GZipResponseWriter) Flush added in v1.20201204.1

func (crw *GZipResponseWriter) Flush()

Flush pushes any buffered data out to the response.

func (*GZipResponseWriter) Header added in v1.20201204.1

func (crw *GZipResponseWriter) Header() http.Header

Header returns the headers for the response.

func (*GZipResponseWriter) InnerResponse added in v1.20201204.1

func (crw *GZipResponseWriter) InnerResponse() http.ResponseWriter

InnerResponse returns the underlying response.

func (*GZipResponseWriter) StatusCode added in v1.20201204.1

func (crw *GZipResponseWriter) StatusCode() int

StatusCode returns the status code for the request.

func (*GZipResponseWriter) Write added in v1.20201204.1

func (crw *GZipResponseWriter) Write(b []byte) (int, error)

Write writes the byes to the stream.

func (*GZipResponseWriter) WriteHeader added in v1.20201204.1

func (crw *GZipResponseWriter) WriteHeader(code int)

WriteHeader writes a status code.

type GracefulHTTPServer added in v1.20201204.1

type GracefulHTTPServer struct {
	Latch               *async.Latch
	Server              *http.Server
	ShutdownGracePeriod time.Duration
	Listener            net.Listener
}

GracefulHTTPServer is a wrapper for an http server that implements the graceful interface.

func NewGracefulHTTPServer added in v1.20201204.1

func NewGracefulHTTPServer(server *http.Server, options ...GracefulHTTPServerOption) *GracefulHTTPServer

NewGracefulHTTPServer returns a new graceful http server wrapper.

func (*GracefulHTTPServer) NotifyStarted added in v1.20201204.1

func (gs *GracefulHTTPServer) NotifyStarted() <-chan struct{}

NotifyStarted implements part of graceful.

func (*GracefulHTTPServer) NotifyStopped added in v1.20201204.1

func (gs *GracefulHTTPServer) NotifyStopped() <-chan struct{}

NotifyStopped implements part of graceful.

func (*GracefulHTTPServer) Start added in v1.20201204.1

func (gs *GracefulHTTPServer) Start() (err error)

Start implements graceful.Graceful.Start. It is expected to block.

func (*GracefulHTTPServer) Stop added in v1.20201204.1

func (gs *GracefulHTTPServer) Stop() error

Stop implements graceful.Graceful.Stop.

type GracefulHTTPServerOption added in v1.20201204.1

type GracefulHTTPServerOption func(*GracefulHTTPServer)

GracefulHTTPServerOption is an option for the graceful http server.

func OptGracefulHTTPServerListener added in v1.20201204.1

func OptGracefulHTTPServerListener(listener net.Listener) GracefulHTTPServerOption

OptGracefulHTTPServerListener sets the server listener.

func OptGracefulHTTPServerShutdownGracePeriod added in v1.20201204.1

func OptGracefulHTTPServerShutdownGracePeriod(d time.Duration) GracefulHTTPServerOption

OptGracefulHTTPServerShutdownGracePeriod sets the shutdown grace period.

type HTTPRequestEvent added in v1.20201204.1

type HTTPRequestEvent struct {
	Request         *http.Request
	Route           string
	ContentLength   int
	ContentType     string
	ContentEncoding string
	StatusCode      int
	Elapsed         time.Duration
	Header          http.Header
}

HTTPRequestEvent is an event type for http requests.

func NewHTTPRequestEvent added in v1.20201204.1

func NewHTTPRequestEvent(req *http.Request, options ...HTTPRequestEventOption) HTTPRequestEvent

NewHTTPRequestEvent is an event representing a request to an http server.

func (HTTPRequestEvent) Decompose added in v1.20201204.1

func (e HTTPRequestEvent) Decompose() map[string]interface{}

Decompose implements JSONWritable.

func (HTTPRequestEvent) GetFlag added in v1.20201204.1

func (e HTTPRequestEvent) GetFlag() string

GetFlag implements event.

func (HTTPRequestEvent) WriteText added in v1.20201204.1

func (e HTTPRequestEvent) WriteText(tf logger.TextFormatter, wr io.Writer)

WriteText implements TextWritable.

type HTTPRequestEventOption added in v1.20201204.1

type HTTPRequestEventOption func(*HTTPRequestEvent)

HTTPRequestEventOption is a function that modifies an http request event.

func OptHTTPRequestContentEncoding added in v1.20201204.1

func OptHTTPRequestContentEncoding(contentEncoding string) HTTPRequestEventOption

OptHTTPRequestContentEncoding sets a field.

func OptHTTPRequestContentLength added in v1.20201204.1

func OptHTTPRequestContentLength(contentLength int) HTTPRequestEventOption

OptHTTPRequestContentLength sets a field.

func OptHTTPRequestContentType added in v1.20201204.1

func OptHTTPRequestContentType(contentType string) HTTPRequestEventOption

OptHTTPRequestContentType sets a field.

func OptHTTPRequestElapsed added in v1.20201204.1

func OptHTTPRequestElapsed(elapsed time.Duration) HTTPRequestEventOption

OptHTTPRequestElapsed sets a field.

func OptHTTPRequestHeader added in v1.20201204.1

func OptHTTPRequestHeader(header http.Header) HTTPRequestEventOption

OptHTTPRequestHeader sets a field.

func OptHTTPRequestRequest added in v1.20201204.1

func OptHTTPRequestRequest(req *http.Request) HTTPRequestEventOption

OptHTTPRequestRequest sets a field.

func OptHTTPRequestRoute added in v1.20201204.1

func OptHTTPRequestRoute(route string) HTTPRequestEventOption

OptHTTPRequestRoute sets a field.

func OptHTTPRequestStatusCode added in v1.20201204.1

func OptHTTPRequestStatusCode(statusCode int) HTTPRequestEventOption

OptHTTPRequestStatusCode sets a field.

type HTTPServerOption added in v1.20201204.1

type HTTPServerOption func(*http.Server) error

HTTPServerOption is a mutator for an http server.

func OptHTTPServerAddr added in v1.20201204.1

func OptHTTPServerAddr(addr string) HTTPServerOption

OptHTTPServerAddr mutates a http server.

func OptHTTPServerBaseContext added in v1.20201204.1

func OptHTTPServerBaseContext(baseContextProvider func(net.Listener) context.Context) HTTPServerOption

OptHTTPServerBaseContext sets the base context for requests to a given server.

func OptHTTPServerErrorLog added in v1.20201204.1

func OptHTTPServerErrorLog(log *log.Logger) HTTPServerOption

OptHTTPServerErrorLog sets the error log.

func OptHTTPServerHandler added in v1.20201204.1

func OptHTTPServerHandler(handler http.Handler) HTTPServerOption

OptHTTPServerHandler mutates a http server.

func OptHTTPServerIdleTimeout added in v1.20201204.1

func OptHTTPServerIdleTimeout(value time.Duration) HTTPServerOption

OptHTTPServerIdleTimeout mutates a http server.

func OptHTTPServerMaxHeaderBytes added in v1.20201204.1

func OptHTTPServerMaxHeaderBytes(value int) HTTPServerOption

OptHTTPServerMaxHeaderBytes mutates a http server.

func OptHTTPServerReadHeaderTimeout added in v1.20201204.1

func OptHTTPServerReadHeaderTimeout(value time.Duration) HTTPServerOption

OptHTTPServerReadHeaderTimeout mutates a http server.

func OptHTTPServerReadTimeout added in v1.20201204.1

func OptHTTPServerReadTimeout(value time.Duration) HTTPServerOption

OptHTTPServerReadTimeout mutates a http server.

func OptHTTPServerTLSConfig added in v1.20201204.1

func OptHTTPServerTLSConfig(cfg *tls.Config) HTTPServerOption

OptHTTPServerTLSConfig mutates a http server.

func OptHTTPServerWriteTimeout added in v1.20201204.1

func OptHTTPServerWriteTimeout(value time.Duration) HTTPServerOption

OptHTTPServerWriteTimeout mutates a http server.

type HTTPTrace added in v1.20201204.1

type HTTPTrace struct {
	Start       time.Time `json:"start"`
	GetConn     time.Time `json:"getConn"`
	GotConn     time.Time `json:"gotConn"`
	PutIdleConn time.Time `json:"putIdleConn"`

	DNSStart time.Time `json:"dnsStart"`
	DNSDone  time.Time `json:"dnsDone"`

	ConnectStart time.Time `json:"connectStart"`
	ConnectDone  time.Time `json:"connectDone"`

	TLSHandshakeStart time.Time `json:"tlsHandshakeStart"`
	TLSHandshakeDone  time.Time `json:"tlsHandshakeDone"`

	WroteHeaders         time.Time `json:"wroteHeaders"`
	WroteRequest         time.Time `json:"wroteRequest"`
	GotFirstResponseByte time.Time `json:"gotFirstResponseByte"`

	DNSElapsed          time.Duration `json:"dnsElapsed"`
	TLSHandshakeElapsed time.Duration `json:"tlsHandshakeElapsed"`
	DialElapsed         time.Duration `json:"dialElapsed"`
	RequestElapsed      time.Duration `json:"requestElapsed"`
	ServerElapsed       time.Duration `json:"severElapsed"`
}

HTTPTrace is timing information for the full http call.

func (*HTTPTrace) Trace added in v1.20201204.1

func (ht *HTTPTrace) Trace() *httptrace.ClientTrace

Trace returns the trace binder.

type HTTPTraceFinisher added in v1.20201204.1

type HTTPTraceFinisher interface {
	Finish(error)
}

HTTPTraceFinisher is a simplified version of `TraceFinisher`.

type HTTPTracer added in v1.20201204.1

type HTTPTracer interface {
	Start(*http.Request) (HTTPTraceFinisher, *http.Request)
}

HTTPTracer is a simplified version of `Tracer` intended for a raw `(net/http).Request`. It returns a "new" request the request context may be modified after opening a span.

type Middleware added in v1.20201204.1

type Middleware func(http.HandlerFunc) http.HandlerFunc

Middleware is a wrapping function that takes a handler and returns a handler.

func HTTPLogged added in v1.20201204.1

func HTTPLogged(log logger.Triggerable) Middleware

HTTPLogged returns a middleware that logs a request.

type MockResponseWriter

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

MockResponseWriter is an object that satisfies response writer but uses an internal buffer.

func NewMockResponse

func NewMockResponse(buffer io.Writer) *MockResponseWriter

NewMockResponse returns a mocked response writer.

func (*MockResponseWriter) Bytes

func (res *MockResponseWriter) Bytes() []byte

Bytes returns the raw response.

func (*MockResponseWriter) Close

func (res *MockResponseWriter) Close() error

Close is a no-op.

func (*MockResponseWriter) ContentLength

func (res *MockResponseWriter) ContentLength() int

ContentLength returns the content length.

func (*MockResponseWriter) Flush

func (res *MockResponseWriter) Flush()

Flush is a no-op.

func (*MockResponseWriter) Header

func (res *MockResponseWriter) Header() http.Header

Header returns the response headers.

func (*MockResponseWriter) InnerResponse

func (res *MockResponseWriter) InnerResponse() http.ResponseWriter

InnerResponse returns the backing httpresponse writer.

func (*MockResponseWriter) StatusCode

func (res *MockResponseWriter) StatusCode() int

StatusCode returns the status code.

func (*MockResponseWriter) Write

func (res *MockResponseWriter) Write(buffer []byte) (int, error)

Write writes data and adds to ContentLength.

func (*MockResponseWriter) WriteHeader

func (res *MockResponseWriter) WriteHeader(statusCode int)

WriteHeader sets the status code.

type PostedFile added in v1.20201204.1

type PostedFile struct {
	Key      string
	FileName string
	Contents []byte
}

PostedFile is a file that has been posted to an hc endpoint.

func PostedFiles added in v1.20201204.1

func PostedFiles(r *http.Request) ([]PostedFile, error)

PostedFiles returns any files posted

type RequestOption added in v1.20201204.1

type RequestOption func(*http.Request) error

RequestOption is an option for http.Request.

func OptBasicAuth added in v1.20201204.1

func OptBasicAuth(username, password string) RequestOption

OptBasicAuth is an option that sets the http basic auth.

func OptBody added in v1.20201204.1

func OptBody(contents io.ReadCloser) RequestOption

OptBody sets the post body on the request.

func OptBodyBytes added in v1.20201204.1

func OptBodyBytes(body []byte) RequestOption

OptBodyBytes sets a body on a context from bytes.

func OptContext added in v1.20201204.1

func OptContext(ctx context.Context) RequestOption

OptContext sets the request context.

func OptCookie added in v1.20201204.1

func OptCookie(cookie *http.Cookie) RequestOption

OptCookie adds a cookie to a context.

func OptCookieValue added in v1.20201204.1

func OptCookieValue(key, value string) RequestOption

OptCookieValue adds a cookie value to a context.

func OptDelete added in v1.20201204.1

func OptDelete() RequestOption

OptDelete sets the request method.

func OptGet added in v1.20201204.1

func OptGet() RequestOption

OptGet sets the request method.

func OptHTTPClientTrace added in v1.20210103.1

func OptHTTPClientTrace(ht *HTTPTrace) RequestOption

OptHTTPClientTrace sets the http trace on the outgoing request.

func OptHeader added in v1.20201204.1

func OptHeader(headers http.Header) RequestOption

OptHeader sets the request headers.

func OptHeaderValue added in v1.20201204.1

func OptHeaderValue(key, value string) RequestOption

OptHeaderValue sets a header value on a request.

func OptJSONBody added in v1.20201204.1

func OptJSONBody(obj interface{}) RequestOption

OptJSONBody sets the post body on the request.

func OptMethod added in v1.20201204.1

func OptMethod(method string) RequestOption

OptMethod sets the request method.

func OptPatch added in v1.20201204.1

func OptPatch() RequestOption

OptPatch sets the request method.

func OptPost added in v1.20201204.1

func OptPost() RequestOption

OptPost sets the request method.

func OptPostForm added in v1.20201204.1

func OptPostForm(postForm url.Values) RequestOption

OptPostForm sets the request post form and the content type.

func OptPostFormValue added in v1.20201204.1

func OptPostFormValue(key, value string) RequestOption

OptPostFormValue sets a request post form value.

func OptPostedFiles added in v1.20201204.1

func OptPostedFiles(files ...PostedFile) RequestOption

OptPostedFiles sets a body from posted files.

func OptPut added in v1.20201204.1

func OptPut() RequestOption

OptPut sets the request method.

func OptQuery added in v1.20201204.1

func OptQuery(query url.Values) RequestOption

OptQuery sets the full querystring.

func OptQueryValue added in v1.20201204.1

func OptQueryValue(key, value string) RequestOption

OptQueryValue sets a query value on a request.

func OptXMLBody added in v1.20201204.1

func OptXMLBody(obj interface{}) RequestOption

OptXMLBody sets the post body on the request.

type RequestOptions added in v1.20201204.1

type RequestOptions []RequestOption

RequestOptions are an array of RequestOption.

func (RequestOptions) Apply added in v1.20201204.1

func (ro RequestOptions) Apply(req *http.Request) (err error)

Apply applies the options to a request.

type ResponseWriter added in v1.20201204.1

type ResponseWriter interface {
	http.ResponseWriter
	ContentLength() int
	StatusCode() int
	InnerResponse() http.ResponseWriter
}

ResponseWriter is a response writer that also returns the written status.

type StatusResponseWriter added in v1.20201204.1

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

StatusResponseWriter a better response writer

func NewStatusResponseWriter added in v1.20201204.1

func NewStatusResponseWriter(w http.ResponseWriter) *StatusResponseWriter

NewStatusResponseWriter creates a new response writer.

func (*StatusResponseWriter) Close added in v1.20201204.1

func (rw *StatusResponseWriter) Close() error

Close calls close on the inner response if it supports it.

func (*StatusResponseWriter) ContentLength added in v1.20201204.1

func (rw *StatusResponseWriter) ContentLength() int

ContentLength returns the content length

func (*StatusResponseWriter) Flush added in v1.20201204.1

func (rw *StatusResponseWriter) Flush()

Flush calls flush on the inner response writer if it is supported.

func (*StatusResponseWriter) Header added in v1.20201204.1

func (rw *StatusResponseWriter) Header() http.Header

Header accesses the response header collection.

func (*StatusResponseWriter) Hijack added in v1.20201204.1

func (rw *StatusResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error)

Hijack wraps response writer's Hijack function.

func (*StatusResponseWriter) InnerResponse added in v1.20201204.1

func (rw *StatusResponseWriter) InnerResponse() http.ResponseWriter

InnerResponse returns the backing writer.

func (*StatusResponseWriter) StatusCode added in v1.20201204.1

func (rw *StatusResponseWriter) StatusCode() int

StatusCode returns the status code.

func (*StatusResponseWriter) Write added in v1.20201204.1

func (rw *StatusResponseWriter) Write(b []byte) (int, error)

Write writes the data to the response.

func (*StatusResponseWriter) WriteHeader added in v1.20201204.1

func (rw *StatusResponseWriter) WriteHeader(code int)

WriteHeader writes the status code (it is a somewhat poorly chosen method name from the standard library).

type TCPKeepAliveListener added in v1.20201204.1

type TCPKeepAliveListener struct {
	*net.TCPListener

	KeepAlive       bool
	KeepAlivePeriod time.Duration
}

TCPKeepAliveListener sets TCP keep-alive timeouts on accepted connections. It's used by ListenAndServe and ListenAndServeTLS so dead TCP connections (e.g. closing laptop mid-download) eventually go away. Taken from net/http/server.go

func (TCPKeepAliveListener) Accept added in v1.20201204.1

func (ln TCPKeepAliveListener) Accept() (c net.Conn, err error)

Accept implements net.Listener

type Webhook added in v1.20201204.1

type Webhook struct {
	Method  string            `json:"method" yaml:"method"`
	URL     string            `json:"url" yaml:"url"`
	Headers map[string]string `json:"headers" yaml:"headers"`
	Body    string            `json:"body" yaml:"body"`
}

Webhook is a configurable request.

func (Webhook) IsZero added in v1.20201204.1

func (wh Webhook) IsZero() bool

IsZero returns if the webhook is set.

func (Webhook) MethodOrDefault added in v1.20201204.1

func (wh Webhook) MethodOrDefault() string

MethodOrDefault returns the method or a default.

func (Webhook) Send added in v1.20201204.1

func (wh Webhook) Send() (*http.Response, error)

Send sends the webhook.

Jump to

Keyboard shortcuts

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