request

package
v1.0.0-b001 Latest Latest
Warning

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

Go to latest
Published: Apr 26, 2018 License: MIT Imports: 20 Imported by: 0

README

request

This is a simple convenience library for making service requests and deserializing the results to objects either from JSON or from XML.

Usage

Here is an exmple of fetching an object:

myObject := MyObject{}
reqErr := request.NewRequest().AsGet().WithUrl("http://myservice.com/api/foo").JSON(&myObject)

Here is an example of fetching a raw response:

res, res_err := request.New().AsGet().WithUrl(host).WithTimeout(5000).FetchRawResponse()
defer res.Body.Close()
//... do things with the raw body ...

Documentation

Index

Constants

View Source
const (
	// Flag is a logger event flag.
	Flag logger.Flag = "request"
	// FlagResponse is a logger event flag.
	FlagResponse logger.Flag = "request.response"
)

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

func MockResponseFromBinary(req *Request, statusCode int, responseBody []byte)

MockResponseFromBinary mocks a service request response from a set of binary responses.

func MockResponseFromFile

func MockResponseFromFile(verb string, url string, statusCode int, responseFilePath string)

MockResponseFromFile mocks a service request response from a set of file paths.

func MockResponseFromString

func MockResponseFromString(verb string, url string, statusCode int, responseBody string)

MockResponseFromString mocks a service request response from a string responseBody.

func NewRequestListener

func NewRequestListener(listener func(Event)) logger.Listener

NewRequestListener creates a new request listener.

Types

type Buffer

type Buffer interface {
	Write([]byte) (int, error)
	Len() int64
	ReadFrom(io.ReadCloser) (int64, error)
	Bytes() []byte
}

Buffer is a type that supplies two methods found on bytes.Buffer.

type CertInfo

type CertInfo struct {
	IssuerCommonName string
	DNSNames         []string
	NotAfter         time.Time
	NotBefore        time.Time
}

CertInfo is the information for a certificate.

func NewCertInfo

func NewCertInfo(res *http.Response) *CertInfo

NewCertInfo returns a new cert info from a response.

type CreateTransportHandler

type CreateTransportHandler func(host *url.URL, transport *http.Transport)

CreateTransportHandler is a receiver for `OnCreateTransport`.

type Deserializer

type Deserializer func(body []byte) error

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.

func (Event) Flag

func (re Event) Flag() logger.Flag

Flag returns the event flag.

func (Event) Request

func (re Event) Request() *Meta

Request returns the request meta.

func (Event) Timestamp

func (re Event) Timestamp() time.Time

Timestamp returns the event timestamp.

func (Event) WriteJSON

func (re Event) WriteJSON() logger.JSONObj

WriteJSON implements logger.JSONWritable.

func (Event) WriteText

func (re Event) WriteText(tf logger.TextFormatter, buf *bytes.Buffer)

WriteText writes an outgoing request as text to a given buffer.

type Meta

type Meta struct {
	StartTime time.Time
	Verb      string
	URL       *url.URL
	Headers   http.Header
	Body      []byte
}

Meta is a summary of the request meta useful for logging.

func NewMeta

func NewMeta(req *http.Request) *Meta

NewMeta returns a new meta object for a request.

func NewMetaWithBody

func NewMetaWithBody(req *http.Request) (*Meta, error)

NewMetaWithBody returns a new meta object for a request and reads the body.

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 OutgoingRequestHandler

type OutgoingRequestHandler func(req *Meta)

OutgoingRequestHandler is a receiver for `OnRequest`.

type PostedFile

type PostedFile struct {
	Key          string
	FileName     string
	FileContents io.Reader
}

PostedFile represents a file to post with the request.

type Request

type Request struct {
	Verb string

	Scheme string
	Host   string
	Path   string

	QueryString url.Values

	Cookies []*http.Cookie

	Header            http.Header
	BasicAuthUsername string
	BasicAuthPassword string

	ContentType string
	PostData    url.Values
	Body        []byte

	Timeout time.Duration

	TLSClientCertPath string
	TLSClientKeyPath  string
	TLSClientCert     []byte
	TLSClientKey      []byte
	TLSSkipVerify     bool

	TLSCAPool *x509.CertPool

	KeepAlive        bool
	KeepAliveTimeout time.Duration
	Label            string
	// contains filtered or unexported fields
}

Request makes http requests.

func Get

func Get(url string) *Request

Get returns a new get request.

func New

func New() *Request

New returns a new HTTPRequest instance.

func Post

func Post(url string, body []byte) *Request

Post returns a new post request with an optional body.

func (*Request) AsDelete

func (hr *Request) AsDelete() *Request

AsDelete sets the http verb of the request to `DELETE`.

func (*Request) AsGet

func (hr *Request) AsGet() *Request

AsGet sets the http verb of the request to `GET`.

func (*Request) AsOptions

func (hr *Request) AsOptions() *Request

AsOptions sets the http verb of the request to `OPTIONS`.

func (*Request) AsPatch

func (hr *Request) AsPatch() *Request

AsPatch sets the http verb of the request to `PATCH`.

func (*Request) AsPost

func (hr *Request) AsPost() *Request

AsPost sets the http verb of the request to `POST`.

func (*Request) AsPut

func (hr *Request) AsPut() *Request

AsPut sets the http verb of the request to `PUT`.

func (*Request) Bytes

func (hr *Request) Bytes() ([]byte, error)

Bytes fetches the response as bytes.

func (*Request) BytesWithMeta

func (hr *Request) BytesWithMeta() ([]byte, *ResponseMeta, error)

BytesWithMeta fetches the response as bytes with meta.

func (*Request) Deserialized

func (hr *Request) Deserialized(deserialize Deserializer) (*ResponseMeta, error)

Deserialized runs a deserializer with the response.

func (*Request) Equals

func (hr *Request) Equals(other *Request) bool

Equals returns if a request equals another request.

func (*Request) Execute

func (hr *Request) Execute() error

Execute makes the request but does not read the response.

func (*Request) ExecuteWithMeta

func (hr *Request) ExecuteWithMeta() (*ResponseMeta, error)

ExecuteWithMeta makes the request and returns the meta of the response.

func (*Request) Hash

func (hr *Request) Hash() uint32

Hash returns a hashcode for a request.

func (Request) Headers

func (hr Request) Headers() http.Header

Headers returns the headers on the request.

func (*Request) JSON

func (hr *Request) JSON(destination interface{}) error

JSON unmarshals the response as json to an object.

func (*Request) JSONError

func (hr *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 (hr *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 (hr *Request) JSONWithMeta(destination interface{}) (*ResponseMeta, error)

JSONWithMeta unmarshals the response as json to an object with metadata.

func (*Request) Logger

func (hr *Request) Logger() *logger.Logger

Logger returns the request diagnostics agent.

func (Request) Meta

func (hr Request) Meta() *Meta

Meta returns the request as a HTTPRequestMeta.

func (Request) PostBody

func (hr Request) PostBody() []byte

PostBody returns the current post body.

func (*Request) Request

func (hr *Request) Request() (*http.Request, error)

Request returns a http.Request for the HTTPRequest.

func (*Request) Response

func (hr *Request) Response() (*http.Response, error)

Response makes the actual request but returns the underlying http.Response object.

func (*Request) String

func (hr *Request) String() (string, error)

String returns the body of the response as a string.

func (*Request) StringWithMeta

func (hr *Request) StringWithMeta() (string, *ResponseMeta, error)

StringWithMeta returns the body of the response as a string in addition to the response metadata.

func (*Request) Transport

func (hr *Request) Transport() (*http.Transport, error)

Transport returns the the custom transport for the request.

func (*Request) URL

func (hr *Request) URL() *url.URL

URL returns the currently formatted request target url.

func (*Request) WithBasicAuth

func (hr *Request) WithBasicAuth(username, password string) *Request

WithBasicAuth sets the basic auth headers for a request.

func (*Request) WithClientTLSCert

func (hr *Request) WithClientTLSCert(cert []byte) *Request

WithClientTLSCert sets a tls cert on the transport for the request.

func (*Request) WithClientTLSCertPath

func (hr *Request) WithClientTLSCertPath(certPath string) *Request

WithClientTLSCertPath sets a tls cert on the transport for the request.

func (*Request) WithClientTLSKey

func (hr *Request) WithClientTLSKey(key []byte) *Request

WithClientTLSKey sets a tls key on the transport for the request.

func (*Request) WithClientTLSKeyPath

func (hr *Request) WithClientTLSKeyPath(keyPath string) *Request

WithClientTLSKeyPath sets a tls key on the transport for the request.

func (*Request) WithClientTrace

func (hr *Request) WithClientTrace(trace *httptrace.ClientTrace) *Request

WithClientTrace sets up a trace for the request.

func (*Request) WithCombinedPath

func (hr *Request) WithCombinedPath(components ...string) *Request

WithCombinedPath sets the path component of the host url by combining the input path segments.

func (*Request) WithContentType

func (hr *Request) WithContentType(contentType string) *Request

WithContentType sets the `Content-Type` header for the request.

func (*Request) WithContext

func (hr *Request) WithContext(ctx context.Context) *Request

WithContext sets a context for the request.

func (*Request) WithCookie

func (hr *Request) WithCookie(cookie *http.Cookie) *Request

WithCookie sets a cookie for the request.

func (*Request) WithHeader

func (hr *Request) WithHeader(field string, value string) *Request

WithHeader sets a header on the request.

func (*Request) WithHost

func (hr *Request) WithHost(host string) *Request

WithHost sets the target url host for the request.

func (*Request) WithKeepAliveTimeout

func (hr *Request) WithKeepAliveTimeout(timeout time.Duration) *Request

WithKeepAliveTimeout sets a keep alive timeout for the requests transport.

func (*Request) WithKeepAlives

func (hr *Request) WithKeepAlives() *Request

WithKeepAlives sets if the request should use the `Connection=keep-alive` header or not.

func (*Request) WithLabel

func (hr *Request) WithLabel(label string) *Request

WithLabel gives the request a logging label.

func (*Request) WithLogger

func (hr *Request) WithLogger(agent *logger.Logger) *Request

WithLogger enables logging with HTTPRequestLogLevelErrors.

func (*Request) WithMockProvider

func (hr *Request) WithMockProvider(provider MockedResponseProvider) *Request

WithMockProvider mocks a request response.

func (*Request) WithOnCreateTransport

func (hr *Request) WithOnCreateTransport(hook CreateTransportHandler) *Request

WithOnCreateTransport configures an event receiver.

func (*Request) WithOnRequest

func (hr *Request) WithOnRequest(hook OutgoingRequestHandler) *Request

WithOnRequest configures an event receiver.

func (*Request) WithOnResponse

func (hr *Request) WithOnResponse(hook ResponseHandler) *Request

WithOnResponse configures an event receiver.

func (*Request) WithOnResponseStateful

func (hr *Request) WithOnResponseStateful(hook StatefulResponseHandler) *Request

WithOnResponseStateful configures an event receiver that includes the request state.

func (*Request) WithPath

func (hr *Request) WithPath(path string) *Request

WithPath sets the path component of the host url..

func (*Request) WithPathf

func (hr *Request) WithPathf(format string, args ...interface{}) *Request

WithPathf sets the path component of the host url by the format and arguments.

func (*Request) WithPostBody

func (hr *Request) WithPostBody(body []byte) *Request

WithPostBody sets the post body directly.

func (*Request) WithPostBodyAsJSON

func (hr *Request) WithPostBodyAsJSON(object interface{}) *Request

WithPostBodyAsJSON sets the post body raw to be the json representation of an object.

func (*Request) WithPostBodyAsXML

func (hr *Request) WithPostBodyAsXML(object interface{}) *Request

WithPostBodyAsXML sets the post body raw to be the xml representation of an object.

func (*Request) WithPostBodySerialized

func (hr *Request) WithPostBodySerialized(object interface{}, serialize Serializer) *Request

WithPostBodySerialized sets the post body with the results of the given serializer.

func (*Request) WithPostData

func (hr *Request) WithPostData(field string, value string) *Request

WithPostData sets a post data value for the request.

func (*Request) WithPostDataFromObject

func (hr *Request) WithPostDataFromObject(object interface{}) *Request

WithPostDataFromObject sets the post data for a request as json from a given object. Remarks; this differs from `WithJSONBody` in that it sets individual post form fields for each member of the object.

func (*Request) WithPostedFile

func (hr *Request) WithPostedFile(key, fileName string, fileContents io.Reader) *Request

WithPostedFile adds a posted file to the multipart form elements of the request.

func (*Request) WithQueryString

func (hr *Request) WithQueryString(field string, value string) *Request

WithQueryString sets a query string value for the host url of the request.

func (*Request) WithResponseBuffer

func (hr *Request) WithResponseBuffer(buffer Buffer) *Request

WithResponseBuffer sets the response buffer for the request (if you want to re-use one). An example is if you're constantly pinging an endpoint with a similarly sized response, You can just re-use a buffer for reading the response.

func (*Request) WithScheme

func (hr *Request) WithScheme(scheme string) *Request

WithScheme sets the scheme, or protocol, of the request.

func (*Request) WithState

func (hr *Request) WithState(state interface{}) *Request

WithState adds a state object to the request for later usage.

func (*Request) WithTLSRootCAPool

func (hr *Request) WithTLSRootCAPool(certPool *x509.CertPool) *Request

WithTLSRootCAPool sets the root TLS ca pool for the request.

func (*Request) WithTimeout

func (hr *Request) WithTimeout(timeout time.Duration) *Request

WithTimeout sets a timeout for the request. Remarks: This timeout is enforced on client connect, not on request read + response.

func (*Request) WithTransport

func (hr *Request) WithTransport(transport *http.Transport) *Request

WithTransport sets a transport for the request.

func (*Request) WithURL

func (hr *Request) WithURL(urlString string) *Request

WithURL sets the request target url whole hog.

func (*Request) WithURLf

func (hr *Request) WithURLf(format string, args ...interface{}) *Request

WithURLf sets the url based on a format and args.

func (*Request) WithVerb

func (hr *Request) WithVerb(verb string) *Request

WithVerb sets the http verb of the request.

func (*Request) WithVerifyTLS

func (hr *Request) WithVerifyTLS(shouldVerify bool) *Request

WithVerifyTLS skips the bad certificate checking on TLS requests.

func (*Request) XML

func (hr *Request) XML(destination interface{}) error

XML unmarshals the response as xml to an object with metadata.

func (*Request) XMLWithErrorHandler

func (hr *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 (hr *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) Flag

func (re ResponseEvent) Flag() logger.Flag

Flag returns the event flag.

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 *Meta, meta *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

type Serializer func(value interface{}) ([]byte, error)

Serializer is a function that turns an object into raw data.

type StatefulResponseHandler

type StatefulResponseHandler func(req *Meta, res *ResponseMeta, content []byte, state interface{})

StatefulResponseHandler is a receiver for `OnResponse` that includes a state object.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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