r2

package
v2.0.0+incompatible Latest Latest
Warning

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

Go to latest
Published: Apr 1, 2019 License: MIT Imports: 15 Imported by: 3

README

r2

This is meant to be an experiment for an options based api for sending request. It is not stable and should only be used on an experimental basis.

Philosophy

Departing from "Fluent APIs", go-sdk/r2 investigates what an "Options" based api for making http requests would look like.

Funadmentally, it means taking code that looks like:

res, err := request.New().
	WithVerb("POST").
	MustWithURL("https://www.google.com/robots.txt").
	WithHeaderValue("X-Authorization", "none").
	WithHeaderValue(request.HeaderContentType, request.ContentTypeApplicationJSON).
	WithBody([]byte(`{"status":"maybe?"}`)).
	Execute()

And refactors that to:

res, err := r2.New("https://www.google.com/robots.txt",
	r2.OptPost(),
	r2.OptHeaderValue("X-Authorization", "none").
	r2.OptHeaderValue(request.HeaderContentType, request.ContentTypeApplicationJSON),
	r2.OptBody([]byte(`{"status":"maybe?"}`)).Do()

The key difference here is making use of a variadic list of "Options" which are really just functions that satisfy the signature func(*r2.Request) error. This lets developers extend the possible options that can be specified, vs. having a strictly hard coded list hung off the request.Request object, which require a PR to make changes to.

Usage

R2 uses a different paradigm from go-sdk/request; instead of chaining calls with a "fluent" api, options can be provided in a variadic list. This lets users extend the possible options as necessary.

Example

package main

import (
	"fmt"
	"os"
	"time"

	"github.com/blend/go-sdk/r2"
)

func CustomOption() r2.Option {
	return func(r *r2.Request) {
		r.Client.Timeout = 10 * time.Millisecond
	}
}

func main() {
	_, err := r2.New("https://google.com",
		r2.Get(),
		r2.Timeout(500*time.Millisecond),
		r2.Header("X-Sent-By", "go-sdk/request2"),
		r2.CookieValue("ssid", "baileydog01"),
		CustomOption(),
	).CopyTo(os.Stdout)

	if err != nil {
		fmt.Fprintf(os.Stderr, "%v\n", err)
		os.Exit(1)
	}
}

Documentation

Overview

Package r2 is a rewrite of the request package that eschews fluent apis in favor of the options pattern. It is meant to be feature equivalent to request.

Index

Constants

View Source
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"
)
View Source
const (
	// HeaderConnection is a http header.
	HeaderConnection = "Connection"
	// HeaderContentType is a http header.
	HeaderContentType = "Content-Type"
)
View Source
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"
	// ContentTypeApplicationOctetStream is a content type header value.
	ContentTypeApplicationOctetStream = "application/octet-stream"
)
View Source
const (
	// Flag is a logger event flag.
	Flag logger.Flag = "request"
	// FlagResponse is a logger event flag.
	FlagResponse logger.Flag = "request.response"
)
View Source
const (
	// ConnectionKeepAlive is a connection header value.
	ConnectionKeepAlive = "keep-alive"
)

Variables

This section is empty.

Functions

This section is empty.

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 ParseCertInfo

func ParseCertInfo(res *http.Response) *CertInfo

ParseCertInfo returns a new cert info from a response.

type Defaults

type Defaults []Option

Defaults is a helper to create requests with a common set of base options.

func (Defaults) Add

func (d Defaults) Add(options ...Option) Defaults

Add adds new options to the default set.

func (Defaults) ConcatWith

func (d Defaults) ConcatWith(options ...Option) []Option

ConcatWith concats the options with a given set of new options for output.

type Event

type Event struct {
	*logger.EventMeta

	// Started is the time the request was started.
	// It is used for elapsed time calculations.
	Started time.Time
	// The request metadata.
	Request *http.Request
	// The response metadata (excluding the body).
	Response *http.Response
	// The response body.
	Body []byte
}

Event is a response to outgoing requests.

func NewEvent

func NewEvent(flag logger.Flag, options ...EventOption) *Event

NewEvent returns a new event.

func (*Event) WriteJSON

func (e *Event) WriteJSON() logger.JSONObj

WriteJSON implements logger.JSONWritable.

func (*Event) WriteText

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

WriteText writes the event to a text writer.

type EventOption

type EventOption func(e *Event)

EventOption is an event option.

func OptEventBody

func OptEventBody(body []byte) EventOption

OptEventBody sets the body.

func OptEventCompleted

func OptEventCompleted(ts time.Time) EventOption

OptEventCompleted sets the event completed time.

func OptEventFlag

func OptEventFlag(flag logger.Flag) EventOption

OptEventFlag sets the event flag.

func OptEventRequest

func OptEventRequest(req *http.Request) EventOption

OptEventRequest sets the response.

func OptEventResponse

func OptEventResponse(res *http.Response) EventOption

OptEventResponse sets the response.

func OptEventStarted

func OptEventStarted(ts time.Time) EventOption

OptEventStarted sets the start time.

type OnRequestListener

type OnRequestListener func(*http.Request) error

OnRequestListener is an a listener for on request events.

type OnResponseListener

type OnResponseListener func(*http.Request, *http.Response, time.Time, error) error

OnResponseListener is an on response listener.

type Option

type Option func(*Request) error

Option is a modifier for a request.

func OptBasicAuth

func OptBasicAuth(username, password string) Option

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 OptContext

func OptContext(ctx context.Context) Option

OptContext sets the request context.

func OptCookie

func OptCookie(cookie *http.Cookie) Option

OptCookie adds a cookie.

func OptCookieValue

func OptCookieValue(name, value string) Option

OptCookieValue adds a cookie with a given name and value.

func OptDelete

func OptDelete() Option

OptDelete sets the request method.

func OptGet

func OptGet() Option

OptGet sets the request method.

func OptHeader

func OptHeader(headers http.Header) Option

OptHeader sets the request headers.

func OptHeaderValue

func OptHeaderValue(key, value string) Option

OptHeaderValue adds or sets a header value.

func OptJSONBody

func OptJSONBody(obj interface{}) Option

OptJSONBody sets the post body on the request.

func OptLogRequest

func OptLogRequest(log logger.Log) Option

OptLogRequest adds an OnResponse listener to log the response of a call.

func OptLogResponse

func OptLogResponse(log logger.Log) Option

OptLogResponse adds an OnResponse listener to log the response of a call.

func OptLogResponseWithBody

func OptLogResponseWithBody(log logger.Log) 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 OptMethod

func OptMethod(method string) Option

OptMethod sets the request method.

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 OptPatch

func OptPatch() Option

OptPatch sets the request method.

func OptPost

func OptPost() Option

OptPost sets the request method.

func OptPostForm

func OptPostForm(postForm url.Values) Option

OptPostForm sets the request post form and the content type.

func OptPostFormValue

func OptPostFormValue(key, value string) Option

OptPostFormValue sets a request post form value.

func OptPut

func OptPut() Option

OptPut sets the request method.

func OptQuery

func OptQuery(query url.Values) Option

OptQuery set the fully querystring.

func OptQueryValue

func OptQueryValue(key, value string) Option

OptQueryValue adds or sets a query value.

func OptReadLimit

func OptReadLimit(byteCount int64) Option

OptReadLimit applies an `io.LimitReader` to a request's response.

func OptResponseBodyInterceptor

func OptResponseBodyInterceptor(interceptor ReaderInterceptor) Option

OptResponseBodyInterceptor sets the response reader on the request. This should be used to do things that modify how we read the response.

func OptResponseHeaderTimeout

func OptResponseHeaderTimeout(d time.Duration) Option

OptResponseHeaderTimeout sets the client transport ResponseHeaderTimeout.

func OptTLSClientCert

func OptTLSClientCert(cert, key []byte) Option

OptTLSClientCert adds a client cert and key to the request.

func OptTLSClientConfig

func OptTLSClientConfig(cfg *tls.Config) Option

OptTLSClientConfig sets the tls config for the request. It will create a client, and a transport if unset.

func OptTLSHandshakeTimeout

func OptTLSHandshakeTimeout(d time.Duration) Option

OptTLSHandshakeTimeout sets the client transport TLSHandshakeTimeout.

func OptTLSRootCAs

func OptTLSRootCAs(pool *x509.CertPool) Option

OptTLSRootCAs sets the client tls root ca pool.

func OptTimeout

func OptTimeout(d time.Duration) Option

OptTimeout sets the client timeout.

func OptTracer

func OptTracer(tracer Tracer) Option

OptTracer sets the optional trace handler.

func OptTransport

func OptTransport(transport http.RoundTripper) Option

OptTransport sets the client transport for a request.

func OptXMLBody

func OptXMLBody(obj interface{}) Option

OptXMLBody sets the post body on the request.

type ReadCloser

type ReadCloser struct {
	Closer io.Closer
	Reader io.Reader
}

ReadCloser allows you to split a ReaderCloser up into separate components. This lets use apply `io.LimitReader` and the like to response bodies, but preserve the original Close functionality.

func NewReadCloser

func NewReadCloser(body io.ReadCloser, interceptor ReaderInterceptor) *ReadCloser

NewReadCloser creates a new read closer from a given body and interceptor.

func (*ReadCloser) Close

func (rc *ReadCloser) Close() error

Close calls the closer.

func (*ReadCloser) Read

func (rc *ReadCloser) Read(contents []byte) (int, error)

Read calls the reader.

type ReaderInterceptor

type ReaderInterceptor func(io.Reader) io.Reader

ReaderInterceptor is a handler for request.ReadResponse

type Request

type Request struct {
	*http.Request
	Client *http.Client

	// Err is an error set on construction.
	// It pre-empts the request going out.
	Err error

	// ResponseBodyInterceptor is an optional custom step to alter the response stream.
	ResponseBodyInterceptor ReaderInterceptor
	Tracer                  Tracer

	// OnRequest and OnResponse are lifecycle hooks.
	OnRequest  []OnRequestListener
	OnResponse []OnResponseListener
}

Request is a combination of the http.Request options and the underlying client.

func New

func New(remoteURL string, options ...Option) *Request

New returns a new request. The default method is GET.

func (*Request) Bytes

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

Bytes reads the response and returns it as a byte array.

func (*Request) Close

func (r *Request) Close() (*http.Response, error)

Close executes and closes the response. It returns the response for metadata purposes. It does not read any data from the response.

func (*Request) CopyTo

func (r *Request) CopyTo(dst io.Writer) (int64, error)

CopyTo copies the response body to a given writer.

func (*Request) Discard

func (r *Request) Discard() error

Discard reads the response fully and discards all data it reads.

func (*Request) Do

func (r *Request) Do() (*http.Response, error)

Do executes the request.

func (*Request) JSON

func (r *Request) JSON(dst interface{}) error

JSON reads the response as json into a given object.

func (*Request) String

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

String reads the response and returns it as a string

func (*Request) XML

func (r *Request) XML(dst interface{}) error

XML reads the response as json into a given object.

type TraceFinisher

type TraceFinisher interface {
	Finish(*http.Request, *http.Response, time.Time, error)
}

TraceFinisher is a finisher for traces.

type Tracer

type Tracer interface {
	Start(*http.Request) TraceFinisher
}

Tracer is a tracer for requests.

Directories

Path Synopsis
_examples
listener command
mtls command
request command
transport command

Jump to

Keyboard shortcuts

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