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
- Variables
- func ColorizeByStatusCode(statusCode int, value string) string
- func ColorizeByStatusCodeWithFormatter(tf logger.TextFormatter, statusCode int, value string) string
- func ColorizeStatusCode(statusCode int) string
- func ColorizeStatusCodeWithFormatter(tf logger.TextFormatter, statusCode int) string
- func DecodeBasicAuth(req *http.Request) (username, password string, err error)
- func DeserializeReaderAsJSON(object interface{}, body io.ReadCloser) error
- func DetectContentType(path string) (string, error)
- func ETag(contents []byte) string
- func ErrIsInvalidSameSite(err error) bool
- func ErrIsInvalidSplitColonInput(err error) bool
- func ErrIsParameterMissing(err error) bool
- func ErrIsUnauthorized(err error) bool
- func FormatHeaders(tf logger.TextFormatter, keyColor ansi.Color, header http.Header) string
- func GetContentEncoding(header http.Header) string
- func GetContentType(header http.Header) string
- func GetHost(r *http.Request) string
- func GetPort(r *http.Request) string
- func GetProto(r *http.Request) (scheme string)
- func GetRemoteAddr(r *http.Request) string
- func GetUserAgent(r *http.Request) string
- func HTTPSRedirectFunc(rw http.ResponseWriter, req *http.Request)
- func HeaderAny(headers http.Header, key, value string) bool
- func HeaderLastValue(headers http.Header, key string) (string, bool)
- func Headers(from map[string]string) http.Header
- func HostHasPort(s string) bool
- func IsHTTPTokenRune(r rune) bool
- func IsValidMethod(method string) bool
- func LocalIP() string
- func MustParseSameSite(sameSite string) http.SameSite
- func MustParseURL(rawURL string) *url.URL
- func NestMiddleware(action http.HandlerFunc, middleware ...Middleware) http.HandlerFunc
- func NewHTTPRequestEventFilter(filter func(context.Context, HTTPRequestEvent) (HTTPRequestEvent, bool)) logger.Filter
- func NewHTTPRequestEventListener(listener func(context.Context, HTTPRequestEvent)) logger.Listener
- func NewMockRequest(method, path string) *http.Request
- func NewMockRequestWithCookie(method, path, cookieName, cookieValue string) *http.Request
- func NoFollowRedirects() func(req *http.Request, via []*http.Request) error
- func ParseSameSite(sameSite string) (http.SameSite, error)
- func PortFromBindAddr(bindAddr string) (port int32)
- func RemoveHostEmptyPort(host string) string
- func SchemeIsSecure(scheme string) bool
- func SplitColon(value string) (first, second string, err error)
- func TLSSecureCipherSuites(tlsConfig *tls.Config)
- func URLWithHost(u *url.URL, host string) *url.URL
- func URLWithPath(u *url.URL, path string) *url.URL
- func URLWithPort(u *url.URL, port string) *url.URL
- func URLWithQuery(u *url.URL, key, value string) *url.URL
- func URLWithRawQuery(u *url.URL, rawQuery string) *url.URL
- func URLWithScheme(u *url.URL, scheme string) *url.URL
- func WithClientHTTPTrace(req *http.Request, trace *HTTPTrace) *http.Request
- func WriteJSON(w http.ResponseWriter, statusCode int, response interface{}) error
- func WriteNoContent(w http.ResponseWriter) error
- func WriteRawContent(w http.ResponseWriter, statusCode int, content []byte) error
- func WriteXML(w http.ResponseWriter, statusCode int, response interface{}) error
- type CertInfo
- type DialOption
- type EventSource
- func (es *EventSource) Data(data string) error
- func (es *EventSource) Event(name string) error
- func (es *EventSource) EventData(name, data string) error
- func (es *EventSource) EventDataWithID(name, data, id string) error
- func (es *EventSource) Ping() error
- func (es *EventSource) StartSession() error
- type GZipResponseWriter
- func (crw *GZipResponseWriter) Close() error
- func (crw *GZipResponseWriter) ContentLength() int
- func (crw *GZipResponseWriter) Flush()
- func (crw *GZipResponseWriter) Header() http.Header
- func (crw *GZipResponseWriter) InnerResponse() http.ResponseWriter
- func (crw *GZipResponseWriter) StatusCode() int
- func (crw *GZipResponseWriter) Write(b []byte) (int, error)
- func (crw *GZipResponseWriter) WriteHeader(code int)
- type GracefulHTTPServer
- type GracefulHTTPServerOption
- type HTTPRequestEvent
- type HTTPRequestEventOption
- func OptHTTPRequestContentEncoding(contentEncoding string) HTTPRequestEventOption
- func OptHTTPRequestContentLength(contentLength int) HTTPRequestEventOption
- func OptHTTPRequestContentType(contentType string) HTTPRequestEventOption
- func OptHTTPRequestElapsed(elapsed time.Duration) HTTPRequestEventOption
- func OptHTTPRequestHeader(header http.Header) HTTPRequestEventOption
- func OptHTTPRequestRequest(req *http.Request) HTTPRequestEventOption
- func OptHTTPRequestRoute(route string) HTTPRequestEventOption
- func OptHTTPRequestStatusCode(statusCode int) HTTPRequestEventOption
- type HTTPServerOption
- func OptHTTPServerAddr(addr string) HTTPServerOption
- func OptHTTPServerBaseContext(baseContextProvider func(net.Listener) context.Context) HTTPServerOption
- func OptHTTPServerErrorLog(log *log.Logger) HTTPServerOption
- func OptHTTPServerHandler(handler http.Handler) HTTPServerOption
- func OptHTTPServerIdleTimeout(value time.Duration) HTTPServerOption
- func OptHTTPServerMaxHeaderBytes(value int) HTTPServerOption
- func OptHTTPServerReadHeaderTimeout(value time.Duration) HTTPServerOption
- func OptHTTPServerReadTimeout(value time.Duration) HTTPServerOption
- func OptHTTPServerTLSConfig(cfg *tls.Config) HTTPServerOption
- func OptHTTPServerWriteTimeout(value time.Duration) HTTPServerOption
- type HTTPTrace
- type HTTPTraceFinisher
- type HTTPTracer
- type Middleware
- type MockResponseWriter
- func (res *MockResponseWriter) Bytes() []byte
- func (res *MockResponseWriter) Close() error
- func (res *MockResponseWriter) ContentLength() int
- func (res *MockResponseWriter) Flush()
- func (res *MockResponseWriter) Header() http.Header
- func (res *MockResponseWriter) InnerResponse() http.ResponseWriter
- func (res *MockResponseWriter) StatusCode() int
- func (res *MockResponseWriter) Write(buffer []byte) (int, error)
- func (res *MockResponseWriter) WriteHeader(statusCode int)
- type PostedFile
- type PostedFileOption
- type PostedFilesOptions
- type RequestOption
- func OptBasicAuth(username, password string) RequestOption
- func OptBody(contents io.ReadCloser) RequestOption
- func OptBodyBytes(body []byte) RequestOption
- func OptContext(ctx context.Context) RequestOption
- func OptCookie(cookie *http.Cookie) RequestOption
- func OptCookieValue(key, value string) RequestOption
- func OptDelete() RequestOption
- func OptGet() RequestOption
- func OptHTTPClientTrace(ht *HTTPTrace) RequestOption
- func OptHeader(headers http.Header) RequestOption
- func OptHeaderValue(key, value string) RequestOption
- func OptJSONBody(obj interface{}) RequestOption
- func OptMethod(method string) RequestOption
- func OptPatch() RequestOption
- func OptPost() RequestOption
- func OptPostForm(postForm url.Values) RequestOption
- func OptPostFormValue(key, value string) RequestOption
- func OptPostedFiles(files ...PostedFile) RequestOption
- func OptPut() RequestOption
- func OptQuery(query url.Values) RequestOption
- func OptQueryValue(key, value string) RequestOption
- func OptQueryValueAdd(key, value string) RequestOption
- func OptXMLBody(obj interface{}) RequestOption
- type RequestOptions
- type ResponseWriter
- type StatusResponseWriter
- func (rw *StatusResponseWriter) Close() error
- func (rw *StatusResponseWriter) ContentLength() int
- func (rw *StatusResponseWriter) Flush()
- func (rw *StatusResponseWriter) Header() http.Header
- func (rw *StatusResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error)
- func (rw *StatusResponseWriter) InnerResponse() http.ResponseWriter
- func (rw *StatusResponseWriter) StatusCode() int
- func (rw *StatusResponseWriter) Write(b []byte) (int, error)
- func (rw *StatusResponseWriter) WriteHeader(code int)
- type TCPKeepAliveListener
- type Webhook
Constants ¶
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')
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".
const ( SchemeHTTP = "http" SchemeHTTPS = "https" SchemeSPDY = "spdy" )
Well known schemes
const ( HSTSMaxAgeFormat = "max-age=%d" HSTSIncludeSubDomains = "includeSubDomains" HSTSPreload = "preload" )
HSTS Cookie Fields
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" // ConnectionClose is the connection value of "close" ConnectionClose = "close" )
const ( ErrInvalidSameSite ex.Class = "invalid cookie same site string value" ErrParameterMissing ex.Class = "parameter missing" ErrInvalidSplitColonInput ex.Class = `split colon input string is not of the form "<first>:<second>"` )
Errors
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.
const ( // DefaultPostedFilesMaxMemory is the maximum post body size we will typically consume. DefaultPostedFilesMaxMemory = 67_108_864 //64mb )
const (
ErrNetWrite ex.Class = "network write error"
)
Errors
const (
FlagHTTPRequest = "http.request"
)
Logger flags
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 ¶
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.
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
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
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
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
DetectContentType generates the content type of a given file by path.
func ErrIsInvalidSameSite ¶ added in v1.20201204.1
ErrIsInvalidSameSite returns if an error is `ErrInvalidSameSite`
func ErrIsInvalidSplitColonInput ¶ added in v1.20201204.1
ErrIsInvalidSplitColonInput returns if an error is `ErrInvalidSplitColonInput`
func ErrIsParameterMissing ¶ added in v1.20201204.1
ErrIsParameterMissing returns if an error is `ErrParameterMissing`
func ErrIsUnauthorized ¶ added in v1.20201204.1
ErrIsUnauthorized returns if an error is `ErrUnauthorized`
func FormatHeaders ¶ added in v1.20201204.1
FormatHeaders formats headers for output. Header keys will be printed in alphabetic order.
func GetContentEncoding ¶ added in v1.20201204.1
GetContentEncoding gets the content type out of a header collection.
func GetContentType ¶ added in v1.20201204.1
GetContentType gets the content type out of a header collection.
func GetProto ¶
GetProto gets the request proto. X-FORWARDED-PROTO is checked first, then the original request proto is used.
func GetRemoteAddr ¶
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 ¶
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
HeaderAny returns if any pieces of a header match a given value.
func HeaderLastValue ¶ added in v1.1.1
HeaderLastValue returns the last value of a potential csv of headers.
func HostHasPort ¶ added in v1.20201204.1
HostHasPort returns true if a string is in the form "host:port", or "[ipv6::address]:port".
func IsHTTPTokenRune ¶ added in v1.20201204.1
IsHTTPTokenRune returns if a rune is in the http valid rune table.
func IsValidMethod ¶ added in v1.20201204.1
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 MustParseSameSite ¶ added in v1.20201204.1
MustParseSameSite parses a string value for same site and panics on error.
func MustParseURL ¶
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 ¶
NewMockRequest creates a mock request.
func NewMockRequestWithCookie ¶
NewMockRequestWithCookie creates a mock request with a cookie attached to it.
func NoFollowRedirects ¶ added in v1.20201204.1
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
ParseSameSite parses a string value for same site.
func PortFromBindAddr ¶
PortFromBindAddr returns a port number as an integer from a bind addr.
func RemoveHostEmptyPort ¶ added in v1.20201204.1
RemoveHostEmptyPort strips the empty port in ":port" to "" as mandated by RFC 3986 Section 6.2.3.
func SchemeIsSecure ¶ added in v1.20210104.2
SchemeIsSecure returns if a given scheme is secure.
This is typically used for the `Secure` flag on cookies.
func SplitColon ¶ added in v1.20201204.1
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
TLSSecureCipherSuites sets the tls config to use secure cipher suites.
func URLWithHost ¶
URLWithHost returns a copy url with a given host.
func URLWithPath ¶
URLWithPath returns a copy url with a given path.
func URLWithPort ¶ added in v0.2.0
URLWithPort returns a copy url with a given pprt attached to the host.
func URLWithQuery ¶ added in v0.2.0
URLWithQuery returns a copy url with a given raw query.
func URLWithRawQuery ¶
URLWithRawQuery returns a copy url with a given raw query.
func URLWithScheme ¶
URLWithScheme returns a copy url with a given scheme.
func WithClientHTTPTrace ¶ added in v1.20210103.1
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.
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
ParseCertInfo returns a new cert info from a response from a check.
type DialOption ¶ added in v1.20201204.1
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
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
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
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) ContentLength ¶
func (res *MockResponseWriter) ContentLength() int
ContentLength returns the content length.
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
PostedFile is a file that has been posted to an hc endpoint.
func PostedFiles ¶ added in v1.20201204.1
func PostedFiles(r *http.Request, opts ...PostedFileOption) ([]PostedFile, error)
PostedFiles returns any files posted to the request.
The files are held in memory, if you need to stream the files out because they may be large, you should use the `*net/http.Request.FormFile(...)` function directly instead of this method.
type PostedFileOption ¶ added in v1.20210815.2
type PostedFileOption func(*PostedFilesOptions)
PostedFileOption mutates posted file options.
func OptPostedFilesMaxMemory ¶ added in v1.20210815.2
func OptPostedFilesMaxMemory(maxMemory int64) PostedFileOption
OptPostedFilesMaxMemory sets the max memory for the posted files options (defaults to 64mb).
func OptPostedFilesParseForm ¶ added in v1.20210815.2
func OptPostedFilesParseForm(parseForm bool) PostedFileOption
OptPostedFilesParseForm sets if we should parse the post form for files (defaults to false).
func OptPostedFilesParseMultipartForm ¶ added in v1.20210815.2
func OptPostedFilesParseMultipartForm(parseMultipartForm bool) PostedFileOption
OptPostedFilesParseMultipartForm sets if we should parse the multipart form for files (defaults to true).
type PostedFilesOptions ¶ added in v1.20210815.2
PostedFilesOptions are options for the PostedFiles function.
type RequestOption ¶ added in v1.20201204.1
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 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 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 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 OptQueryValueAdd ¶ added in v1.20210402.2
func OptQueryValueAdd(key, value string) RequestOption
OptQueryValueAdd adds 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.
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
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) MethodOrDefault ¶ added in v1.20201204.1
MethodOrDefault returns the method or a default.
Source Files ¶
- cert_info.go
- constants.go
- decode_basic_auth.go
- detect_content_type.go
- dial_option.go
- doc.go
- errors.go
- etag.go
- event_source.go
- get_content_encoding.go
- get_content_type.go
- get_host.go
- get_port.go
- get_proto.go
- get_remoteaddr.go
- get_useragent.go
- graceful_http_server.go
- gzip_response_writer.go
- header_util.go
- http_logged.go
- http_request_event.go
- http_server_option.go
- http_trace.go
- https_redirect.go
- is_valid_method.go
- local_ip.go
- logging_util.go
- middleware.go
- mock_request.go
- mock_response.go
- no_follow_redirects.go
- parse_same_site.go
- port_bind_addr.go
- posted_files.go
- remove_host_empty_port.go
- request_option.go
- response_writer.go
- scheme_is_secure.go
- secure_cipher_suites.go
- split_colon.go
- status_response_writer.go
- tcp_keep_alive_listener.go
- tracer.go
- url.go
- webhook.go
- write_helpers.go