Documentation
¶
Overview ¶
Package request implements helpers ontop of net/http.Client. It is designed to enable thorough testing of apps through mocked responses (which can be injected optionally).
Index ¶
- Constants
- func ClearMockedResponses()
- func MockCatchAll(generator MockedResponseGenerator)
- func MockResponse(req *Request, generator MockedResponseGenerator)
- func MockResponseFromBinary(req *Request, statusCode int, responseBody []byte)
- func MockResponseFromFile(verb string, url string, statusCode int, responseFilePath string)
- func MockResponseFromString(verb string, url string, statusCode int, responseBody string)
- func NewRequestListener(listener func(Event)) logger.Listener
- type CertInfo
- type Deserializer
- type Event
- type Factory
- func (m Factory) Create() *Request
- func (m Factory) Get(url string) (*Request, error)
- func (m Factory) Post(url string, body []byte) (*Request, error)
- func (m *Factory) WithLogger(log *logger.Logger) *Factory
- func (m *Factory) WithMockedResponseProvider(mrp MockedResponseProvider) *Factory
- func (m *Factory) WithOnRequest(handler Handler) *Factory
- func (m *Factory) WithOnResponse(handler ResponseHandler) *Factory
- func (m *Factory) WithTracer(tracer Tracer) *Factory
- type HTTPTrace
- type Handler
- type Meta
- type MockedResponse
- type MockedResponseGenerator
- type MockedResponseProvider
- type PostedFile
- type Request
- func (r *Request) ApplyTransport(transport *http.Transport) error
- func (r *Request) AsDelete() *Request
- func (r *Request) AsGet() *Request
- func (r *Request) AsOptions() *Request
- func (r *Request) AsPatch() *Request
- func (r *Request) AsPost() *Request
- func (r *Request) AsPut() *Request
- func (r *Request) BasicAuth() (username, password string)
- func (r *Request) Bytes() ([]byte, error)
- func (r *Request) BytesWithMeta() ([]byte, *ResponseMeta, error)
- func (r *Request) ClientTrace() *httptrace.ClientTrace
- func (r *Request) ContentType() string
- func (r *Request) Context() context.Context
- func (r *Request) Deserialized(deserialize Deserializer) (*ResponseMeta, error)
- func (r *Request) DialTimeout() time.Duration
- func (r *Request) DisableCompression() bool
- func (r *Request) Discard() error
- func (r *Request) DiscardWithMeta() (*ResponseMeta, error)
- func (r *Request) Equals(other *Request) bool
- func (r *Request) Execute() error
- func (r *Request) ExecuteWithMeta() (*ResponseMeta, error)
- func (r *Request) Hash() uint32
- func (r *Request) Header() http.Header
- func (r *Request) Headers() http.Header
- func (r *Request) Host() string
- func (r *Request) JSON(destination interface{}) error
- func (r *Request) JSONError(errorObject interface{}) (*ResponseMeta, error)
- func (r *Request) JSONWithErrorHandler(successObject interface{}, errorObject interface{}) (*ResponseMeta, error)
- func (r *Request) JSONWithMeta(destination interface{}) (*ResponseMeta, error)
- func (r *Request) KeepAlive() bool
- func (r *Request) KeepAliveTimeout() time.Duration
- func (r *Request) Logger() *logger.Logger
- func (r *Request) Meta() *Meta
- func (r *Request) Method() string
- func (r *Request) MockProvider() MockedResponseProvider
- func (r *Request) MustWithRawURL(rawURL string) *Request
- func (r *Request) MustWithRawURLf(format string, args ...interface{}) *Request
- func (r *Request) Path() string
- func (r *Request) PostBody() []byte
- func (r *Request) Request() (*http.Request, error)
- func (r *Request) RequestHandler() Handler
- func (r *Request) RequiresTransport() bool
- func (r *Request) Response() (res *http.Response, err error)
- func (r *Request) ResponseHandler() ResponseHandler
- func (r *Request) ResponseHeaderTimeout() time.Duration
- func (r *Request) Scheme() string
- func (r *Request) State() interface{}
- func (r *Request) String() (string, error)
- func (r *Request) StringWithMeta() (string, *ResponseMeta, error)
- func (r *Request) TLSHandshakeTimeout() time.Duration
- func (r *Request) TLSSkipVerify() bool
- func (r *Request) Timeout() time.Duration
- func (r *Request) Tracer() Tracer
- func (r *Request) Transport() *http.Transport
- func (r *Request) URL() *url.URL
- func (r *Request) WithBasicAuth(username, password string) *Request
- func (r *Request) WithClientTrace(trace *httptrace.ClientTrace) *Request
- func (r *Request) WithContentType(contentType string) *Request
- func (r *Request) WithContext(ctx context.Context) *Request
- func (r *Request) WithCookie(cookie *http.Cookie) *Request
- func (r *Request) WithDialTimeout(timeout time.Duration) *Request
- func (r *Request) WithDisableCompression(value bool) *Request
- func (r *Request) WithHeader(field string, value string) *Request
- func (r *Request) WithHost(host string) *Request
- func (r *Request) WithKeepAlive() *Request
- func (r *Request) WithKeepAliveTimeout(timeout time.Duration) *Request
- func (r *Request) WithLogger(log *logger.Logger) *Request
- func (r *Request) WithMethod(verb string) *Request
- func (r *Request) WithMockProvider(provider MockedResponseProvider) *Request
- func (r *Request) WithPath(path string) *Request
- func (r *Request) WithPathf(format string, args ...interface{}) *Request
- func (r *Request) WithPostBody(body []byte) *Request
- func (r *Request) WithPostBodyAsJSON(object interface{}) *Request
- func (r *Request) WithPostBodyAsXML(object interface{}) *Request
- func (r *Request) WithPostBodySerialized(object interface{}, serialize Serializer) *Request
- func (r *Request) WithPostData(field string, value string) *Request
- func (r *Request) WithPostedFile(key, fileName string, fileContents io.Reader) *Request
- func (r *Request) WithQueryString(field string, value string) *Request
- func (r *Request) WithRawURL(rawURL string) (*Request, error)
- func (r *Request) WithRawURLf(format string, args ...interface{}) (*Request, error)
- func (r *Request) WithRequestHandler(handler Handler) *Request
- func (r *Request) WithResponseHandler(listener ResponseHandler) *Request
- func (r *Request) WithResponseHeaderTimeout(timeout time.Duration) *Request
- func (r *Request) WithScheme(scheme string) *Request
- func (r *Request) WithState(state interface{}) *Request
- func (r *Request) WithTLSClientCert(cert []byte) *Request
- func (r *Request) WithTLSClientKey(key []byte) *Request
- func (r *Request) WithTLSHandshakeTimeout(timeout time.Duration) *Request
- func (r *Request) WithTLSRootCAPool(certPool *x509.CertPool) *Request
- func (r *Request) WithTLSSkipVerify(skipVerify bool) *Request
- func (r *Request) WithTimeout(timeout time.Duration) *Request
- func (r *Request) WithTracer(tracer Tracer) *Request
- func (r *Request) WithTransport(transport *http.Transport) *Request
- func (r *Request) WithURL(target *url.URL) *Request
- func (r *Request) XML(destination interface{}) error
- func (r *Request) XMLWithErrorHandler(successObject interface{}, errorObject interface{}) (*ResponseMeta, error)
- func (r *Request) XMLWithMeta(destination interface{}) (*ResponseMeta, error)
- type ResponseEvent
- func (re ResponseEvent) Body() []byte
- func (re ResponseEvent) Flag() logger.Flag
- func (re ResponseEvent) Request() *Meta
- func (re ResponseEvent) Response() *ResponseMeta
- func (re ResponseEvent) Timestamp() time.Time
- func (re ResponseEvent) WriteJSON() logger.JSONObj
- func (re ResponseEvent) WriteText(tf logger.TextFormatter, buf *bytes.Buffer)
- type ResponseHandler
- type ResponseMeta
- type Serializer
- type TraceFinisher
- type Tracer
Constants ¶
const ( // ErrMultipleBodySources is an error returned if a request has both the post body and post data set. ErrMultipleBodySources = exception.Class("Cannot set both `Body` and `Post Data`") // ErrRequiresTransport is an error michael turner is going to hate. ErrRequiresTransport = exception.Class("Request settings require a http.Transport to be provided") )
const ( // DefaultKeepAlive returns if we should use a keep alive by default. DefaultKeepAlive = false // DefaultKeepAliveTimeout is the default time to keep idle connections open before they're closed. DefaultKeepAliveTimeout = 60 * time.Second )
const ( // MethodGet is a method. MethodGet = "GET" // MethodPost is a method. MethodPost = "POST" // MethodPut is a method. MethodPut = "PUT" // MethodPatch is a method. MethodPatch = "PATCH" // MethodDelete is a method. MethodDelete = "DELETE" // MethodOptions is a method. MethodOptions = "OPTIONS" )
const ( // HeaderConnection is a http header. HeaderConnection = "Connection" // HeaderContentType is a http header. HeaderContentType = "Content-Type" )
const ( // ContentTypeApplicationJSON is a content type header value. 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" )
const ( // Flag is a logger event flag. Flag logger.Flag = "request" // FlagResponse is a logger event flag. FlagResponse logger.Flag = "request.response" )
const (
// ConnectionKeepAlive is a connection header value.
ConnectionKeepAlive = "keep-alive"
)
Variables ¶
This section is empty.
Functions ¶
func ClearMockedResponses ¶
func ClearMockedResponses()
ClearMockedResponses clears any mocked responses that have been set up for the test.
func MockCatchAll ¶
func MockCatchAll(generator MockedResponseGenerator)
MockCatchAll sets a "catch all" mock generator.
func MockResponse ¶
func MockResponse(req *Request, generator MockedResponseGenerator)
MockResponse mocks are response with a given generator.
func MockResponseFromBinary ¶
MockResponseFromBinary mocks a service request response from a set of binary responses.
func MockResponseFromFile ¶
MockResponseFromFile mocks a service request response from a set of file paths.
func MockResponseFromString ¶
MockResponseFromString mocks a service request response from a string responseBody.
func NewRequestListener ¶
NewRequestListener creates a new request listener.
Types ¶
type CertInfo ¶
type CertInfo struct {
IssuerCommonName string `json:"issuerCommonName" yaml:"issuerCommonName"`
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 NewCertInfo ¶
NewCertInfo returns a new cert info from a response.
type Deserializer ¶
Deserializer is a function that does things with the response body.
type Event ¶
type Event struct {
// contains filtered or unexported fields
}
Event is a logger event for outgoing requests.
type Factory ¶
type Factory struct {
Log *logger.Logger
MockedResponseProvider MockedResponseProvider
OnRequest Handler
OnResponse ResponseHandler
Tracer Tracer
}
Factory is a helper to create requests with common metadata. It is generally for creating requests to *any* host.
func (*Factory) WithLogger ¶
WithLogger sets the logger.
func (*Factory) WithMockedResponseProvider ¶
func (m *Factory) WithMockedResponseProvider(mrp MockedResponseProvider) *Factory
WithMockedResponseProvider sets the mocked response provider.
func (*Factory) WithOnRequest ¶
WithOnRequest sets the on request handler..
func (*Factory) WithOnResponse ¶
func (m *Factory) WithOnResponse(handler ResponseHandler) *Factory
WithOnResponse sets the on response handler.
func (*Factory) WithTracer ¶
WithTracer sets the tracer.
type HTTPTrace ¶
type HTTPTrace struct {
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 ¶
func (ht *HTTPTrace) Trace() *httptrace.ClientTrace
Trace returns the trace binder.
type Meta ¶
Meta is a summary of the request meta useful for logging.
func NewRequestMeta ¶
NewRequestMeta returns a new meta object for a request.
type MockedResponse ¶
type MockedResponse struct {
Meta ResponseMeta
Res []byte
Err error
}
MockedResponse is the metadata and response body for a response
func MockedResponseInjector ¶
func MockedResponseInjector(req *Request) *MockedResponse
MockedResponseInjector injects the mocked response into the request response.
func (MockedResponse) Response ¶
func (mr MockedResponse) Response() *http.Response
Response returns a response object for the mock response.
type MockedResponseGenerator ¶
type MockedResponseGenerator func(*Request) MockedResponse
MockedResponseGenerator is a function that returns a mocked response.
type MockedResponseProvider ¶
type MockedResponseProvider func(*Request) *MockedResponse
MockedResponseProvider is a mocked response provider.
type PostedFile ¶
PostedFile represents a file to post with the request.
type Request ¶
type Request struct {
// contains filtered or unexported fields
}
Request makes http requests.
func (*Request) ApplyTransport ¶
ApplyTransport applies the request settings to a transport.
func (*Request) BytesWithMeta ¶
func (r *Request) BytesWithMeta() ([]byte, *ResponseMeta, error)
BytesWithMeta fetches the response as bytes with meta.
func (*Request) ClientTrace ¶
func (r *Request) ClientTrace() *httptrace.ClientTrace
ClientTrace returns the diagnostics trace object.
func (*Request) ContentType ¶
ContentType returns the request content type.
func (*Request) Deserialized ¶
func (r *Request) Deserialized(deserialize Deserializer) (*ResponseMeta, error)
Deserialized runs a deserializer with the response.
func (*Request) DialTimeout ¶
DialTimeout returns the request dial timeout.
func (*Request) DisableCompression ¶
DisableCompression returns if the requests transport should disable compression.
func (*Request) Discard ¶
Discard executes the request does not pass the response to handlers or events.
func (*Request) DiscardWithMeta ¶
func (r *Request) DiscardWithMeta() (*ResponseMeta, error)
DiscardWithMeta discards the response but triggers listeners.
func (*Request) ExecuteWithMeta ¶
func (r *Request) ExecuteWithMeta() (*ResponseMeta, error)
ExecuteWithMeta makes the request and returns the meta of the response.
func (*Request) JSONError ¶
func (r *Request) JSONError(errorObject interface{}) (*ResponseMeta, error)
JSONError unmarshals the response as json to an object if the meta indiciates an error.
func (*Request) JSONWithErrorHandler ¶
func (r *Request) JSONWithErrorHandler(successObject interface{}, errorObject interface{}) (*ResponseMeta, error)
JSONWithErrorHandler unmarshals the response as json to an object with metadata or an error object depending on the meta.
func (*Request) JSONWithMeta ¶
func (r *Request) JSONWithMeta(destination interface{}) (*ResponseMeta, error)
JSONWithMeta unmarshals the response as json to an object with metadata.
func (*Request) KeepAliveTimeout ¶
KeepAliveTimeout returns the keep alive timeout, ro the time before idle connections are closed.
func (*Request) MockProvider ¶
func (r *Request) MockProvider() MockedResponseProvider
MockProvider returns the request mock provider.
func (*Request) MustWithRawURL ¶
MustWithRawURL sets the request target url whole hog.
func (*Request) MustWithRawURLf ¶
MustWithRawURLf sets the url based on a format and args.
func (*Request) RequestHandler ¶
RequestHandler returns the request handler.
func (*Request) RequiresTransport ¶
RequiresTransport returns if there are request settings that require a shared transport.
func (*Request) Response ¶
Response makes the actual request but returns the underlying http.Response object.
func (*Request) ResponseHandler ¶
func (r *Request) ResponseHandler() ResponseHandler
ResponseHandler returns the request response handler.
func (*Request) ResponseHeaderTimeout ¶
ResponseHeaderTimeout returns a timeout.
func (*Request) StringWithMeta ¶
func (r *Request) StringWithMeta() (string, *ResponseMeta, error)
StringWithMeta returns the body of the response as a string in addition to the response metadata.
func (*Request) TLSHandshakeTimeout ¶
TLSHandshakeTimeout returns a timeout.
func (*Request) TLSSkipVerify ¶
TLSSkipVerify returns if we should skip server tls verification.
func (*Request) WithBasicAuth ¶
WithBasicAuth sets the basic auth headers for a request.
func (*Request) WithClientTrace ¶
func (r *Request) WithClientTrace(trace *httptrace.ClientTrace) *Request
WithClientTrace sets up a trace for the request.
func (*Request) WithContentType ¶
WithContentType sets the `Content-Type` header for the request.
func (*Request) WithContext ¶
WithContext sets a context for the request.
func (*Request) WithCookie ¶
WithCookie sets a cookie for the request.
func (*Request) WithDialTimeout ¶
WithDialTimeout sets a dial timeout for the request.
func (*Request) WithDisableCompression ¶
WithDisableCompression sets the disable compression value.
func (*Request) WithHeader ¶
WithHeader sets a header on the request.
func (*Request) WithKeepAlive ¶
WithKeepAlive sets if the request should use the `Connection=keep-alive` header or not.
func (*Request) WithKeepAliveTimeout ¶
WithKeepAliveTimeout sets a keep alive timeout for the requests transport.
func (*Request) WithLogger ¶
WithLogger enables logging with HTTPRequestLogLevelErrors.
func (*Request) WithMethod ¶
WithMethod sets the http verb/method of the request.
func (*Request) WithMockProvider ¶
func (r *Request) WithMockProvider(provider MockedResponseProvider) *Request
WithMockProvider mocks a request response.
func (*Request) WithPathf ¶
WithPathf sets the path component of the host url by the format and arguments.
func (*Request) WithPostBody ¶
WithPostBody sets the post body directly.
func (*Request) WithPostBodyAsJSON ¶
WithPostBodyAsJSON sets the post body raw to be the json representation of an object.
func (*Request) WithPostBodyAsXML ¶
WithPostBodyAsXML sets the post body raw to be the xml representation of an object.
func (*Request) WithPostBodySerialized ¶
func (r *Request) WithPostBodySerialized(object interface{}, serialize Serializer) *Request
WithPostBodySerialized sets the post body with the results of the given serializer.
func (*Request) WithPostData ¶
WithPostData sets a post data value for the request.
func (*Request) WithPostedFile ¶
WithPostedFile adds a posted file to the multipart form elements of the request.
func (*Request) WithQueryString ¶
WithQueryString sets a query string value for the host url of the request.
func (*Request) WithRawURL ¶
WithRawURL sets the request target url whole hog.
func (*Request) WithRawURLf ¶
WithRawURLf sets the url based on a format and args.
func (*Request) WithRequestHandler ¶
WithRequestHandler configures an event receiver.
func (*Request) WithResponseHandler ¶
func (r *Request) WithResponseHandler(listener ResponseHandler) *Request
WithResponseHandler configures an event receiver.
func (*Request) WithResponseHeaderTimeout ¶
WithResponseHeaderTimeout sets a timeout
func (*Request) WithScheme ¶
WithScheme sets the scheme, or protocol, of the request.
func (*Request) WithTLSClientCert ¶
WithTLSClientCert sets a tls cert on the transport for the request.
func (*Request) WithTLSClientKey ¶
WithTLSClientKey sets a tls key on the transport for the request.
func (*Request) WithTLSHandshakeTimeout ¶
WithTLSHandshakeTimeout sets a timeout
func (*Request) WithTLSRootCAPool ¶
WithTLSRootCAPool sets the root TLS ca pool for the request.
func (*Request) WithTLSSkipVerify ¶
WithTLSSkipVerify skips the bad certificate checking on TLS requests.
func (*Request) WithTimeout ¶
WithTimeout sets a timeout for the request. This timeout enforces the time between the start of the connection dial to the first response byte.
func (*Request) WithTracer ¶
WithTracer sets the request tracer.
func (*Request) WithTransport ¶
WithTransport sets a transport for the request.
func (*Request) XMLWithErrorHandler ¶
func (r *Request) XMLWithErrorHandler(successObject interface{}, errorObject interface{}) (*ResponseMeta, error)
XMLWithErrorHandler unmarshals the response as xml to an object with metadata or an error object depending on the meta.
func (*Request) XMLWithMeta ¶
func (r *Request) XMLWithMeta(destination interface{}) (*ResponseMeta, error)
XMLWithMeta unmarshals the response as xml to an object with metadata.
type ResponseEvent ¶
type ResponseEvent struct {
// contains filtered or unexported fields
}
ResponseEvent is a response to outgoing requests.
func (ResponseEvent) Body ¶
func (re ResponseEvent) Body() []byte
Body returns the outgoing request body.
func (ResponseEvent) Request ¶
func (re ResponseEvent) Request() *Meta
Request returns the request meta.
func (ResponseEvent) Response ¶
func (re ResponseEvent) Response() *ResponseMeta
Response returns the response meta.
func (ResponseEvent) Timestamp ¶
func (re ResponseEvent) Timestamp() time.Time
Timestamp returns the event timestamp.
func (ResponseEvent) WriteJSON ¶
func (re ResponseEvent) WriteJSON() logger.JSONObj
WriteJSON implements logger.JSONWritable.
func (ResponseEvent) WriteText ¶
func (re ResponseEvent) WriteText(tf logger.TextFormatter, buf *bytes.Buffer)
WriteText writes the event to a text writer.
type ResponseHandler ¶
type ResponseHandler func(req *Request, res *ResponseMeta, content []byte)
ResponseHandler is a receiver for `OnResponse`.
type ResponseMeta ¶
type ResponseMeta struct {
Cert *CertInfo
CompleteTime time.Time
StatusCode int
ContentLength int64
ContentEncoding string
ContentType string
Headers http.Header
}
ResponseMeta is just the meta information for an http response.
func NewResponseMeta ¶
func NewResponseMeta(res *http.Response) *ResponseMeta
NewResponseMeta returns a new meta object for a response.
type Serializer ¶
Serializer is a function that turns an object into raw data.
type TraceFinisher ¶
type TraceFinisher interface {
Finish(*http.Request, *ResponseMeta, error)
}
TraceFinisher is a finisher for traces.
type Tracer ¶
type Tracer interface {
Start(*http.Request) TraceFinisher
}
Tracer is a tracer for requests.