Documentation ¶
Overview ¶
Package r2 is a rewrite of the sdk http request package that eschews fluent apis in favor of the options pattern.
The request returned by `r2.New()` i.e. `*r2.Request` holds everything required to send the request, including the http client reference, and a transport reference. If neither are specified, defaults are used (http.DefaultClient for the client, etc.)
To send a request, simply:
resp, err := r2.New("http://example.com/").Do() if err != nil { // handle error } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) // ...
You can specify additional options as a variadic list of `Opt...` functions:
resp, err := r2.New("http://example.com", r2.OptPost(), r2.OptHeaderValue("X-Foo", "example-string"), ).Do()
There are convenience methods on the request type that help with things like decoding types as json:
meta, err := r2.New("http://example.com", r2.OptPost(), r2.OptHeaderValue("X-Foo", "example-string"), ).JSON(&myObj)
Note that in the above, the JSON method also returns a closed version of the response for metadata purposes.
You can also fire and forget the request with the `.Discard()` method:
meta, err := r2.New("http://example.com", r2.OptPost(), r2.OptHeaderValue("X-Foo", "example-string"), ).Discard()
Index ¶
- Constants
- Variables
- func EnsureHTTPTransport(r *Request) (*http.Transport, error)
- func ErrIsTooManyRedirects(err error) bool
- func GetParameterizedPath(ctx context.Context) string
- func GetParameterizedURLString(req *http.Request) string
- func NewEventFilter(filter func(context.Context, Event) (Event, bool)) logger.Filter
- func NewEventListener(listener func(context.Context, Event)) logger.Listener
- func WithParameterizedPath(ctx context.Context, path string) context.Context
- type DialOption
- type Event
- type EventJSONSchema
- type EventOption
- type LogOption
- type LogOptions
- type OnRequestListener
- type OnResponseListener
- type Option
- func OptBasicAuth(username, password string) Option
- func OptBody(contents io.ReadCloser) Option
- func OptBodyBytes(contents []byte) Option
- func OptClient(client *http.Client) Option
- func OptCloser(action func() error) Option
- func OptContext(ctx context.Context) Option
- func OptCookie(cookie *http.Cookie) Option
- func OptCookieValue(name, value string) Option
- func OptDelete() Option
- func OptDial(opts ...DialOption) Option
- func OptDisableKeepAlives(disableKeepAlives bool) Option
- func OptGet() Option
- func OptHTTPClientTrace(ht *webutil.HTTPTrace) Option
- func OptHeader(headers http.Header) Option
- func OptHeaderValue(key, value string) Option
- func OptHost(host string) Option
- func OptJSONBody(obj interface{}) Option
- func OptLog(log logger.Log) Option
- func OptLogRequest(log logger.Log) Option
- func OptLogResponse(log logger.Triggerable) Option
- func OptLogResponseWithBody(log logger.Triggerable) Option
- func OptLogWithBody(log logger.Log) Option
- func OptMaxRedirects(maxRedirects int) Option
- func OptMethod(method string) Option
- func OptNoFollow() Option
- func OptOnRequest(listener OnRequestListener) Option
- func OptOnResponse(listener OnResponseListener) Option
- func OptParameterizedPath(format string, params map[string]string) Option
- func OptPatch() Option
- func OptPath(path string) Option
- func OptPathf(format string, args ...interface{}) Option
- func OptPort(port int32) Option
- func OptPost() Option
- func OptPostForm(postForm url.Values) Option
- func OptPostFormValue(key, value string) Option
- func OptPostedFiles(files ...webutil.PostedFile) Option
- func OptPut() Option
- func OptQuery(query url.Values) Option
- func OptQueryValue(key, value string) Option
- func OptQueryValueAdd(key, value string) Option
- func OptResponseHeaderTimeout(d time.Duration) Option
- func OptScheme(scheme string) Option
- func OptTLSClientCert(cert, key []byte) Option
- func OptTLSClientCertFilePair(certFile, keyFile string) Option
- func OptTLSClientConfig(cfg *tls.Config) Option
- func OptTLSHandshakeTimeout(d time.Duration) Option
- func OptTLSRootCAs(pool *x509.CertPool) Option
- func OptTLSSkipVerify(skipVerify bool) Option
- func OptTimeout(d time.Duration) Option
- func OptTracer(tracer Tracer) Option
- func OptTransport(transport http.RoundTripper) Option
- func OptURL(rawURL string) Option
- func OptUserAgent(userAgent string) Option
- func OptXMLBody(obj interface{}) Option
- func RequestOption(opt func(*http.Request) error) Option
- type Request
- func (r Request) Bytes() (contents []byte, res *http.Response, err error)
- func (r *Request) Close() error
- func (r Request) CopyTo(dst io.Writer) (count int64, err error)
- func (r Request) Discard() (res *http.Response, err error)
- func (r Request) Do() (*http.Response, error)
- func (r Request) JSON(dst interface{}) (res *http.Response, err error)
- func (r Request) JSONBytes(dst interface{}) (body []byte, res *http.Response, err error)
- func (r *Request) WithContext(ctx context.Context) *Request
- func (r Request) XML(dst interface{}) (res *http.Response, err error)
- type TraceFinisher
- type Tracer
Constants ¶
const ( // MethodGet is a method. MethodGet = webutil.MethodGet // MethodPost is a method. MethodPost = webutil.MethodPost // MethodPut is a method. MethodPut = webutil.MethodPut // MethodPatch is a method. MethodPatch = webutil.MethodPatch // MethodDelete is a method. MethodDelete = webutil.MethodDelete // MethodOptions is a method. MethodOptions = webutil.MethodOptions )
const ( // ContentTypeApplicationJSON is a content type header value. ContentTypeApplicationJSON = webutil.ContentTypeApplicationJSON // ContentTypeApplicationXML is a content type header value. ContentTypeApplicationXML = webutil.ContentTypeApplicationXML // ContentTypeApplicationFormEncoded is a content type header value. ContentTypeApplicationFormEncoded = webutil.ContentTypeApplicationFormEncoded // ContentTypeApplicationOctetStream is a content type header value. ContentTypeApplicationOctetStream = webutil.ContentTypeApplicationOctetStream )
const ( // ErrRequestUnset is an error returned from options if they are called on a r2.Request that has not // been created by r2.New(), and as a result the underlying request is uninitialized. ErrRequestUnset ex.Class = "r2; cannot modify request, underlying request unset. please use r2.New()" // ErrInvalidTransport is an error returned from options if they are called on a request that has had // the transport set to something other than an *http.Transport; this precludes using http.Transport // specific options like tls.Config mutators. ErrInvalidTransport ex.Class = "r2; cannot modify transport, is not *http.Transport" // ErrNoContentJSON is returns from sending requests when a no-content status is returned. ErrNoContentJSON ex.Class = "server returned an http 204 for a request expecting json" // ErrNoContentXML is returns from sending requests when a no-content status is returned. ErrNoContentXML ex.Class = "server returned an http 204 for a request expecting xml" // ErrInvalidMethod is an error that is returned from `r2.Request.Do()` if a method // is specified on the request that violates the valid charset for HTTP methods. ErrInvalidMethod ex.Class = "r2; invalid http method" // ErrMismatchedPathParameters is an error that is returned from `OptParameterizedPath()` if // the parameterized path string has a different number of parameters than what was passed as // variadic arguments. ErrMismatchedPathParameters ex.Class = "r2; route parameters provided don't match parameters needed in path" )
Error Constants
const ( // Flag is a logger event flag. Flag = "http.client.request" // FlagResponse is a logger event flag. FlagResponse = "http.client.response" )
const ( // ConnectionKeepAlive is a connection header value. ConnectionKeepAlive = webutil.ConnectionKeepAlive )
const ( // TestURL can be used in tests for the URL passed to r2.New(...) // // 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 top level special domain that will _never_ be assigned // to a real registrant, it is always reserved for testing. // See: https://www.iana.org/domains/reserved TestURL = webutil.TestURL )
Variables ¶
var ( // HeaderConnection is a http header. HeaderConnection = webutil.HeaderConnection // HeaderContentType is a http header. HeaderContentType = webutil.HeaderContentType )
Functions ¶
func EnsureHTTPTransport ¶
EnsureHTTPTransport ensures the http client's transport is set and that it is an *http.Transport.
It will return an error `ErrInvalidTransport` if it is set to something other than *http.Transport.
func ErrIsTooManyRedirects ¶
ErrIsTooManyRedirects returns if the error is too many redirects.
func GetParameterizedPath ¶ added in v1.20210908.5
GetParameterizedPath gets a path with named parameters off a context. Useful for outbound request aggregation for metrics and tracing when route parameters are involved. Relies on OptParameterizedPath being added to a Request.
func GetParameterizedURLString ¶ added in v1.20210908.5
GetParameterizedURLString gets a URL string with named route parameters in place of the raw path for a request. Useful for outbound request aggregation for metrics and tracing when route parameters are involved. Relies on the request's context storing the parameterized path, otherwise will default to returning the request `URL`'s `String()`.
func NewEventFilter ¶
NewEventFilter returns a new r2 event filter.
func NewEventListener ¶
NewEventListener returns a new r2 event listener.
Types ¶
type DialOption ¶
type DialOption = webutil.DialOption
DialOption is an option for the net dialer.
func OptDialKeepAlive ¶
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 ¶
func OptDialTimeout(d time.Duration) DialOption
OptDialTimeout sets the dial timeout.
type Event ¶
type Event struct { Flag string // The request metadata. Request *http.Request // The response metadata (excluding the body). Response *http.Response // The response body. Body []byte // Elapsed is the time elapsed. Elapsed time.Duration }
Event is a response to outgoing requests.
func NewEvent ¶
func NewEvent(flag string, options ...EventOption) Event
NewEvent returns a new event.
type EventJSONSchema ¶
type EventJSONSchema struct { Req struct { StartTime time.Time `json:"startTime"` Method string `json:"method"` URL string `json:"url"` Headers map[string][]string `json:"headers"` } `json:"req"` Res struct { CompleteTime time.Time `json:"completeTime"` StatusCode int `json:"statusCode"` ContentLength int `json:"contentLength"` Headers map[string][]string `json:"headers"` } `json:"res"` Body string `json:"body"` }
EventJSONSchema is the json schema of the logger event.
type EventOption ¶
type EventOption func(e *Event)
EventOption is an event option.
func OptEventElapsed ¶
func OptEventElapsed(elapsed time.Duration) EventOption
OptEventElapsed sets the elapsed time.
func OptEventRequest ¶
func OptEventRequest(req *http.Request) EventOption
OptEventRequest sets the response.
func OptEventResponse ¶
func OptEventResponse(res *http.Response) EventOption
OptEventResponse sets the response.
type LogOptions ¶
type LogOptions struct {
RequestSanitizationDefaults []sanitize.RequestOption
}
LogOptions are options that govern the logging of requests.
type OnRequestListener ¶
OnRequestListener is an a listener for on request events.
type OnResponseListener ¶
OnResponseListener is an on response listener.
The time.Time is given as the start time of the request in the UTC timezone. To compute the elapsed time you would subtract from the current time in UTC i.e. `time.Now().UTC().Sub(startTime)`.
type Option ¶
Option is a modifier for a request.
func OptBasicAuth ¶
OptBasicAuth is an option that sets the http basic auth.
func OptBody ¶
func OptBody(contents io.ReadCloser) Option
OptBody sets the post body on the request.
func OptBodyBytes ¶
OptBodyBytes sets the post body on the request from a byte array.
func OptClient ¶
OptClient sets the underlying client on the request.
It is specifically useful to prevent churning allocations on sending repeated requests.
func OptCloser ¶
OptCloser sets the request closer.
It is typically used to clean up or trigger other actions.
func OptCookieValue ¶
OptCookieValue adds a cookie with a given name and value.
func OptDial ¶
func OptDial(opts ...DialOption) Option
OptDial sets dial options for a request, these must be done all at once.
func OptDisableKeepAlives ¶
OptDisableKeepAlives disables keep alives.
func OptHTTPClientTrace ¶ added in v1.20210103.1
OptHTTPClientTrace sets the outgoing httptrace.ClientTrace context.
func OptHeaderValue ¶
OptHeaderValue adds or sets a header value.
func OptJSONBody ¶
func OptJSONBody(obj interface{}) Option
OptJSONBody sets the post body on the request.
func OptLogRequest ¶
OptLogRequest adds OnRequest and OnResponse listeners to log that a call was made.
func OptLogResponse ¶
func OptLogResponse(log logger.Triggerable) Option
OptLogResponse adds an OnResponse listener to log the response of a call.
func OptLogResponseWithBody ¶
func OptLogResponseWithBody(log logger.Triggerable) Option
OptLogResponseWithBody adds an OnResponse listener to log the response of a call. It reads the contents of the response fully before emitting the event. Do not use this if the size of the responses can be large.
func OptLogWithBody ¶
OptLogWithBody adds OnRequest and OnResponse listeners to log that a call was made. It will also display the body of the response.
func OptMaxRedirects ¶
OptMaxRedirects tells the http client to only follow a given number of redirects, overriding the standard library default of 10. Use the companion helper `ErrIsTooManyRedirects` to test if the returned error from a call indicates the redirect limit was reached.
func OptNoFollow ¶
func OptNoFollow() Option
OptNoFollow tells the http client to not follow redirects returned by the remote server.
func OptOnRequest ¶
func OptOnRequest(listener OnRequestListener) Option
OptOnRequest sets an on request listener.
func OptOnResponse ¶
func OptOnResponse(listener OnResponseListener) Option
OptOnResponse adds an on response listener. If an OnResponse listener has already been addded, it will be merged with the existing listener.
func OptParameterizedPath ¶ added in v1.20210908.5
OptParameterizedPath sets the url path based on a parameterized path and arguments. Parameterized paths should appear in the same format as paths you would add to your web app (ex. `/resource/:resource_id`).
func OptPostForm ¶
OptPostForm sets the request post form and the content type.
func OptPostFormValue ¶
OptPostFormValue sets a request post form value.
func OptPostedFiles ¶ added in v1.20210727.1
func OptPostedFiles(files ...webutil.PostedFile) Option
OptPostedFiles adds multipart uploads to the request.
Usage note: this option will also encode any currently provided post form fields into the body as well, so you should make this the last option in a list to capture those fields.
func OptQueryValueAdd ¶ added in v1.20210402.2
OptQueryValueAdd adds a query value.
func OptResponseHeaderTimeout ¶
OptResponseHeaderTimeout sets the client transport ResponseHeaderTimeout.
func OptTLSClientCert ¶
OptTLSClientCert adds a client cert and key to the request.
func OptTLSClientCertFilePair ¶
OptTLSClientCertFilePair adds a client cert and key to the request.
func OptTLSClientConfig ¶
OptTLSClientConfig sets the tls config for the request. It will create a client, and a transport if unset.
func OptTLSHandshakeTimeout ¶
OptTLSHandshakeTimeout sets the client transport TLSHandshakeTimeout.
func OptTLSRootCAs ¶
OptTLSRootCAs sets the client tls root ca pool.
func OptTLSSkipVerify ¶
OptTLSSkipVerify sets if we should skip verification.
func OptTransport ¶
func OptTransport(transport http.RoundTripper) Option
OptTransport sets the client transport for a request.
func OptUserAgent ¶
OptUserAgent sets the user agent header on a request. It will initialize the request headers map if it's unset. It will overwrite any existing user agent header.
func OptXMLBody ¶
func OptXMLBody(obj interface{}) Option
OptXMLBody sets the post body on the request.
type Request ¶
type Request struct { Request *http.Request // Err is an error set on construction. // It is checked before sending the request, and will be returned from any of the // methods that execute the request. // It is typically set in `New(string,...Option)`. Err error // Client is the underlying http client used to make the requests. Client *http.Client // Closer is an optional step to run as part of the Close() function. Closer func() error // Tracer is used to report span contexts to a distributed tracing collector. Tracer Tracer // OnRequest is an array of request lifecycle hooks used for logging // or to modify the request on a per call basis before it is sent. OnRequest []OnRequestListener // OnResponse is an array of response lifecycle hooks used typically for logging. OnResponse []OnResponseListener }
Request is a combination of the http.Request options and the underlying client.
func (Request) Bytes ¶
Bytes reads the response and returns it as a byte array, along with the response metadata..
func (Request) Discard ¶
Discard reads the response fully and discards all data it reads, and returns the response metadata.
func (Request) JSON ¶
JSON reads the response as json into a given object and returns the response metadata.
func (Request) JSONBytes ¶ added in v1.20210615.7
JSONBytes reads the response as json into a given object and returns the response bytes as well as the response metadata.
This method is useful for debugging responses.
func (*Request) WithContext ¶
WithContext implements the `WithContext` method for the underlying request.
It is preserved here because the pointer indirects are non-trivial.
type TraceFinisher ¶
TraceFinisher is a finisher for traces.
type Tracer ¶
type Tracer interface {
Start(*http.Request) TraceFinisher
}
Tracer is a tracer for requests.
Source Files ¶
- constants.go
- context.go
- dial_option.go
- doc.go
- ensure_http_transport.go
- errors.go
- event.go
- event_option.go
- log_option.go
- opt_basic_auth.go
- opt_body.go
- opt_client.go
- opt_closer.go
- opt_context.go
- opt_cookie.go
- opt_dial.go
- opt_dial_keepalive.go
- opt_dial_timeout.go
- opt_disable_keep_alives.go
- opt_header.go
- opt_host.go
- opt_http_client_trace.go
- opt_json_body.go
- opt_log.go
- opt_log_request.go
- opt_log_response.go
- opt_max_redirects.go
- opt_method.go
- opt_no_follow.go
- opt_on_request.go
- opt_on_response.go
- opt_path.go
- opt_port.go
- opt_post_form.go
- opt_posted_files.go
- opt_query.go
- opt_response_header_timeout.go
- opt_scheme.go
- opt_timeout.go
- opt_tls_client_cert.go
- opt_tls_client_cert_file_pair.go
- opt_tls_client_config.go
- opt_tls_handshake_timeout.go
- opt_tls_root_cas.go
- opt_tls_skip_verify.go
- opt_tracer.go
- opt_transport.go
- opt_url.go
- opt_user_agent.go
- opt_xml_body.go
- option.go
- request.go
- request_option.go
- tracer.go