rekwest

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Aug 26, 2018 License: MIT Imports: 12 Imported by: 0

README

rekwest

Build Status godoc

Fluent HTTP request client

Installation

Use go get:

$ go get github.com/m90/rekwest

Example

Perform a POST request, encoding the JSON response into data, by calling Do(targets ...interface{}) on the previously constructed request:

req := rekwest.New("https://www.example.com/api/create-animal").
    Method(http.MethodPost).
    JSONBody(map[string]interface{}{
        "kind":     "platypus",
        "flappers": true,
    }).
    BasicAuth("username", "secret")

data := responseType{}
if err := req.Do(&data); err != nil {
    panic(err)
}
Features
Authentication

Use BasicAuth(username, password string) or BearerToken(token string) to send Authorization headers:

rekwest.New("https://www.example.com/api").BasicAuth("user", "pass")

rekwest.New("https://www.example.com/api").BearerToken("my-token")
Context

Add a context.Context using Context(ctx context.Context):

timeout, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()

rekwest.New("https://www.example.com/api").Context(timeout).Do()
Timeout

Set a duration for when the request is supposed to time out using Timeout(value time.Duration):

rekwest.New("https://www.example.com/api").Timeout(time.Second)
Headers

Set header values using Header(key, value string) or Headers(headers map[string]string):

r := rekwest.New("https://www.example.com/api").Header("X-Foo", "bar")
r.Headers(map[string]string{
	"X-Bar":   "foo",
	"X-Other": "another one",
})
HTTP Client

Use a custom http.Client instance by passing it to Client(client *http.Client):

rekwest.New("https://www.example.com/api").Client(&http.Client{
	Timeout: time.Second,
})
Response content type

Use ResponseFormat(format ResponseFormat) in case you want to specify the expected payload:

json := rekwest.New("https://www.example.com/api").ResponseFormat(rekwest.ResponseFormatJSON)
data := responseType{}
err := json.Do(&data)

Available formats are ResponseFormatJSON, ResponseFormatXML and ResponseFormatBytes. If no value is set, rekwest will try to read the responses Content-Type header and act accordingly. If none is sent, the response body will be treated as type []byte.

For JSON and XML, the correct Accept header will be automatically set.

Request body Marshaling

Request payloads can automatically be marshalled into the desired format using JSONBody(data interface{}), XMLBody(data interface{}) and MarshalBody(data interface{}, marshalFunc func(interface{}) ([]byte, error)):

rekwest.New("https://www.example.com/api/create-animal").
    Method(http.MethodPost).
    JSONBody(map[string]interface{}{
        "kind":     "platypus",
        "flappers": true,
    })

Alternatively an io.Reader can be passed to Body(data io.Reader).

License

MIT © Frederik Ring

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type MultiError

type MultiError struct {
	Errors []error
}

MultiError is a basic wrapper around multiple errors.

func (MultiError) Error

func (e MultiError) Error() string

type Rekwest

type Rekwest interface {
	// Method sets the request Method.
	Method(string) Rekwest
	// Body sets the request body.
	Body(io.Reader) Rekwest
	// bytesBody uses the given byte array as the request body.
	BytesBody([]byte) Rekwest
	// MarshalBody uses the given marshal func to marshal the given data into the
	// request body. For JSON and XML payloads, you can use the JSONBody and
	// XMLBody methods.
	MarshalBody(interface{}, func(interface{}) ([]byte, error)) Rekwest
	// JSONBody marshals the given data into JSON and uses it as the request body.
	JSONBody(interface{}) Rekwest
	// XMLBody marshals the given data into XML and uses it as the request body.
	XMLBody(interface{}) Rekwest
	// Header sets the request header of the given key to the given value.
	Header(string, string) Rekwest
	// Headers sets the request headers for all key/value pairs in the
	// given map.
	Headers(map[string]string) Rekwest
	// BasicAuth ensures the given basic auth credentials will be used
	// when performing the request.
	BasicAuth(string, string) Rekwest
	// BearerToken ensures Authorization headers with the given bearer token
	// will be sent.
	BearerToken(string) Rekwest
	// Context adds a context to the request. In case the context hits the
	// cancellation deadline before the request can be performed, `Do` will return
	// the context's error.
	Context(context.Context) Rekwest
	// ResponseFormat sets the expected response format. It can be set to
	// ResponseFormatJSON or ResponseFormatXML.
	ResponseFormat(ResponseFormat) Rekwest
	// Timeout sets a timeout value for performing the request. The countdown
	// starts when calling `Do`.
	Timeout(time.Duration) Rekwest
	// Client ensures the given *http.Client will be used for performing the
	// request when calling `Do`.
	Client(*http.Client) Rekwest
	// Errors returns all errors that occurred when building the request.
	Errors() []error
	// OK returns true if no errors have been encountered when building the request.
	OK() bool
	// Do performs the request and returns possible errors.
	// The response body will encoded onto the passed target if given.
	Do(...interface{}) error
}

Rekwest is a chainable interface for building and performing HTTP requests.

func New

func New(url string) Rekwest

New creates a new Rekwest that will perform requests against the given URL. It defaults to performing GET requests and no body, expecting JSON to be sent in return.

type ResponseFormat

type ResponseFormat string

ResponseFormat is a string describing the expected encoding of the response.

const (
	ResponseFormatContentType ResponseFormat = "content-type"
	ResponseFormatJSON        ResponseFormat = "json"
	ResponseFormatXML         ResponseFormat = "xml"
	ResponseFormatBytes       ResponseFormat = "bytes"
)

A list of supported `ResponseFormat`s.

Jump to

Keyboard shortcuts

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