restful

package
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Apr 11, 2019 License: MIT Imports: 23 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func InjectCanaryAttr

func InjectCanaryAttr(json io.Reader, attrName string) io.Reader

InjectCanaryAttr injects an attribute into an io.Reader that contains JSON

func PlaceholderLogger

func PlaceholderLogger() logSet

PlaceholderLogger returns a log set that fulfills the restful logging interface - a convenience for when you don't want or need to wrap a logger in appropriate interface fulfillment.

func Retryable

func Retryable(err error) bool

Retryable is a predicate on error that returns true if the error indicates that a subsequent attempt at e.g. an Update might succeed.

Types

type Comparable

type Comparable interface {
	// EmptyReceiver should return a pointer to an "zero value" for the recieving type.
	// For example:
	//   func (x *X) EmptyReceiver() Comparable { return &X{} }
	EmptyReceiver() Comparable

	// VariancesFrom returns a list of differences from another Comparable.
	// If the two structs are equivalent, it should return an empty list.
	// Usually, the first check will be for identical type, and return "types differ."
	VariancesFrom(Comparable) Variances
}

Comparable is a required interface for Update and Delete, which provides the mechanism for comparing the remote resource to the local data.

type Deleteable

type Deleteable interface {
	Delete(*RouteMap, logging.LogSink, http.ResponseWriter, *http.Request, httprouter.Params) Exchanger
}

Deleteable tags ResourceFamilies that respond to DELETE

type Deleter

type Deleter interface {
	Delete(headers map[string]string) error
}

A Deleter captures the state of a retrieved resource so that it can be later deleted.

type DummyHTTPClient

type DummyHTTPClient struct {
	// Error returned by all calls.
	AlwaysReturnErr error
}

DummyHTTPClient doesn't really make HTTP requests.

func (*DummyHTTPClient) Create

func (d *DummyHTTPClient) Create(urlPath string, qParms map[string]string, rqBody interface{}, headers map[string]string) (UpdateDeleter, error)

Create implements HTTPClient on DummyHTTPClient - it does nothing and returns nil.

func (*DummyHTTPClient) Retrieve

func (d *DummyHTTPClient) Retrieve(urlPath string, qParms map[string]string, rzBody interface{}, headers map[string]string) (UpdateDeleter, error)

Retrieve implements HTTPClient on DummyHTTPClient - it does nothing and returns nil

type ExchangeFactory

An ExchangeFactory builds an Exchanger - they're used to configure the RouteMap

type ExchangeLogger

type ExchangeLogger struct {
	Exchanger Exchanger
	logging.LogSink
	*http.Request
	httprouter.Params
}

ExchangeLogger wraps and logs the exchange.

func (*ExchangeLogger) Exchange

func (xlog *ExchangeLogger) Exchange() (data interface{}, status int)

Exchange implements Exchanger on ExchangeLogger.

type Exchanger

type Exchanger interface {
	Exchange() (interface{}, int)
}

A Exchanger has an Exchange method - which is presumed to write to an injected ResponseWriter

type Getable

Getable tags ResourceFamilies that respond to GET

type HTTPClient

type HTTPClient interface {
	Create(urlPath string, qParms map[string]string, rqBody interface{}, headers map[string]string) (UpdateDeleter, error)
	Retrieve(urlPath string, qParms map[string]string, rzBody interface{}, headers map[string]string) (UpdateDeleter, error)
}

HTTPClient interacts with a HTTPServer

It's designed to handle basic CRUD operations in a safe and restful way.

func NewInMemoryClient

func NewInMemoryClient(handler http.Handler, ls logging.LogSink, headers ...map[string]string) (HTTPClient, error)

NewInMemoryClient wraps a MemoryListener in a restful.Client

type HTTPClientWithContext

type HTTPClientWithContext interface {
	CreateCtx(ctx context.Context, urlPath string, qParms map[string]string, rqBody interface{}, headers map[string]string) (UpdateDeleter, error)
	RetrieveCtx(ctx context.Context, ctrlpath string, qparms map[string]string, rzbody interface{}, headers map[string]string) (UpdateDeleter, error)
}

HTTPClientWithContext interacts with a HTTPServer

It's designed to handle basic CRUD operations in a safe and restful way, adding context.

type HeaderAdder

type HeaderAdder interface {
	AddHeaders(header http.Header)
}

HeaderAdder is an interface for response bodies to use to set headers

type Injector

type Injector interface {
	Inject(...interface{}) error
	MustInject(...interface{})
	Add(...interface{})
}

Injector is an interface for DI systems.

type KV

type KV []string

KV (Key/Value) is a convenience type for URIFor.

type LiveHTTPClient

type LiveHTTPClient struct {
	http.Client
	logging.LogSink
	// contains filtered or unexported fields
}

LiveHTTPClient interacts with a Sous http server.

It's designed to handle basic CRUD operations in a safe and restful way.

func NewClient

func NewClient(serverURL string, ls logging.LogSink, headers ...map[string]string) (*LiveHTTPClient, error)

NewClient returns a new LiveHTTPClient for a particular serverURL.

func (*LiveHTTPClient) Create

func (client *LiveHTTPClient) Create(urlPath string, qParms map[string]string, qBody interface{}, headers map[string]string) (UpdateDeleter, error)

Create uses the contents of qBody to create a new resource at the server at urlPath/qParms It issues a PUT with "If-No-Match: *", so if a resource already exists, it'll return an error.

func (*LiveHTTPClient) CreateCtx

func (client *LiveHTTPClient) CreateCtx(ctx context.Context, urlPath string, qParms map[string]string, qBody interface{}, headers map[string]string) (UpdateDeleter, error)

CreateCtx Add context to Create to ability to cancel

func (*LiveHTTPClient) Retrieve

func (client *LiveHTTPClient) Retrieve(urlPath string, qParms map[string]string, rzBody interface{}, headers map[string]string) (UpdateDeleter, error)

Retrieve makes a GET request on urlPath, after transforming qParms into ?&= style query params. It deserializes the returned JSON into rzBody. Errors are returned if anything goes wrong, including a non-Success HTTP result (but note that there may be a response anyway. It returns an Updater so that the resource can be updated later

func (*LiveHTTPClient) RetrieveCtx

func (client *LiveHTTPClient) RetrieveCtx(ctx context.Context, urlPath string, qParms map[string]string, rzBody interface{}, headers map[string]string) (UpdateDeleter, error)

RetrieveCtx Add context to Retrieve to ability to cancel

type MetaHandler

type MetaHandler struct {
	logging.LogSink
	// contains filtered or unexported fields
}

The MetaHandler collects common behavior for route handlers.

func (*MetaHandler) DeleteHandling

func (mh *MetaHandler) DeleteHandling(resName string, factory ExchangeFactory) httprouter.Handle

DeleteHandling handles Delete requests.

func (*MetaHandler) GetHandling

func (mh *MetaHandler) GetHandling(resName string, factory ExchangeFactory) httprouter.Handle

GetHandling handles Get requests.

func (*MetaHandler) HeadHandling

func (mh *MetaHandler) HeadHandling(resName string, factory ExchangeFactory) httprouter.Handle

HeadHandling handles Head requests.

func (*MetaHandler) InstallPanicHandler

func (mh *MetaHandler) InstallPanicHandler()

InstallPanicHandler installs an panic handler into the router.

func (*MetaHandler) OptionsHandling

func (mh *MetaHandler) OptionsHandling(resName string, factory ExchangeFactory) httprouter.Handle

OptionsHandling handles Options requests.

func (*MetaHandler) PutHandling

func (mh *MetaHandler) PutHandling(resName string, factory ExchangeFactory) httprouter.Handle

PutHandling handles PUT requests.

type Optionsable

type Optionsable interface {
	Options(*RouteMap, logging.LogSink, http.ResponseWriter, *http.Request, httprouter.Params) Exchanger
}

Optionsable tags ResourceFamilies that respond to OPTIONS

type Putable

Putable tags ResourceFamilies that respond to PUT

type QueryParser

type QueryParser struct{}

QueryParser is a convenience embed for parsing query values

func (QueryParser) ParseQuery

func (QueryParser) ParseQuery(req *http.Request) QueryValues

ParseQuery parses query values out of a url, returning an empty list of values in the event of an error

type QueryValues

type QueryValues struct {
	url.Values
}

QueryValues wrap url.Values to provide a few convenience methods

func (QueryValues) Single

func (qv QueryValues) Single(field string, def ...string) (string, error)

Single returns a singular value for a query field, or an error if the field is missing (and no default is supplied) or if multiple values are supplied

type Resource

type Resource interface{}

A Resource bundles up the exchangers that deal with a kind of resources (n.b. that properly, URL == resource, so a URL pattern == many resources

type ResponseWriter

type ResponseWriter struct {
	http.ResponseWriter
}

ResponseWriter wraps the the http.ResponseWriter interface. XXX This is a workaround for Psyringe

type RouteEntryBuilder

type RouteEntryBuilder func(name string, path string, resource Resource)

RouteEntryBuilder is used to provide a concise way to define a route entry to BuildRouteMap (c.f.)

type RouteMap

type RouteMap []routeEntry

RouteMap is a list of entries for routing

func BuildRouteMap

func BuildRouteMap(f func(RouteEntryBuilder)) *RouteMap

BuildRouteMap receives a function that will define the route map. It passes in a constructor for route entries, and appends the ones constructed to the RouteMap.

BuildRouteMap(func(re RouteEntryBuilder){
  re("me", "/author", newAuthorResource())
})

This probably deserves a full example.

func (*RouteMap) BuildRouter

func (rm *RouteMap) BuildRouter(ls logging.LogSink) http.Handler

BuildRouter builds a returns an http.Handler based on some constant configuration

func (RouteMap) FullURIFor

func (rm RouteMap) FullURIFor(hostName string, name string, pathParams map[string]string, kvs ...KV) (string, error)

FullURIFor returns the hostname with the uri appended

func (*RouteMap) SingleExchanger

func (rm *RouteMap) SingleExchanger(factory ExchangeFactory, gf func() Injector, ls logging.LogSink) Exchanger

SingleExchanger returns a single exchanger for the given exchange factory and injector factory. Can be useful in testing or trickier integrations.

func (RouteMap) URIFor

func (rm RouteMap) URIFor(name string, pathParams map[string]string, kvs ...KV) (string, error)

URIFor returns the URI (relative to the root) for the named route using pathParams and kv to fill out path parameters and query values respectively.

type StatusMiddleware

type StatusMiddleware struct {
	logging.LogSink
	// contains filtered or unexported fields
}

A StatusMiddleware processes panics into 500s and other status codes.

func (*StatusMiddleware) HandlePanic

func (ph *StatusMiddleware) HandlePanic(w http.ResponseWriter, r *http.Request, recovered interface{})

HandlePanic returns a 500 and logs the error. It uses the LogSet provided by the graph.

func (*StatusMiddleware) HandleResponse

func (ph *StatusMiddleware) HandleResponse(status int, r *http.Request, w http.ResponseWriter, data interface{})

HandleResponse returns empty responses. It uses the LogSet provided by the graph.

type TraceID

type TraceID string

A TraceID is the header to add to requests for tracing purposes.

func (TraceID) EachField

func (tid TraceID) EachField(fn logging.FieldReportFn)

EachField implements EachFielder on TraceID

type UpdateDeleter

type UpdateDeleter interface {
	Updater
	Deleter
	Location() string
}

An UpdateDeleter allows for a given resource to be updated or deleted.

type Updater

type Updater interface {
	Update(body Comparable, headers map[string]string) (UpdateDeleter, error)
}

An Updater captures the state of a retrieved resource so that it can be updated later.

type Variances

type Variances []string

Variances is a list of differences between two structs.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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