webutil

package
v1.1.1 Latest Latest
Warning

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

Go to latest
Published: Feb 5, 2019 License: MIT Imports: 15 Imported by: 4

Documentation

Index

Constants

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

Well known schemes

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"

	// 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"

	// 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"

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

Variables

View Source
var (
	// RFC7239 defines a new "Forwarded: " header designed to replace the
	// existing use of X-Forwarded-* headers.
	// e.g. Forwarded: for=192.0.2.60;proto=https;by=203.0.113.43
	HeaderForwarded               = http.CanonicalHeaderKey("Forwarded")
	HeaderXForwardedFor           = http.CanonicalHeaderKey("X-Forwarded-For")
	HeaderXForwardedPort          = http.CanonicalHeaderKey("X-Forwarded-Port")
	HeaderXForwardedHost          = http.CanonicalHeaderKey("X-Forwarded-Host")
	HeaderXForwardedProto         = http.CanonicalHeaderKey("X-Forwarded-Proto")
	HeaderXForwardedScheme        = http.CanonicalHeaderKey("X-Forwarded-Scheme")
	HeaderXRealIP                 = http.CanonicalHeaderKey("X-Real-IP")
	HeaderAcceptEncoding          = http.CanonicalHeaderKey("Accept-Encoding")
	HeaderSetCookie               = http.CanonicalHeaderKey("Set-Cookie")
	HeaderCookie                  = http.CanonicalHeaderKey("Cookie")
	HeaderDate                    = http.CanonicalHeaderKey("Date")
	HeaderCacheControl            = http.CanonicalHeaderKey("Cache-Control")
	HeaderConnection              = http.CanonicalHeaderKey("Connection")
	HeaderContentEncoding         = http.CanonicalHeaderKey("Content-Encoding")
	HeaderContentLength           = http.CanonicalHeaderKey("Content-Length")
	HeaderContentType             = http.CanonicalHeaderKey("Content-Type")
	HeaderUserAgent               = http.CanonicalHeaderKey("User-Agent")
	HeaderServer                  = http.CanonicalHeaderKey("Server")
	HeaderVary                    = http.CanonicalHeaderKey("Vary")
	HeaderXServedBy               = http.CanonicalHeaderKey("X-Served-By")
	HeaderXFrameOptions           = http.CanonicalHeaderKey("X-Frame-Options")
	HeaderXXSSProtection          = http.CanonicalHeaderKey("X-Xss-Protection")
	HeaderXContentTypeOptions     = http.CanonicalHeaderKey("X-Content-Type-Options")
	HeaderStrictTransportSecurity = http.CanonicalHeaderKey("Strict-Transport-Security")
)

canonical header names.

View Source
var (
	// ErrURLUnset is a (hopefully) uncommon error.
	ErrURLUnset = exception.Class("request url unset")

	// DefaultRequestTimeout is the default webhook timeout.
	DefaultRequestTimeout = 10 * time.Second

	// DefaultRequestMethod is the default webhook method.
	DefaultRequestMethod = "POST"
)

Functions

func DeserializeReaderAsJSON

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

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

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 first 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 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 LocalIP

func LocalIP() string

LocalIP returns the local server ip.

func MustParseURL

func MustParseURL(rawURL string) *url.URL

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

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 PortFromBindAddr

func PortFromBindAddr(bindAddr string) (port int32)

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

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 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 GracefulServer added in v1.1.1

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

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

func NewGracefulServer added in v1.1.1

func NewGracefulServer(server *http.Server) *GracefulServer

NewGracefulServer returns a new graceful server.

func (*GracefulServer) Listener added in v1.1.1

func (gs *GracefulServer) Listener() net.Listener

Listener returns the listener.

func (*GracefulServer) NotifyStarted added in v1.1.1

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

NotifyStarted implements graceful.Graceful.NotifyStarted.

func (*GracefulServer) NotifyStopped added in v1.1.1

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

NotifyStopped implements graceful.Graceful.NotifyStopped.

func (*GracefulServer) ShutdownGracePeriod added in v1.1.1

func (gs *GracefulServer) ShutdownGracePeriod() time.Duration

ShutdownGracePeriod returns the shutdown graceperiod or a default.

func (*GracefulServer) Start added in v1.1.1

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

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

func (*GracefulServer) Stop added in v1.1.1

func (gs *GracefulServer) Stop() error

Stop implements graceful.Graceful.Stop.

func (*GracefulServer) WithListener added in v1.1.1

func (gs *GracefulServer) WithListener(l net.Listener) *GracefulServer

WithListener sets the server listener.

func (*GracefulServer) WithShutdownGracePeriod added in v1.1.1

func (gs *GracefulServer) WithShutdownGracePeriod(d time.Duration) *GracefulServer

WithShutdownGracePeriod sets the shutdown grace period.

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() error

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 RequestSender

type RequestSender struct {
	*url.URL
	// contains filtered or unexported fields
}

RequestSender is a slack webhook sender.

func NewRequestSender

func NewRequestSender(destination *url.URL) *RequestSender

NewRequestSender creates a new request sender.

A request sender is a sepcialized request factory that makes request to a single endpoint.

It is useful when calling out to predefined things like webhooks.

You can send either raw bytes as the contents.

func (*RequestSender) Client

func (rs *RequestSender) Client() *http.Client

Client returns the underlying client.

func (*RequestSender) Close

func (rs *RequestSender) Close() bool

Close returns if we should close the connection.

func (*RequestSender) Headers

func (rs *RequestSender) Headers() http.Header

Headers returns the headers.

func (*RequestSender) Method

func (rs *RequestSender) Method() string

Method is the request method. It defaults to "POST".

func (*RequestSender) Send

func (rs *RequestSender) Send() (*http.Response, error)

Send sends a request to the destination without a payload.

func (*RequestSender) SendBytes

func (rs *RequestSender) SendBytes(ctx context.Context, contents []byte) (*http.Response, error)

SendBytes sends a message to the webhook with a given msg body as raw bytes.

func (*RequestSender) SendJSON

func (rs *RequestSender) SendJSON(ctx context.Context, contents interface{}) (*http.Response, error)

SendJSON sends a message to the webhook with a given msg body as json.

func (*RequestSender) Tracer

func (rs *RequestSender) Tracer() RequestTracer

Tracer returns the request tracer.

func (*RequestSender) Transport

func (rs *RequestSender) Transport() *http.Transport

Transport returns the transport.

func (*RequestSender) WithClose

func (rs *RequestSender) WithClose(close bool) *RequestSender

WithClose sets if we should close the connection.

func (*RequestSender) WithHeader

func (rs *RequestSender) WithHeader(key, value string) *RequestSender

WithHeader adds an individual header.

func (*RequestSender) WithHeaders

func (rs *RequestSender) WithHeaders(headers http.Header) *RequestSender

WithHeaders sets headers.

func (*RequestSender) WithMethod

func (rs *RequestSender) WithMethod(method string) *RequestSender

WithMethod sets the request method (defaults to POST).

func (*RequestSender) WithTracer

func (rs *RequestSender) WithTracer(tracer RequestTracer) *RequestSender

WithTracer sets the request tracer.

func (*RequestSender) WithTransport

func (rs *RequestSender) WithTransport(transport *http.Transport) *RequestSender

WithTransport sets the transport.

type RequestTraceFinisher

type RequestTraceFinisher interface {
	Finish(*http.Request, *http.Response, error)
}

RequestTraceFinisher is a finisher for request traces.

type RequestTracer

type RequestTracer interface {
	Start(*http.Request) RequestTraceFinisher
}

RequestTracer is a tracer for requests.

Jump to

Keyboard shortcuts

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