requester

package module
v0.2.3 Latest Latest
Warning

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

Go to latest
Published: May 9, 2018 License: MIT Imports: 16 Imported by: 0

README

Requester Build Status GoDoc Go Report Card

A.K.A "Yet Another Golang Requests Package"

EXPERIMENTAL: Until the version reaches 1.0, the API may change.

Requester makes it a bit simpler to use Go's http package as a client. As an example, take a simple request, with the http package:

req, err := http.NewRequest("GET", "http://www.google.com", nil)
if err != nil { return err }

resp, err := http.DefaultClient.Do(req)
if err != nil { return err }

defer resp.Body.Close()
if resp.StatusCode == 200 {
    respBody, _ := ioutil.ReadAll(resp.Body)
    fmt.Println(string(respBody))
}

With requester:

resp, body, err := requester.Receive(nil, requester.Get("http://www.google.com"))
if err != nil { return err }

fmt.Printf("%d %s", resp.StatusCode, string(body))

For a more complex use case, take an API call, which sends and receives JSON.
With http:

bodyBytes, err := json.Marshal(reqBodyStruct)
if err != nil { return err }

req, err := http.NewRequest("POST", "http://api.com/resources/", bytes.NewReader(bodyBytes))
if err != nil { return err }
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json"

resp, err := http.DefaultClient.Do(req)
if err != nil { return err }

if resp.StatusCode == 201 {
    respBody, _ := ioutil.ReadAll(resp.Body)
    var respStruct Resource
    err := json.Unmarshal(respBody, &respStruct)
    if err != nil { return err }
    
    fmt.Println(respBody)
}

With Requester:

var respStruct Resource

resp, body, err := requester.Receive(&respStruct, 
    requester.JSON(),
    requester.Get("http://www.google.com")
)
if err != nil { return err }
    
fmt.Printf("%d %s %v", resp.StatusCode, string(body), respStruct)

Requester revolves around the use of Options, which are arguments to the functions which create and/or send requests. Options can be be used to set headers, set query parameters, compose the URL, set the method, install middleware, configure or replace the HTTP client used to send the request, etc.

The package-level Request(...Option) function creates an (unsent) *http.Request:

req, err := requester.Request(requester.Get("http://www.google.com"))

The Send(...Option) function both creates the request and sends it, using the http.DefaultClient:

resp, err := requester.Do(Get("http://www.google.com"))

A raw *http.Response is returned. It is the caller's responsibility to close the response body, just as with http.Client's Do() method.

The package also has Receive(interface{}, ...Option)
function which handles reading the response and optionally unmarshaling the body into a struct:

var user User
resp, body, err := requester.Receive(&user, requester.Get("http://api.com/users/bob"))

The Receive() function reads and closes the response body for you, returns the entire response body as a string, and optionally unmarshals the response body into a struct. If you only want the body back as a string, pass nil as the first argument. The string body is returned either way. Requester can handle JSON and XML response bodies, as determined by the response's Content-Type header. Other types of bodies can be handled by using a custom Unmarshaler.

All these functions have *Context() variants, which add a context.Context to the request. This is particularly useful for setting a request timeout:

ctx = context.WithTimeout(ctx, 10 * time.Second)
requester.RequestContext(ctx, requester.Get("http://www.google.com"))
requester.DoContext(ctx, requester.Get("http://www.google.com"))
requester.ReceiveContext(ctx, &into, requester.Get("http://www.google.com"))

Requester Instance

The package level functions just delegate to the DefaultRequester variable, which holds a Requester instance. An instance of Requester is useful for building re-usable, composable HTTP clients.

A new Requester can be constructed with New(...Options):

reqs, err := requester.New(
    requester.Get("http://api.server/resources/1"), 
    requester.JSON(), 
    requester.Accept(requester.ContentTypeJSON)
)

...or can be created with a literal:

u, _ := url.Parse("http://api.server/resources/1")

reqs := &requester.Requester{
    URL: u,
    Method: "GET",
    Header: http.Header{
        requester.HeaderContentType: []string{requester.ContentTypeJSON),
        requester.HeaderAccept: []string{requester.ContentTypeJSON),
    },
}

Additional options can be applied with Apply():

err := reqs.Apply(requester.Method("POST"), requester.Body(bodyStruct))
if err != nil { return err }

...or can just be set directly:

reqs.Method = "POST"
reqs.Body = bodyStruct

Requester can be cloned, creating a copy which can be further configured:

base, _ := requester.New(
    requester.URL("https://api.com"), 
    requester.JSON(),
    requester.Accept(requester.ContentTypeJSON),
    requester.BearerAuth(token),
)
    
getResource = base.Clone()
getResource.Apply(requester.Get("resources/1"))

With(...Option) combines Clone() and Apply(...Option):

getResource, _ := base.With(requester.Get("resources/1"))

Options can also be passed to the Request/Do/Receive methods. These Options will only be applied to the particular request, not the Requester instance:

resp, body, err := base.Receive(nil, requester.Get("resources", "1")  // path elements
                                                                     // will be joined.

Request Options

The Requester struct has attributes mirror counterparts on *http.Request:

Method string
URL    *url.URL
Header http.Header
GetBody          func() (io.ReadCloser, error)
ContentLength    int64
TransferEncoding []string
Close            bool
Host             string
Trailer          http.Header

If not set, the constructed *http.Requests will have the normal default values these attributes have after calling http.NewRequest() (some attributes will be initialized, some remained zeroed).

If set, then the Requester' values will overwrite the values of these attributes in the *http.Request.

Functional Options are defined which set most of these attributes. You can configure Requester either by applying Options, or by simply setting the attributes directly.

Client Options

The HTTP client used to execute requests can also be customized through options:

requester.Send(requester.Get("https://api.com"), requester.Client(httpclient.SkipVerify()))

github.com/gemalto/requester/httpclient is a standalone package for constructing and configuring http.Clients. The requester.Client(...httpclient.Option) option constructs a new HTTP client and installs it into Requester.Doer.

Query Params

The QueryParams attribute will be merged into any query parameters encoded into the URL. For example:

reqs, _ := requester.New(requester.URL("http://test.com?color=red"))
reqs.QueryParams = url.Values("flavor":[]string{"vanilla"})
r, _ := reqs.Request()
r.URL.String()             // http://test.com?color=red&flavor=vanilla

The QueryParams() option can take a map[string]string, map[string]interface{}, or url.Values, or accepts a struct, which is marshaled into a url.Values using github.com/google/go-querystring:

type Params struct {
    Color string `url:"color"`
}

reqs, _ := requester.New(
    requester.URL("http://test.com"),
    requester.QueryParams(Params{Color:"blue"}),
    requester.QueryParams(map[string][]string{"flavor":[]string{"vanilla"}}),
)
r, _ := reqs.Request()
r.URL.String()             // http://test.com?color=blue,flavor=vanilla

Body

If Requester.Body is set to a string, []byte, or io.Reader, the value will be used directly as the request body:

req, _ := requester.Request(
    requester.Post("http://api.com"),
    requester.ContentType(requester.ContentTypeJSON),
    requester.Body(`{"color":"red"}`),
)
httputil.DumpRequest(req, true)

// POST / HTTP/1.1
// Host: api.com
// Content-Type: application/json
// 
// {"color":"red"}

If Body is any other value, it will be marshaled into the body, using the Marshaler:

type Resource struct {
    Color string `json:"color"`
}

req, _ := requester.Request(
    requester.Post("http://api.com"),
    requester.Body(Resource{Color:"red"}),
)
httputil.DumpRequest(req, true)

// POST / HTTP/1.1
// Host: api.com
// Content-Type: application/json
// 
// {"color":"red"}

Note the default marshaler is JSON, and sets the Content-Type header.

Receive

Receive() handles the response as well:

type Resource struct {
    Color string `json:"color"`
}

var res Resource

resp, body, err := requester.Receive(&res, requester.Get("http://api.com/resources/1")
if err != nil { return err }

fmt.Println(body)     // {"color":"red"}

The body of the response is returned. If the first argument is not nil, the body will also be unmarshaled into that value.

By default, the unmarshaler will use the response's Content-Type header to determine how to unmarshal the response body into a struct. This can be customized by setting Requester.Unmarshaler:

reqs.Unmarshaler = &requester.XMLMarshaler(Indent:true)                  // via assignment
reqs.Apply(requester.Unmarshaler(&requester.XMLMarshaler(Indent:true)))   // or via an Option

Doer and Middleware

Requester uses an implementation of Doer to execute requests. By default, http.DefaultClient is used, but this can be replaced by a customize client, or a mock Doer:

reqs.Doer = requester.DoerFunc(func(req *http.Request) (*http.Response, error) {
    return &http.Response{}
})

You can also install middleware into Requester, which can intercept the request and response:

mw := func(next requester.Doer) requester.Doer {
    return requester.DoerFunc(func(req *http.Request) (*http.Response, error) {
        fmt.Println(httputil.DumpRequest(req, true))
        resp, err := next(req)
        if err == nil { 
            fmt.Println(httputil.DumpResponse(resp, true))
        }
        return resp, err
    })
}
reqs.Middleware = append(reqs.Middleware, mw)   // via assignment
reqs.Apply(requester.Use(mw))                    // or via option

FAQ

  • Why, when there are like, 50 other packages that do the exact same thing?

Yeah, good question. This library started as a few tweaks to https://github.com/dghubble/sling. Then it became more of a fork, then a complete rewrite, inspiration from a bunch of other similar libraries.

A few things bugged me about other libraries:

  1. Some didn't offer enough control over the base http primitives, like the underlying http.Client, and all the esoteric attributes of http.Request.

  2. I wanted more control over marshaling and unmarshaling bodies, without sacrificing access to the raw body.

  3. Some libraries which offer lots more control or options also seemed to be much more complicated, or less idiomatic.

  4. Most libraries don't handle context.Contexts at all.

  5. The main thing: most other libraries use a "fluent" API, where you call methods on a builder instance to configure the request, and these methods each return the builder, making it simple to call the next method, something like this:

     req.Get("http://api.com").Header("Content-Type", "application/json").Body(reqBody)
    

    I used to like fluent APIs in other languages, but they don't feel right in Go. You typically end up deferring errors until later, so the error doesn't surface near the code that caused the error. Its difficult to mix fluent APIs with interfaces, because the concrete types tend to have lots of methods, and they all have to return the same concrete type. For the same reason, it's awkward to embed types with fluent APIs. Fluent APIs also make it hard to extend the library with additional, external options.

Requester swaps a fluent API for the functional option pattern. This hopefully keeps a fluent-like coding style, while being more idiomatic Go. Since Options are just a simple interface, it's easy to bring your own options, or contribute new options back to this library.

Also, making the options into objects improved ergonomics in a few places, like mirroring the main functions (Request(), Send(), Receive()) on the struct and the package. Options can be passed around as arguments or accumulated in slices.

Documentation

Overview

Package requester is a Go library for building and sending HTTP requests. It's a thin wrapper around the http package, which makes it a little easier to create and send requests, and to handle responses.

Requester revolves around the use of functional Options. Options can be be used to configure aspects of the request, like headers, query params, the URL, etc. Options can also configure the client used to send requests.

The central functions are Request(), Send(), and Receive():

// Create a request
req, err := requester.Request(
	requester.JSON(),
	requester.Get("http://api.com/users/bob"),
)

// Create and send a request
resp, err := requester.Send(
	requester.JSON(),
	requester.Non2XXResponseAsError(),
	requester.Get("http://api.com/users/bob"),
)

// Create and send a request, and handle the response
var user User
resp, body, err := requester.Receive(&user,
	requester.JSON(),
	requester.Non2XXResponseAsError(),
	requester.BasicAuth("user", "password"),
	requester.Client(httpclient.NoRedirects()),
	requester.DumpToStout(),
	requester.Get("http://api.com/users/bob"),
)

// Create a reusable Requester instance
reqr, err := requester.New(
	requester.JSON(),
	requester.Non2XXResponseAsError(),
	requester.BasicAuth("user", "password"),
	requester.Client(httpclient.NoRedirects()),
	requester.DumpToStout(),
)

// Requester instances have the same main methods as the package
req, err := reqr.Request(
	requester.Get("http://api.com/users/bob")
)

resp, err := reqr.Send(
	requester.Get("http://api.com/users/bob")
)

resp, body, err := reqr.Receive(&user,
	requester.Get("http://api.com/users/bob")
)

There are also *Context() variants as well:

ctx = context.WithTimeout(ctx, 10 * time.Second)
requester.RequestContext(ctx, requester.Get("http://api.com/users/bob"))
requester.SendContext(ctx, requester.Get("http://api.com/users/bob"))
requester.ReceiveContext(ctx, &into, requester.Get("http://api.com/users/bob"))

The attributes of the Requester control how it creates and sends requests, and how it handles responses:

type Requester struct {

	// These are copied directly into requests, if they contain
	// a non-zero value
	Method string
	URL    *url.URL
	Header http.Header
	GetBody          func() (io.ReadCloser, error)
	ContentLength    int64
	TransferEncoding []string
	Close            bool
	Host             string
	Trailer          http.Header

	// these are handled specially, see below
	QueryParams url.Values
	Body interface{}
	Marshaler Marshaler

	// these configure how to send requests
	Doer Doer
	Middleware []Middleware

	// this configures response handling
	Unmarshaler Unmarshaler
}

These attributes can be modified directly, by assignment, or by applying Options. Options are simply functions which modify these attributes. For example:

reqr, err := requester.New(
	requester.Method("POST),
)

is equivalent to

reqr := &requester.Requester{
	Method: "POST",
}

New Requesters can be constructed with New(...Options):

reqs, err := requester.New(
	requester.Get("http://api.server/resources/1"),
	requester.JSON(),
	requester.Accept(requester.MediaTypeJSON)
)

Additional options can be applied with Apply():

err := reqs.Apply(
	requester.Method("POST"),
	requester.Body(bodyStruct),
)

...or the Requester's members can just be set directly:

reqs.Method = "POST"
reqs.Body = bodyStruct

Requesters can be cloned, creating a copy which can be further configured:

base, err := requester.New(
	requester.URL("https://api.com"),
	requester.JSON(),
	requester.Accept(requester.MediaTypeJSON),
	requester.BearerAuth(token),
)

clone = base.Clone()

err = clone.Apply(
	requester.Get("resources/1"),
)

With(...Option) combines Clone() and Apply(...Option):

clone, err := base.With(
	requester.Get("resources/1"),
)

HTTP Client Options

The HTTP client used to execute requests can also be customized with Options:

import "github.com/gemalto/requester/httpclient"

requester.Send(
	requester.Get("https://api.com"),
	requester.Client(httpclient.SkipVerify()),
)

"github.com/gemalto/requester/httpclient" is a standalone package for constructing and configuring http.Clients. The requester.Client(...httpclient.Option) option constructs a new HTTP client and installs it into Requester.Doer.

Query Params

Requester.QueryParams will be merged into any query parameters encoded into the URL. For example:

reqs, _ := requester.New(
	requester.URL("http://test.com?color=red"),
)

reqs.QueryParams = url.Values("flavor":[]string{"vanilla"})

r, _ := reqs.Request()
r.URL.String()
// Output: http://test.com?color=red&flavor=vanilla

The QueryParams() option can take a map[string]string, a map[string]interface{}, a url.Values, or a struct. Structs are marshaled into url.Values using "github.com/google/go-querystring":

type Params struct {
	Color string `url:"color"`
}

reqs, _ := requester.New(
	requester.URL("http://test.com"),
	requester.QueryParams(
		Params{Color:"blue"},
		map[string][]string{"flavor":[]string{"vanilla"}},
		map[string]string{"temp":"hot"},
		url.Values{"speed":[]string{"fast"}},
	),
	requester.QueryParam("volume","load"),
)

r, _ := reqs.Request()
r.URL.String()
// Output: http://test.com?color=blue,flavor=vanilla,temp=hot,speed=fast,volume=loud

Body

If Requester.Body is set to a string, []byte, or io.Reader, the value will be used directly as the request body:

req, _ := requester.Request(
	requester.Post("http://api.com"),
	requester.ContentType(requester.MediaTypeJSON),
	requester.Body(`{"color":"red"}`),
)

httputil.DumpRequest(req, true)

// POST / HTTP/1.1
// Host: api.com
// Content-Type: application/json
//
// {"color":"red"}

If Body is any other value, it will be marshaled into the body, using the Requester.Marshaler:

type Resource struct {
	Color string `json:"color"`
}

req, _ := requester.Request(
	requester.Post("http://api.com"),
	requester.Body(Resource{Color:"red"}),
)

httputil.DumpRequest(req, true)

// POST / HTTP/1.1
// Host: api.com
// Content-Type: application/json
//
// {"color":"red"}

Note the default marshaler is JSON, and sets the Content-Type header.

Receive

Receive() handles the response as well:

type Resource struct {
	Color string `json:"color"`
}

var res Resource

resp, body, err := requester.Receive(&res,
	requester.Get("http://api.com/resources/1",
)

fmt.Println(body)     // {"color":"red"}

The body of the response is returned. Even in cases where an error is returned, the body and the response will be returned as well, if available. This is helpful when middleware which validates aspects of the response generates an error, but the calling code still needs to inspect the contents of the body (e.g. for an error message).

If the first argument is not nil, the body will also be unmarshaled into that value. By default, the unmarshaler will use the response's Content-Type header to determine how to unmarshal the response body into a struct. This can be customized by setting Requester.Unmarshaler:

reqs.Unmarshaler = &requester.XMLMarshaler(Indent:true)                  // via assignment
reqs.Apply(requester.WithUnmarshaler(&requester.XMLMarshaler(Indent:true)))   // or via an Option

Doer and Middleware

Requester uses a Doer to execute requests, which is an interface. By default, http.DefaultClient is used, but this can be replaced by a customize client, or a mock Doer:

reqs.Doer = requester.DoerFunc(func(req *http.Request) (*http.Response, error) {
	return &http.Response{}
})

Requester itself is a Doer, so it can be nested in other Requester or composed with other packages that support Doers.

You can also install middleware into Requester, which can intercept the request and response:

mw := func(next requester.Doer) requester.Doer {
	return requester.DoerFunc(func(req *http.Request) (*http.Response, error) {
		fmt.Println(httputil.DumpRequest(req, true))
		resp, err := next(req)
		if err == nil {
			fmt.Println(httputil.DumpResponse(resp, true))
		}
		return resp, err
	})
}
reqs.Middleware = append(reqs.Middleware, mw)   // via assignment
reqs.Apply(requester.Use(mw))                    // or via option
Example
package main

import (
	"fmt"
	"github.com/gemalto/requester"
	"net/http"
	"net/http/httptest"
)

func main() {
	s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(200)
		w.Write([]byte(`{"color":"red"}`))
	}))
	defer s.Close()

	resp, body, _ := requester.Receive(
		requester.Get(s.URL),
	)

	fmt.Println(resp.StatusCode)
	fmt.Println(string(body))
}
Output:

200
{"color":"red"}
Example (Receive)
package main

import (
	"fmt"
	"github.com/gemalto/requester"
	"net/http"
	"net/http/httptest"
)

func main() {
	s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(200)
		w.Write([]byte(`{"color":"red"}`))
	}))
	defer s.Close()

	respStruct := struct {
		Color string
	}{}

	requester.Receive(&respStruct,
		requester.Get(s.URL),
	)

	fmt.Println(respStruct.Color)
}
Output:

red

Index

Examples

Constants

View Source
const (
	HeaderAccept        = "Accept"
	HeaderContentType   = "Content-Type"
	HeaderAuthorization = "Authorization"

	MediaTypeJSON          = "application/json"
	MediaTypeXML           = "application/xml"
	MediaTypeForm          = "application/x-www-form-urlencoded"
	MediaTypeOctetStream   = "application/octet-stream"
	MediaTypeTextPlain     = "text/plain"
	MediaTypeMultipart     = "multipart/mixed"
	MediaTypeMultipartForm = "multipart/form-data"
)

HTTP constants.

Variables

View Source
var DefaultRequester = Requester{}

DefaultRequester is the singleton used by the package-level Request/Send/Receive functions.

Functions

func ChannelHandler added in v0.2.0

func ChannelHandler() (chan<- *http.Response, http.Handler)

ChannelHandler returns an http.Handler and an input channel. The Handler returns the http.Responses sent to the channel.

Example
in, h := ChannelHandler()

ts := httptest.NewServer(h)
defer ts.Close()

in <- &http.Response{
	StatusCode: 201,
	Body:       ioutil.NopCloser(strings.NewReader("pong")),
}

resp, body, _ := Receive(URL(ts.URL))

fmt.Println(resp.StatusCode)
fmt.Println(string(body))
Output:

201
pong

func MockHandler added in v0.2.0

func MockHandler(statusCode int, options ...Option) http.Handler

MockHandler returns an http.Handler which returns responses built from the args. The Option arguments are used to build an http.Request, then the header and body of the request are copied into an http.Response object.

Example
h := MockHandler(201,
	JSON(false),
	Body(map[string]interface{}{"color": "blue"}),
)

ts := httptest.NewServer(h)
defer ts.Close()

resp, body, _ := Receive(URL(ts.URL))

fmt.Println(resp.StatusCode)
fmt.Println(resp.Header.Get(HeaderContentType))
fmt.Println(string(body))
Output:

201
application/json
{"color":"blue"}

func MockResponse added in v0.2.0

func MockResponse(statusCode int, options ...Option) *http.Response

MockResponse creates an *http.Response from the Options. Requests and Responses share most of the same fields, so we use the options to build a Request, then copy the values as appropriate into a Response. Useful for created mocked responses for tests.

func Receive

func Receive(successV interface{}, opts ...Option) (*http.Response, []byte, error)

Receive does the same as Requester.Receive(), using the DefaultRequester.

func ReceiveContext

func ReceiveContext(ctx context.Context, successV interface{}, opts ...Option) (*http.Response, []byte, error)

ReceiveContext does the same as Requester.ReceiveContext(), using the DefaultRequester.

func Request

func Request(opts ...Option) (*http.Request, error)

Request does the same as Requester.Request(), using the DefaultRequester.

func RequestContext

func RequestContext(ctx context.Context, opts ...Option) (*http.Request, error)

RequestContext does the same as Requester.RequestContext(), using the DefaultRequester.

func Send

func Send(opts ...Option) (*http.Response, error)

Send does the same as Requester.Send(), using the DefaultRequester.

func SendContext

func SendContext(ctx context.Context, opts ...Option) (*http.Response, error)

SendContext does the same as Requester.SendContext(), using the DefaultRequester.

Types

type Doer

type Doer interface {
	Do(req *http.Request) (*http.Response, error)
}

Doer executes http requests. It is implemented by *http.Client. You can wrap *http.Client with layers of Doers to form a stack of client-side middleware.

func Wrap

func Wrap(d Doer, m ...Middleware) Doer

Wrap applies a set of middleware to a Doer. The returned Doer will invoke the middleware in the order of the arguments.

type DoerFunc

type DoerFunc func(req *http.Request) (*http.Response, error)

DoerFunc adapts a function to implement Doer

func ChannelDoer added in v0.2.0

func ChannelDoer() (chan<- *http.Response, DoerFunc)

ChannelDoer returns a DoerFunc and a channel. The DoerFunc will return the responses send on the channel.

Example
in, d := ChannelDoer()

in <- &http.Response{
	StatusCode: 201,
	Body:       ioutil.NopCloser(strings.NewReader("pong")),
}

resp, body, _ := Receive(d)

fmt.Println(resp.StatusCode)
fmt.Println(string(body))
Output:

201
pong

func MockDoer added in v0.2.0

func MockDoer(statusCode int, options ...Option) DoerFunc

MockDoer creates a mock Doer which returns a mocked response. By default, the mocked response will contain the status code, and typical default values for some standard response fields, like the ProtoXXX fields.

Options can be passed in, which are used to construct a template http.Request. The fields of the template request are copied into the mocked responses (http.Request and http.Response share most fields, so we're leverage the rich set of requester.Options to build the response).

Example
d := MockDoer(201,
	JSON(false),
	Body(map[string]interface{}{"color": "blue"}),
)

resp, body, _ := Receive(d)

fmt.Println(resp.StatusCode)
fmt.Println(resp.Header.Get(HeaderContentType))
fmt.Println(string(body))
Output:

201
application/json
{"color":"blue"}

func (DoerFunc) Apply added in v0.2.0

func (f DoerFunc) Apply(r *Requester) error

Apply implements the Option interface. DoerFuncs can be used as requester options. They install themselves as the requester's Doer.

func (DoerFunc) Do

func (f DoerFunc) Do(req *http.Request) (*http.Response, error)

Do implements the Doer interface

type FormMarshaler

type FormMarshaler struct{}

FormMarshaler implements Marshaler. It marshals values into URL-Encoded form data.

The value can be either a map[string][]string, map[string]string, url.Values, or a struct with `url` tags.

func (*FormMarshaler) Marshal

func (*FormMarshaler) Marshal(v interface{}) (data []byte, contentType string, err error)

Marshal implements Marshaler.

type Inspector added in v0.2.0

type Inspector struct {

	// The last request sent by the client.
	Request *http.Request

	// The last response received by the client.
	Response *http.Response

	// The last client request body
	RequestBody *bytes.Buffer

	// The last client response body
	ResponseBody *bytes.Buffer
}

Inspector is a Requester Option which captures requests and responses. It's useful for inspecting the contents of exchanges in tests.

It not an efficient way to capture bodies, and keeps requests and responses around longer than their intended lifespan, so it should not be used in production code or benchmarks.

func Inspect added in v0.2.0

func Inspect(r *Requester) *Inspector

Inspect installs and returns an Inspector. The Inspector captures the last request, request body, response and response body. Useful in tests for inspecting traffic.

Example

Inspect returns an Inspector, which captures the traffic to and from a Requester. It's a tool for writing tests.

r := MustNew(
	MockDoer(201, Body("pong")),
	Header(HeaderAccept, MediaTypeTextPlain),
	Body("ping"),
)

i := Inspect(r)

r.Receive(nil)

fmt.Println(i.Request.Header.Get(HeaderAccept))
fmt.Println(i.RequestBody.String())
fmt.Println(i.Response.StatusCode)
fmt.Println(i.ResponseBody.String())
Output:

text/plain
ping
201
pong

func (*Inspector) Apply added in v0.2.0

func (i *Inspector) Apply(r *Requester) error

Apply implements Option

func (*Inspector) Clear added in v0.2.0

func (i *Inspector) Clear()

Clear clears the inspector's fields.

func (*Inspector) Wrap added in v0.2.0

func (i *Inspector) Wrap(next Doer) Doer

Wrap implements Middleware

type JSONMarshaler

type JSONMarshaler struct {
	Indent bool
}

JSONMarshaler implement Marshaler and Unmarshaler. It marshals values to and from JSON. If Indent is true, marshaled JSON will be indented.

r := requester.Requester{
    Body: &JSONMarshaler{},
}

func (*JSONMarshaler) Marshal

func (m *JSONMarshaler) Marshal(v interface{}) (data []byte, contentType string, err error)

Marshal implements Marshaler.

func (*JSONMarshaler) Unmarshal

func (m *JSONMarshaler) Unmarshal(data []byte, contentType string, v interface{}) error

Unmarshal implements Unmarshaler.

type MarshalFunc

type MarshalFunc func(v interface{}) ([]byte, string, error)

MarshalFunc adapts a function to the Marshaler interface.

func (MarshalFunc) Apply added in v0.2.0

func (f MarshalFunc) Apply(r *Requester) error

Apply implements Option. MarshalFunc can be applied as a requester option, which install itself as the Marshaler.

func (MarshalFunc) Marshal

func (f MarshalFunc) Marshal(v interface{}) ([]byte, string, error)

Marshal implements the Marshaler interface.

type Marshaler

type Marshaler interface {
	Marshal(v interface{}) (data []byte, contentType string, err error)
}

Marshaler marshals structs into a []byte, and supplies a matching Content-Type header.

var DefaultMarshaler Marshaler = &JSONMarshaler{}

DefaultMarshaler is used by Requester if Requester.Marshaler is nil.

type Middleware

type Middleware func(Doer) Doer

Middleware can be used to wrap Doers with additional functionality:

loggingMiddleware := func(next Doer) Doer {
    return func(req *http.Request) (*http.Response, error) {
        logRequest(req)
        return next(req)
    }
}

Middleware can be applied to a Requester object with the Use() option:

reqs.Apply(requester.Use(loggingMiddleware))

Middleware itself is an Option, so it can also be applied directly:

reqs.Apply(Middleware(loggingMiddleware))

func Dump

func Dump(w io.Writer) Middleware

Dump dumps requests and responses to a writer. Just intended for debugging.

func DumpToLog

func DumpToLog(logf func(a ...interface{})) Middleware

DumpToLog dumps the request and response to a logging function. logf is compatible with fmt.Print(), testing.T.Log, or log.XXX() functions.

Request and response will be logged separately. Though logf takes a variadic arg, it will only be called with one string arg at a time.

func DumpToStout added in v0.2.0

func DumpToStout() Middleware

DumpToStout dumps requests to os.Stdout.

func ExpectCode added in v0.2.0

func ExpectCode(code int) Middleware

ExpectCode is middleware which generates an error if the response's status code does not match the expected code.

Example
resp, body, err := Receive(
	Get("/profile"),
	MockDoer(400, Body("bad format")),
	ExpectCode(201),
)

fmt.Println(resp.StatusCode)
fmt.Println(string(body))
fmt.Println(err.Error())
Output:

400
bad format
server returned unexpected status code.  expected: 201, received: 400

func ExpectSuccessCode added in v0.2.0

func ExpectSuccessCode() Middleware

ExpectSuccessCode is middleware which generates an error if the response's status code is not between 200 and 299.

Example
resp, body, err := Receive(
	Get("/profile"),
	MockDoer(400, Body("bad format")),
	ExpectSuccessCode(),
)

fmt.Println(resp.StatusCode)
fmt.Println(string(body))
fmt.Println(err.Error())
Output:

400
bad format
server returned an unsuccessful status code: 400

func (Middleware) Apply

func (m Middleware) Apply(r *Requester) error

Apply implements Option

type MultiUnmarshaler

type MultiUnmarshaler struct {
	// contains filtered or unexported fields
}

MultiUnmarshaler implements Unmarshaler. It uses the value of the Content-Type header in the response to choose between the JSON and XML unmarshalers. If Content-Type is something else, an error is returned.

func (*MultiUnmarshaler) Unmarshal

func (m *MultiUnmarshaler) Unmarshal(data []byte, contentType string, v interface{}) error

Unmarshal implements Unmarshaler.

type Option

type Option interface {

	// Apply modifies the Requester argument.  The Requester pointer will never be nil.
	// Returning an error will stop applying the request of the Options, and the error
	// will float up to the original caller.
	Apply(*Requester) error
}

Option applies some setting to a Requester object. Options can be passed as arguments to most of Requester' methods.

func Accept

func Accept(accept string) Option

Accept sets the Accept header.

func AddHeader

func AddHeader(key, value string) Option

AddHeader adds a header value, using Header.Add()

func BasicAuth

func BasicAuth(username, password string) Option

BasicAuth sets the Authorization header to "Basic <encoded username and password>". If username and password are empty, it deletes the Authorization header.

func BearerAuth

func BearerAuth(token string) Option

BearerAuth sets the Authorization header to "Bearer <token>". If the token is empty, it deletes the Authorization header.

func Body

func Body(body interface{}) Option

Body sets Requester.Body

func Client

func Client(opts ...httpclient.Option) Option

Client replaces Requester.Doer with an *http.Client. The client will be created and configured using the `httpclient` package.

func ContentType

func ContentType(contentType string) Option

ContentType sets the Content-Type header.

func Delete

func Delete(paths ...string) Option

Delete sets the HTTP method to "DELETE". Optional path arguments will be applied via the RelativeURL option.

func DeleteHeader

func DeleteHeader(key string) Option

DeleteHeader deletes a header key, using Header.Del()

func Form

func Form() Option

Form sets Requester.Marshaler to the FormMarshaler, which marshals the body into form-urlencoded. The FormMarshaler will set the Content-Type header to "application/x-www-form-urlencoded" unless explicitly overwritten.

func Get

func Get(paths ...string) Option

Get sets the HTTP method to "GET". Optional path arguments will be applied via the RelativeURL option.

func Head(paths ...string) Option

Head sets the HTTP method to "HEAD". Optional path arguments will be applied via the RelativeURL option.

func Header(key, value string) Option

Header sets a header value, using Header.Set()

func Host

func Host(host string) Option

Host sets Requester.Host

func JSON

func JSON(indent bool) Option

JSON sets Requester.Marshaler to the JSONMarshaler. If the arg is true, the generated JSON will be indented. The JSONMarshaler will set the Content-Type header to "application/json" unless explicitly overwritten.

func Method

func Method(m string, paths ...string) Option

Method sets the HTTP method (e.g. GET/DELETE/etc). If path arguments are passed, they will be applied via the RelativeURL option.

func Patch

func Patch(paths ...string) Option

Patch sets the HTTP method to "PATCH". Optional path arguments will be applied via the RelativeURL option.

func Post

func Post(paths ...string) Option

Post sets the HTTP method to "POST". Optional path arguments will be applied via the RelativeURL option.

func Put

func Put(paths ...string) Option

Put sets the HTTP method to "PUT". Optional path arguments will be applied via the RelativeURL option.

func QueryParam

func QueryParam(k, v string) Option

QueryParam adds a query parameter.

func QueryParams

func QueryParams(queryStructs ...interface{}) Option

QueryParams adds params to the Requester.QueryParams member. The arguments may be either map[string][]string, map[string]string, url.Values, or a struct. The argument values are merged into Requester.QueryParams, overriding existing values.

If the arg is a struct, the struct is marshaled into a url.Values object using the github.com/google/go-querystring/query package. Structs should tag their members with the "url" tag, e.g.:

type ReqParams struct {
    Color string `url:"color"`
}

An error will be returned if marshaling the struct fails.

func RelativeURL

func RelativeURL(paths ...string) Option

RelativeURL resolves the arg as a relative URL references against the current URL, using the standard lib's url.URL.ResolveReference() method. For example:

r, _ := requester.New(Get("http://test.com"), RelativeURL("red"))
fmt.Println(r.URL.String())  // http://test.com/red

Multiple arguments will be resolved in order:

r, _ := requester.New(Get("http://test.com"), RelativeURL("red", "blue"))
fmt.Println(r.URL.String())  // http://test.com/red/blue

func URL

func URL(rawurl string) Option

URL sets the request URL. Returns an error if arg is not a valid URL.

func Use

func Use(m ...Middleware) Option

Use appends middlware to Requester.Middleware. Middleware is invoked in the order added.

func WithDoer

func WithDoer(d Doer) Option

WithDoer replaces Requester.Doer. If nil, Requester will revert to using the http.DefaultClient.

func WithMarshaler added in v0.2.0

func WithMarshaler(m Marshaler) Option

WithMarshaler sets Requester.WithMarshaler

func WithUnmarshaler added in v0.2.0

func WithUnmarshaler(m Unmarshaler) Option

WithUnmarshaler sets Requester.WithUnmarshaler

func XML

func XML(indent bool) Option

XML sets Requester.Marshaler to the XMLMarshaler. If the arg is true, the generated XML will be indented. The XMLMarshaler will set the Content-Type header to "application/xml" unless explicitly overwritten.

type OptionFunc

type OptionFunc func(*Requester) error

OptionFunc adapts a function to the Option interface.

func (OptionFunc) Apply

func (f OptionFunc) Apply(r *Requester) error

Apply implements Option.

type Requester

type Requester struct {

	// Method defaults to "GET".
	Method string
	URL    *url.URL

	// Header supplies the request headers.  If the Content-Type header
	// is explicitly set here, it will override the Content-Type header
	// supplied by the Marshaler.
	Header http.Header

	// advanced options, not typically used.  If not sure, leave them
	// blank.
	// Most of these settings are set automatically by the http package.
	// Setting them here will override the automatic values.
	GetBody          func() (io.ReadCloser, error)
	ContentLength    int64
	TransferEncoding []string
	Close            bool
	Host             string
	Trailer          http.Header

	// QueryParams are added to the request, in addition to any
	// query params already encoded in the URL
	QueryParams url.Values

	// Body can be set to a string, []byte, io.Reader, or a struct.
	// If set to a string, []byte, or io.Reader,
	// the value will be used as the body of the request.
	// If set to a struct, the Marshaler
	// will be used to marshal the value into the request body.
	Body interface{}

	// Marshaler will be used to marshal the Body value into the body
	// of requester.  It is only used if Body is a struct value.
	// Defaults to the DefaultMarshaler, which marshals to JSON.
	//
	// If no Content-Type header has been explicitly set in Requester.Header, the
	// Marshaler will supply an appropriate one.
	Marshaler Marshaler

	// Doer holds the HTTP client for used to execute requester.
	// Defaults to http.DefaultClient.
	Doer Doer

	// Middleware wraps the Doer.  Middleware will be invoked in the order
	// it is in this slice.
	Middleware []Middleware

	// Unmarshaler will be used by the Receive methods to unmarshal
	// the response body.  Defaults to DefaultUnmarshaler, which unmarshals
	// multiple content types based on the Content-Type response header.
	Unmarshaler Unmarshaler
}

Requester is an HTTP request builder and HTTP client.

Requester can be used to construct requests, send requests via a configurable HTTP client, and unmarshal the response. A Requester is configured by setting its members, which in most cases mirror the members of *http.Request. A Requester can also be configured by applying functional Options, which simply modify Requester's members.

Once configured, you can use Requester solely as a *http.Request factory, by calling Request() or RequestContext().

Requester can both construct and send requests (via a configurable Doer) with the Send() and SendContext() methods.

Finally, Requester can construct and send requests, and handle the responses with Receive() and ReceiveContext().

A Requester can be constructed as a literal:

r := requester.Requester{
         URL:    u,
         Method: "POST",
         Body:   b,
     }

...or via the New() constructor, which takes functional Options:

reqs, err := requester.New(requester.Post("http://test.com/red"), requester.Body(b))

Additional options can be applied with Apply():

err := reqs.Apply(requester.Accept("application/json"))

Requester can be cloned. The clone can then be further configured without affecting the parent:

reqs2 := reqs.Clone()
err := reqs2.Apply(Header("X-Frame","1"))

With() is equivalent to Clone() and Apply():

reqs2, err := reqs.With(requester.Header("X-Frame","1"))

The remaining methods of Requester are for creating HTTP requests, sending them, and handling the responses: Request(), Send(), and Receive().

req, err        := reqs.Request()           // create a requests
resp, err       := reqs.Send()                // create and send a request

var m Resource
resp, body, err := reqs.Receive(&m)         // create and send request, read and unmarshal response

Request(), Send(), and Receive() all accept a varargs of Options, which will be applied only to a single request, not to the Requester.

req, err 	   := reqs.Request(
                   	requester.Put("users/bob"),
                     requester.Body(bob),
                   )

RequestContext(), SendContext(), and ReceiveContext() variants accept a context, which is attached to the constructed request:

req, err        := reqs.RequestContext(ctx)

func MustNew

func MustNew(options ...Option) *Requester

MustNew creates a new Requester, applying all options. If an error occurs applying options, this will panic.

func New

func New(options ...Option) (*Requester, error)

New returns a new Requester, applying all options.

func (*Requester) Apply

func (r *Requester) Apply(opts ...Option) error

Apply applies the options to the receiver.

func (*Requester) Clone

func (r *Requester) Clone() *Requester

Clone returns a deep copy of a Requester. Useful inheriting and adding settings from a parent Requester without modifying the parent. For example,

    parent, _ := requester.New(Get("https://api.io/"))
    foo := parent.Clone()
    foo.Apply(Get("foo/"))
	   bar := parent.Clone()
    bar.Apply(Post("bar/"))

foo and bar will both use the same client, but send requests to https://api.io/foo/ and https://api.io/bar/ respectively.

func (*Requester) Do

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

Do implements Doer. Executes the request using the configured Doer and Middleware.

func (*Requester) Headers

func (r *Requester) Headers() http.Header

Headers returns the Header, initializing it if necessary. Never returns nil.

func (*Requester) MustApply

func (r *Requester) MustApply(opts ...Option)

MustApply applies the options to the receiver. Panics on errors.

func (*Requester) Params

func (r *Requester) Params() url.Values

Params returns the QueryParams, initializing them if necessary. Never returns nil.

func (*Requester) Receive

func (r *Requester) Receive(into interface{}, opts ...Option) (resp *http.Response, body []byte, err error)

Receive creates a new HTTP request and returns the response. Success responses (2XX) are unmarshaled into successV. Any error creating the request, sending it, or decoding a 2XX response is returned.

If option arguments are passed, they are applied to this single request only.

If the into argument is an Option, then it's treated like an option and not unmarshaled into.

    // these are all equivalent
    r.Receive(Get())
	   r.Receive(nil, Get())

func (*Requester) ReceiveContext

func (r *Requester) ReceiveContext(ctx context.Context, into interface{}, opts ...Option) (resp *http.Response, body []byte, err error)

ReceiveContext does the same as Receive, but requires a context.

func (*Requester) Request

func (r *Requester) Request(opts ...Option) (*http.Request, error)

Request returns a new http.Request.

If Options are passed, they will only by applied to this single request.

If r.Body is a struct, it will be marshaled into the request body using r.Marshaler. The Marshaler will also set the Content-Type header, unless this header is already explicitly set in r.Header.

If r.Body is an io.Reader, string, or []byte, it is set as the request body directly, and no default Content-Type is set.

func (*Requester) RequestContext

func (r *Requester) RequestContext(ctx context.Context, opts ...Option) (*http.Request, error)

RequestContext does the same as Request, but requires a context. Use this to set a request timeout:

req, err := r.RequestContext(context.WithTimeout(context.Background(), 10 * time.Seconds))

func (*Requester) Send

func (r *Requester) Send(opts ...Option) (*http.Response, error)

Send executes a request with the Doer. The response body is not closed: it is the caller's responsibility to close the response body. If the caller prefers the body as a byte slice, or prefers the body unmarshaled into a struct, see the Receive methods below.

Additional options arguments can be passed. They will be applied to this request only.

func (*Requester) SendContext

func (r *Requester) SendContext(ctx context.Context, opts ...Option) (*http.Response, error)

SendContext does the same as Request, but requires a context.

func (*Requester) Trailers

func (r *Requester) Trailers() http.Header

Trailers returns the Trailer, initializing it if necessary. Never returns nil.

func (*Requester) With

func (r *Requester) With(opts ...Option) (*Requester, error)

With clones the Requester object, then applies the options to the clone.

type UnmarshalFunc

type UnmarshalFunc func(data []byte, contentType string, v interface{}) error

UnmarshalFunc adapts a function to the Unmarshaler interface.

func (UnmarshalFunc) Apply added in v0.2.0

func (f UnmarshalFunc) Apply(r *Requester) error

Apply implements Option. UnmarshalFunc can be applied as a requester option, which install itself as the Unmarshaler.

func (UnmarshalFunc) Unmarshal

func (f UnmarshalFunc) Unmarshal(data []byte, contentType string, v interface{}) error

Unmarshal implements the Unmarshaler interface.

type Unmarshaler

type Unmarshaler interface {
	Unmarshal(data []byte, contentType string, v interface{}) error
}

Unmarshaler unmarshals a []byte response body into a value. It is provided the value of the Content-Type header from the response.

var DefaultUnmarshaler Unmarshaler = &MultiUnmarshaler{}

DefaultUnmarshaler is used by Requester if Requester.Unmarshaler is nil.

type XMLMarshaler

type XMLMarshaler struct {
	Indent bool
}

XMLMarshaler implements Marshaler and Unmarshaler. It marshals values to and from XML. If Indent is true, marshaled XML will be indented.

r := requester.Requester{
    Marshaler: &XMLMarshaler{},
}

func (*XMLMarshaler) Marshal

func (m *XMLMarshaler) Marshal(v interface{}) (data []byte, contentType string, err error)

Marshal implements Marshaler.

func (*XMLMarshaler) Unmarshal

func (*XMLMarshaler) Unmarshal(data []byte, contentType string, v interface{}) error

Unmarshal implements Unmarshaler.

Directories

Path Synopsis
Package clientserver is a utility for writing HTTP tests.
Package clientserver is a utility for writing HTTP tests.
Package httpclient is a set of utilities for creating and configuring instances of http.Client.
Package httpclient is a set of utilities for creating and configuring instances of http.Client.
Package httptestutil contains utilities for use in HTTP tests, particular when using httptest.Server.
Package httptestutil contains utilities for use in HTTP tests, particular when using httptest.Server.

Jump to

Keyboard shortcuts

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