rq

package module
v0.0.0-...-b7f1a03 Latest Latest
Warning

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

Go to latest
Published: Mar 3, 2020 License: MIT Imports: 13 Imported by: 0

README

github.com/tetratom/rq

GoDoc CircleCI Codecov

rq is a no-nonsense library for working with rest apis

highlights

  • request constructors pass values: one rq.Request can be used as the basis of another without copy concerns
  • easy access to common operations: Path(), Queryf(), SetHeader(), Is2xx(), and many more
  • support for arbitrary request, response middleware, and marshallers
  • context-first

example

import "github.com/tetratom/rq"

req := rq.
    Begin("https://httpbin.org").
    Path("get").
    Queryf("x", "y%d", 1)

rep, err := req.GET(context.Background())
switch {
case err != nil:
    panic(err)
case !rep.Is2xx():
    panic("bad response!")
}

log.Printf("response: %s", rep.ReadStringOrPanic())

Documentation

Overview

rq is a wrapper for go's http client.

Example (SigningMiddleware)
package main

import (
	"context"
	"crypto/md5"
	"encoding/hex"
	"errors"
	"fmt"
	"github.com/tetratom/rq"
	"io"
	"io/ioutil"
)

// NewRequestSigningMiddleware returns a rq request middleware that generates
// an example digest based on a secret value and the request body (if any).
// The result is the X-Request-Signature header, a hex-encoded MD5 hash.
//
// If the request has a body, it will be fully buffered into memory.
func NewRequestSigningMiddleware(secret string) rq.RequestMiddleware {
	return func(req rq.Request) rq.Request {
		digest := md5.New()
		io.WriteString(digest, secret)

		if req.Body != nil {
			data, _ := ioutil.ReadAll(req.Body.Reader())
			digest.Write(data)
			req = req.SetBodyBytes(data)
		}

		return req.
			SetHeader(
				"X-Request-Signature",
				hex.EncodeToString(digest.Sum(nil)))
	}
}

// NewResponseVerifyingMiddleware returns a rq response middleware that converts
// a successful response into a failure if the response did not include the
// X-Response-Signature header.
func NewResponseVerifyingMiddleware() rq.ResponseMiddleware {
	return func(req rq.Request, rep rq.Response, err error) (rq.Response, error) {
		if err != nil {
			return rep, err
		}

		if !rep.HasHeader("X-Response-Signature") {
			return rep, errors.New("no response signature")
		}

		return rep, nil
	}
}

func main() {
	api := rq.
		Begin("http://httpbin.org").
		Path("anything").
		AddRequestMiddlewares(NewRequestSigningMiddleware("much secure"))

	var response HTTPBinResponse
	rep, _ := api.SetBodyString("very covert").GET(context.TODO())
	rep.UnmarshalJSON(&response)
	fmt.Println("first request")
	fmt.Println("signature:", response.Headers["X-Request-Signature"])
	fmt.Println("body:", response.Data)

	_, err := api.
		AddResponseMiddlewares(NewResponseVerifyingMiddleware()).
		GET(context.TODO())
	fmt.Println("second request")
	fmt.Println("error:", err) // error: no response signature

}
Output:

first request
signature: 121aa41cde97e6d27d468e743a8c05a6
body: very covert
second request
error: no response signature

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func UnmarshalJSON

func UnmarshalJSON(response Response, value interface{}) error

func UnmarshalXML

func UnmarshalXML(response Response, value interface{}) error

Types

type Header struct {
	Name  string
	Value string
}

type Marshaller

type Marshaller func(Request, interface{}) Request

Marshaller is a function for marshalling the given value into the given request. The marshaller is expected to set any additional relevant properties, such as the Content-Type header.

If marshalling fails, the error of the resultant request should be set using SetError().

type Request

type Request struct {
	URL                 url.URL
	Method              string
	Headers             []Header
	Client              *http.Client
	Body                RequestBody
	RequestMiddlewares  []RequestMiddleware
	ResponseMiddlewares []ResponseMiddleware
	Marshaller          Marshaller
	Unmarshaller        Unmarshaller
	// contains filtered or unexported fields
}

func Begin

func Begin(url string) Request

Begin creates an otherwise empty rq.Request with the given base URL.

func FormMarshaller

func FormMarshaller(req Request, value interface{}) Request

func JSONMarshaller

func JSONMarshaller(req Request, value interface{}) Request

func NOOPMarshaller

func NOOPMarshaller(req Request, _ interface{}) Request

func SetURL

func SetURL(url string) Request

SetURL is an alias for Begin().

func XMLMarshaller

func XMLMarshaller(req Request, value interface{}) Request

func (Request) AddHeader

func (req Request) AddHeader(name string, value string, args ...interface{}) Request

func (Request) AddQueryf

func (req Request) AddQueryf(name string, value string, args ...interface{}) Request

func (Request) AddRequestMiddlewares

func (req Request) AddRequestMiddlewares(middlewares ...RequestMiddleware) Request

func (Request) AddResponseMiddlewares

func (req Request) AddResponseMiddlewares(middlewares ...ResponseMiddleware) Request

func (Request) DELETE

func (req Request) DELETE(ctx context.Context) (Response, error)

func (Request) Do

func (req Request) Do(ctx context.Context) (Response, error)

func (Request) GET

func (req Request) GET(ctx context.Context) (Response, error)

func (Request) GetContext

func (req Request) GetContext() context.Context

GetContext returns the context currently associated with the request. The context is set as part of an execution method, so this is only useful in middlewares.

func (Request) GetError

func (req Request) GetError() error

func (Request) GetFragment

func (req Request) GetFragment() string

func (Request) GetHeader

func (req Request) GetHeader(name string) string

func (Request) GetQuery

func (req Request) GetQuery(name string) string

func (Request) HasError

func (req Request) HasError() bool

func (Request) HasHeader

func (req Request) HasHeader(name string) bool

func (Request) HeaderMap

func (req Request) HeaderMap() http.Header

HeaderMap returns a copy of the headers assigned to this request.

Modifying the map will affect the request.

func (Request) Map

func (req Request) Map(mapper func(Request) Request) Request

func (Request) MapHeaders

func (req Request) MapHeaders(f func([]Header) []Header) Request

func (Request) MapURL

func (req Request) MapURL(f func(url url.URL) url.URL) Request

func (Request) Marshal

func (req Request) Marshal(value interface{}) Request

Marshal sets the body of the request by marshalling the given value using the Marshaller set on the request object. If none is set, it is marshalled using the MarshalJSON() method of the request.

func (Request) MarshalForm

func (req Request) MarshalForm(value url.Values) Request

func (Request) MarshalJSON

func (req Request) MarshalJSON(value interface{}) Request

MarshalJSON marshals the given value using the default JSON marshaller. The Content-Type of the request will be set to "application/json; charset=utf-8".

func (Request) MarshalXML

func (req Request) MarshalXML(value interface{}) Request

MarshalXML marshals the given value using the default XML marshaller. The Content-Type of the request will be set to "text/xml; charset=utf-8".

func (Request) PATCH

func (req Request) PATCH(ctx context.Context) (Response, error)

func (Request) POST

func (req Request) POST(ctx context.Context) (Response, error)

func (Request) PUT

func (req Request) PUT(ctx context.Context) (Response, error)

func (Request) Path

func (req Request) Path(segments ...string) Request

func (Request) Pathf

func (req Request) Pathf(segment string, args ...interface{}) Request

func (Request) Prepare

func (req Request) Prepare(ctx context.Context) (*http.Request, error)

Prepare builds the native http.Request that will be used for the HTTP request. It returns a new instance of request

func (Request) RemoveHeader

func (req Request) RemoveHeader(name string) Request

func (Request) RemoveQuery

func (req Request) RemoveQuery(name string) Request

func (Request) ReplaceQuery

func (req Request) ReplaceQuery(query url.Values) Request

func (Request) SetApiKey

func (req Request) SetApiKey(key string) Request

func (Request) SetBasicAuth

func (req Request) SetBasicAuth(username, password string) Request

func (Request) SetBearerToken

func (req Request) SetBearerToken(token string) Request

func (Request) SetBody

func (req Request) SetBody(body RequestBody) Request

func (Request) SetBodyBytes

func (req Request) SetBodyBytes(data []byte) Request

func (Request) SetBodyReader

func (req Request) SetBodyReader(r io.Reader) Request

func (Request) SetBodyString

func (req Request) SetBodyString(data string) Request

func (Request) SetClient

func (req Request) SetClient(client *http.Client) Request

func (Request) SetError

func (req Request) SetError(err error) Request

SetError is used to taint a Request. Builder methods can continue to change the request, but executing the request will fail with the given error immediately.

The request can be un-tainted with SetError(nil).

func (Request) SetFragment

func (req Request) SetFragment(fragment string) Request

func (Request) SetHeader

func (req Request) SetHeader(name string, value string, args ...interface{}) Request

func (Request) SetMarshaller

func (req Request) SetMarshaller(marshaller Marshaller) Request

func (Request) SetMethod

func (req Request) SetMethod(method string) Request

func (Request) SetQueryf

func (req Request) SetQueryf(name string, value string, args ...interface{}) Request

func (Request) SetRequestMiddlewares

func (req Request) SetRequestMiddlewares(middlewares ...RequestMiddleware) Request

func (Request) SetResponseMiddlewares

func (req Request) SetResponseMiddlewares(middlewares ...ResponseMiddleware) Request

func (Request) SetURL

func (req Request) SetURL(value string) Request

func (Request) SetUnmarshaller

func (req Request) SetUnmarshaller(unmarshaller Unmarshaller) Request

func (Request) SetUserAgent

func (req Request) SetUserAgent(ua string) Request

type RequestBody

type RequestBody interface {
	Reader() io.Reader
}

RequestBody produces readers for requests. Any time a request is executed, the body is set to be the reader returned by Reader(). If a RequestBody is to be reused, the implementation must ensure that every call to Reader() returns a new io.Reader that starts from the beginning.

type RequestBodyBytes

type RequestBodyBytes struct {
	Data []byte
}

RequestBodyBytes is a reusable request body of bytes.

func (*RequestBodyBytes) Reader

func (rbb *RequestBodyBytes) Reader() io.Reader

type RequestBodyReader

type RequestBodyReader struct {
	BodyReader io.Reader
}

func (*RequestBodyReader) Reader

func (rbb *RequestBodyReader) Reader() io.Reader

type RequestBodyString

type RequestBodyString struct {
	Data string
}

func (*RequestBodyString) Reader

func (rbb *RequestBodyString) Reader() io.Reader

type RequestMiddleware

type RequestMiddleware func(Request) Request

type Response

type Response struct {
	Underlying        *http.Response
	Unmarshaller      Unmarshaller
	IgnoreContentType bool
}

func (Response) Close

func (resp Response) Close() error

func (*Response) GetHeader

func (resp *Response) GetHeader(name string) string

func (*Response) HasHeader

func (resp *Response) HasHeader(name string) bool

func (Response) IgnoringContentType

func (resp Response) IgnoringContentType() Response

func (Response) Is1xx

func (resp Response) Is1xx() bool

func (Response) Is2xx

func (resp Response) Is2xx() bool

func (Response) Is3xx

func (resp Response) Is3xx() bool

func (Response) Is4xx

func (resp Response) Is4xx() bool

func (Response) Is5xx

func (resp Response) Is5xx() bool

func (*Response) LookupHeader

func (resp *Response) LookupHeader(name string) (string, bool)

func (Response) Map

func (resp Response) Map(f func(Response) Response) Response

func (Response) ReadAll

func (resp Response) ReadAll() ([]byte, error)

func (Response) ReadString

func (resp Response) ReadString() (string, error)

func (Response) ReadStringOrPanic

func (resp Response) ReadStringOrPanic() string

func (Response) Status

func (resp Response) Status() int

func (Response) StatusOneOf

func (resp Response) StatusOneOf(statuses ...int) bool

func (Response) Unmarshal

func (resp Response) Unmarshal(v interface{}) error

func (Response) UnmarshalJSON

func (resp Response) UnmarshalJSON(v interface{}) error

func (Response) UnmarshalXML

func (resp Response) UnmarshalXML(v interface{}) error

type ResponseMiddleware

type ResponseMiddleware func(req Request, rep Response, err error) (Response, error)

ResponseMiddleware intercepts a response. It is also called in case of a request failure, in which case `rep` may be empty, and `err` non-nil. The middleware is expected to return (rep, err) immediately if it is not designed to handle an erroneous response.

The `req` passed to the middleware is exactly the same as was used for the original request. Use req.GetContext() to obtain the request context.

type Unmarshaller

type Unmarshaller func(Response, interface{}) error

Jump to

Keyboard shortcuts

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