sawyer

package module
v0.0.0-...-0b59bd9 Latest Latest
Warning

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

Go to latest
Published: Jul 25, 2014 License: MIT Imports: 8 Imported by: 19

README

Sawyer

Status: Very experimental

Sawyer is an HTTP user agent for REST APIs. It is a spiritual compliment to the Ruby sawyer gem.

Use this to build clients for HTTP/JSON APIs that behave like the GitHub API.

Usage

type User struct {
  Login string `json:"login"`
}

class ApiError struct {
  Message string `json:"message"`
}

client := sawyer.NewFromString("https://api.github.com")

// the GitHub API prefers a vendor media type
client.Headers.Set("Accept", "application/vnd.github+json")

apierr := &ApiError{} // decoded from response body on non-20x responses
user := &User{}
req := client.NewRequest("user/21", apierr)
res := req.Get(user)

// get the user's repositories
apierr := &ApiError{}
repos := new([]Repository)
req := client.NewRequest(res.Hyperlink("repos", sawyer.M{"page": "2"}), apierr)
res := req.Get(repos)

// post a new user
mtype := mediatype.Parse("application/vnd.github+json")
apierr := &ApiError{}
userInput := &User{Login: "bob"}
userOutput := &User{}
req := client.NewRequest("users", apierr)
err := req.SetBody(mtype, userInput)
res := req.Post(userOutput)

Documentation

Index

Constants

View Source
const (
	HeadMethod    = "HEAD"
	GetMethod     = "GET"
	PostMethod    = "POST"
	PutMethod     = "PUT"
	PatchMethod   = "PATCH"
	DeleteMethod  = "DELETE"
	OptionsMethod = "OPTIONS"
)

Variables

This section is empty.

Functions

func UseApiError

func UseApiError(status int) bool

UseApiError determines if the given status is considered an API error.

Types

type CachedResponse

type CachedResponse interface {
	Decode(*Request) *Response
	SetupRequest(*http.Request)
	IsFresh() bool
	IsExpired() bool
}

CachedResponse is an interface for the httpcache CachedResponseDecoder.

type Cacher

type Cacher interface {
	// Get gets a CachedResponse for the given request.
	Get(*http.Request) (CachedResponse, error)

	// Set caches the response for the given request.
	Set(*http.Request, *Response) error

	// Reset removes the cached response and body, but leaves the cached relations.
	Reset(*http.Request) error

	// Clear removes all cached information for the request.
	Clear(*http.Request) error

	// UpdateCache updates the cache for the given request with the expiration from
	// the response.
	UpdateCache(*http.Request, *http.Response) error

	// SetRels caches the given relations for the request.
	SetRels(*http.Request, hypermedia.Relations) error

	// Rels gets the cached relations for the given request.
	Rels(*http.Request) (hypermedia.Relations, bool)
}

A Cacher has the ability to get and set caches for HTTP requests and resource relations. See the sawyer/httpcache package.

type Client

type Client struct {
	HttpClient *http.Client
	Endpoint   *url.URL
	Header     http.Header
	Query      url.Values
	Cacher     Cacher
}

A Client wraps an *http.Client with a base url Endpoint and common header and query values.

func New

func New(endpoint *url.URL, client *http.Client) *Client

New returns a new Client with a given a URL and an optional client.

func NewFromString

func NewFromString(endpoint string, client *http.Client) (*Client, error)

NewFromString returns a new Client given a string URL and an optional client.

func (*Client) NewRequest

func (c *Client) NewRequest(rawurl string) (*Request, error)

NewRequest creates a new sawyer.Request for the given relative url path, with any default headers or query parameters specified on Client. The Request URL is resolved to an absolute URL.

func (*Client) Rels

func (c *Client) Rels(req *Request, value interface{}) (hypermedia.Relations, *Response)

Rels attempts to get the cached relations for the given request. If it hasn't been cached, send a GET to the request URL, decode the response body to the given value, and get the relations from the value.

func (*Client) ResolveReference

func (c *Client) ResolveReference(u *url.URL) *url.URL

ResolveReference resolves a URI reference to an absolute URI from an absolute base URI. It also merges the query values.

func (*Client) ResolveReferenceString

func (c *Client) ResolveReferenceString(rawurl string) (string, error)

ResolveReference resolves a string URI reference to an absolute URI from an absolute base URI. It also merges the query values.

type Request

type Request struct {
	Client    *http.Client
	MediaType *mediatype.MediaType
	Query     url.Values
	Cacher    Cacher
	*http.Request
}

Request is a wrapped net/http Request with a pointer to the net/http Client, MediaType, parsed URI query, and the configured Cacher. Requests are capable of returning a sawyer Response with Do() or the HTTP verb helpers (Get(), Head(), Post(), etc).

func (*Request) Delete

func (r *Request) Delete() *Response

Delete is a helper method for Do().

func (*Request) Do

func (r *Request) Do(method string) *Response

Do completes the HTTP request, returning a response. The Request's Cacher is used to return a cached response if available. Otherwise, the request goes through and fills the cache for future requests.

func (*Request) Get

func (r *Request) Get() *Response

Get is a helper method for Do().

func (*Request) Head

func (r *Request) Head() *Response

Head is a helper method for Do().

func (*Request) Options

func (r *Request) Options() *Response

Options is a helper method for Do().

func (*Request) Patch

func (r *Request) Patch() *Response

Patch is a helper method for Do().

func (*Request) Post

func (r *Request) Post() *Response

Post is a helper method for Do().

func (*Request) Put

func (r *Request) Put() *Response

Put is a helper method for Do().

func (*Request) SetBody

func (r *Request) SetBody(mtype *mediatype.MediaType, resource interface{}) error

SetBody encodes and sets the proper headers for the request body from the given resource. The resource is encoded in-memory, so be careful about passing a massive object. You can set the ContentLength and Body properties manually.

type Response

type Response struct {
	// ResponseError stores any errors made making the HTTP request.  If set, then
	// AnyError() and IsError() will return true, and Error() will delegate to it.
	ResponseError error
	MediaType     *mediatype.MediaType
	BodyClosed    bool
	Cacher        Cacher

	*http.Response
	// contains filtered or unexported fields
}

Response is a wrapped net/http Response with a pointer to the MediaType and the cacher. It also doubles as a possible error object.

func ResponseError

func ResponseError(err error) *Response

ResponseError returns an empty Response with the ResponseError set from the given error.

func (*Response) AnyError

func (r *Response) AnyError() bool

AnyError returns true if the HTTP request returned an error, or if the response status is not a 2xx code.

func (*Response) CacheRels

func (r *Response) CacheRels(rels hypermedia.Relations)

CacheRels will set the given relations for this resource.

func (*Response) Decode

func (r *Response) Decode(resource interface{}) error

Decode will decode the body into the given resource, and parse the hypermedia relations. This is meant to be called after an HTTP request, and will close the response body. The decoder is set from the response's MediaType.

func (*Response) DecodeFrom

func (r *Response) DecodeFrom(resource interface{}, body io.Reader) error

DecodeFrom decodes the resource from the given io.Reader, using the decoder from the response's MediaType.

func (*Response) Error

func (r *Response) Error() string

Error returns the ResponseError's error string if set, or an empty string.

func (*Response) HypermediaRels

func (r *Response) HypermediaRels(rels hypermedia.Relations)

HypermediaRels implements the hypermedia.HypermediaResource interface. The relations are parsed from the Link header.

func (*Response) IsApiError

func (r *Response) IsApiError() bool

IsApiError returns true if the response status is not a 2xx code.

func (*Response) IsError

func (r *Response) IsError() bool

IsError returns true if the HTTP request returned an error.

func (*Response) Rels

func (r *Response) Rels() (hypermedia.Relations, bool)

Rels returns the cached relations if they have been set.

Directories

Path Synopsis
Package httpcache provides facilities for caching HTTP responses and hypermedia for REST resources.
Package httpcache provides facilities for caching HTTP responses and hypermedia for REST resources.
Package hypermedia provides helpers for parsing hypermedia links in resources and expanding the links to make further requests.
Package hypermedia provides helpers for parsing hypermedia links in resources and expanding the links to make further requests.
Package mediatype contains helpers for parsing media type strings.
Package mediatype contains helpers for parsing media type strings.

Jump to

Keyboard shortcuts

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