resource

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

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

Go to latest
Published: Jun 4, 2019 License: MIT Imports: 16 Imported by: 0

README

resource

Simple resource abstraction for golang. Inspired by Spring's Resource API.

Documentation

Overview

Package resource provides an abstraction for loading external data from multiple sources in a manner compatible with dependency injection and configuration-driven programming.

Index

Constants

View Source
const (
	SchemeSeparator = "://"

	StringScheme = "string"
	BytesScheme  = "bytes"
	FileScheme   = "file"
	HTTPScheme   = "http"
	HTTPSScheme  = "https"
)
View Source
const DefaultEnvFunc = "env"

DefaultEnvFunc is the default key in a template.FuncMap that maps to Getenv.

Variables

View Source
var ErrTooManyDefaults = errors.New("Too many default values")

Functions

func ConfigureTemplateDefaults

func ConfigureTemplateDefaults(t *template.Template) *template.Template

ConfigureTemplateDefaults is used to set up the defaults for a resource template. This function is useful when using an arbitrary template as the parent for parsing.

func DrainOnClose

func DrainOnClose(rc io.ReadCloser) io.ReadCloser

DrainOnClose decorates an existing io.ReadCloser such that invoking Close on the returned io.ReadCloser causes any remaining contents to be discarded. Used by HTTP resources to ensure that the HTTP response body is fully read when client code closes the resource's io.ReadCloser returned by Open.

func Getenv

func Getenv(key string, def ...string) (string, error)

Getenv is an analog to os.Getenv that allows for an optional default value to be used when the given environment variable is not present. Supplying multiple default values raises an error.

func Split

func Split(v string) (scheme, value string)

Split parses a resource value into its scheme and value. This is much more relaxed than url.Parse, as it permits characters that are not allowed in URIs. This fact is importent when allowing arbitrary strings or bytes as in-memory resources.

Types

type Bytes

type Bytes []byte

Bytes represents an in-memory resource backed by a byte slice.

func (Bytes) Location

func (b Bytes) Location() string

func (Bytes) Open

func (b Bytes) Open() (io.ReadCloser, error)

func (Bytes) WriteTo

func (b Bytes) WriteTo(w io.Writer) (int64, error)

type BytesResolver

type BytesResolver struct {
	// Encoding is the base64 encoding to use.  If not supplied, base64.StdEncoding is used.
	Encoding *base64.Encoding
}

BytesResolver resolves values as in-memory bytes encoding as base64 strings. The choice of encoding is configurable, and defaults to base64.StdEncoding. Any scheme is ignored by this resolver, allowing it to be mapped to any desired scheme.

func (BytesResolver) Resolve

func (r BytesResolver) Resolve(v string) (Interface, error)

type File

type File string

File represents a resource backed by a system file.

func (File) Location

func (f File) Location() string

func (File) Open

func (f File) Open() (io.ReadCloser, error)

func (File) WriteTo

func (f File) WriteTo(w io.Writer) (int64, error)

type FileResolver

type FileResolver struct {
	// Root is the optional file system path that acts as the logical root directory
	// for any resource strings this instance resolves.  If not supplied, no root is assumed.
	Root string
}

FileResolver resolves values as file system paths, relative to an optional Root directory. Any scheme is ignored by this resolver.

func (FileResolver) Resolve

func (r FileResolver) Resolve(v string) (Interface, error)

type HTTP

type HTTP struct {
	// URL is the required URL of the resource
	URL string

	// OpenMethod is the HTTP verb used to request the resource's data.  If not
	// supplied, GET is used.
	OpenMethod string

	// Client is the HTTP client to use to obtain the resource.  If not supplied,
	// http.DefaultClient is used.
	Client HTTPClient
}

HTTP represents a resource backed by an HTTP or HTTPS URL.

func (HTTP) Location

func (h HTTP) Location() string

func (HTTP) Open

func (h HTTP) Open() (io.ReadCloser, error)

func (HTTP) WriteTo

func (h HTTP) WriteTo(w io.Writer) (int64, error)

type HTTPClient

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

HTTPClient is the method set expected of an object which can transact with an HTTP server. http.Client implements this interface.

func WithClose

func WithClose(c HTTPClient) HTTPClient

WithClose decorates an HTTPClient, setting the Request.Close flag for each request

func WithHeader

func WithHeader(name, value string, c HTTPClient) HTTPClient

WithHeader decorates an HTTPClient, setting a single HTTP header name/value on each request

func WithHeaders

func WithHeaders(h http.Header, c HTTPClient) HTTPClient

WithHeaders decorates an HTTPClient, copying a set of headers onto each request

func WithMethod

func WithMethod(method string, c HTTPClient) HTTPClient

WithMethod decorates an HTTPClient, setting a specific HTTP method on each request

func WithTimeout

func WithTimeout(d time.Duration, c HTTPClient) HTTPClient

WithTimeout decorates an HTTPClient, creating a context with a timeout for each request

type HTTPClientFunc

type HTTPClientFunc func(*http.Request) (*http.Response, error)

func (HTTPClientFunc) Do

func (f HTTPClientFunc) Do(request *http.Request) (*http.Response, error)

type HTTPError

type HTTPError struct {
	URL  string
	Code int
}

HTTPError represents a failure to obtain an HTTP resource. This error indicates that a successful HTTP transaction occurred with a non-2XX response code.

func (HTTPError) Error

func (he HTTPError) Error() string

func (HTTPError) StatusCode

func (he HTTPError) StatusCode() int

StatusCode is supplied to implement go-kit's StatusCoder interface

type HTTPResolver

type HTTPResolver struct {
	OpenMethod string
	Client     HTTPClient
}

HTTPResolver uses an HTTP client to resolve resources. Resource strings are expected to be valid URIs resolvable by the net/http package.

func (HTTPResolver) Resolve

func (r HTTPResolver) Resolve(v string) (Interface, error)

type Interface

type Interface interface {
	io.WriterTo

	Location() string
	Open() (io.ReadCloser, error)
}

Interface represents a handle to a resource.

All resource handles implement io.WriterTo, giving each type of resource the ability to optimize how transfers of data occur. For example, in-memory resources can perform a simple copy without creating intermediate objects.

func Must

func Must(r Interface, err error) Interface

Must panics if err != nil, returning the given resource handle otherwise

type NoSchemeError

type NoSchemeError struct {
	Value string
}

NoSchemeError is returned when no scheme was supplied on a resource and the SchemeResolver had no NoScheme resolver configured.

func (NoSchemeError) Error

func (e NoSchemeError) Error() string

type Resolver

type Resolver interface {
	// Resolve accepts a resource string and returns a handle that can load data
	// from that resource.  All Resolver implementations must safely permit this
	// method to be called concurrently.
	Resolve(string) (Interface, error)
}

Resolver is the strategy used to turn strings into resource handles.

func DefaultResolver

func DefaultResolver() Resolver

DefaultResolver returns the default Resolver implementation, which is a TemplateResolver that delegates to a default SchemeResolver.

type ResolverFunc

type ResolverFunc func(string) (Interface, error)

ResolverFunc is a function type that can resolve resources

func (ResolverFunc) Resolve

func (rf ResolverFunc) Resolve(v string) (Interface, error)

type Resolvers

type Resolvers map[string]Resolver

Resolvers represents a mapping of component resolvers by an arbitrary string key. The most common usage is looking up a resolver by the scheme that it is mapped to.

func NewDefaultSchemeResolvers

func NewDefaultSchemeResolvers() Resolvers

NewDefaultSchemeResolvers produces a Resolvers with the default scheme mappings. These mappings are:

StringScheme is mapped to a StringResolver
BytesScheme is mapped to a BytesResolver with standard base64 encoding
FileScheme is mapped to a FileResolver with no relative path
HTTPScheme and HTTPSScheme are mapped to an HTTPResolver using the default HTTP Client

When constructing custom SchemeResolver instances, this function is useful as a starting point.

func (Resolvers) Get

func (rs Resolvers) Get(k string) (Resolver, bool)

func (*Resolvers) Set

func (rs *Resolvers) Set(k string, r Resolver)

type SchemeError

type SchemeError struct {
	Value  string
	Scheme string
}

SchemeError is returned when a scheme had no associated resolver.

func (SchemeError) Error

func (e SchemeError) Error() string

type SchemeResolver

type SchemeResolver struct {
	Resolvers Resolvers
	NoScheme  Resolver
}

SchemeResolver is a resource resolver that uses URI-style schemes to determine how to resolve resources. For example, "http://localhost/foo" is a resource value with the scheme "http". Resource values resolved by this type of resolver do not have to be well-formed URIs unless the component resolver expects that. For example, "string://hello world" would resolve to a string resource when using the default scheme resolver.

func (SchemeResolver) Resolve

func (sr SchemeResolver) Resolve(v string) (Interface, error)

type String

type String string

String represents an in-memory resource backed by a golang string.

func (String) Location

func (s String) Location() string

func (String) Open

func (s String) Open() (io.ReadCloser, error)

func (String) WriteTo

func (s String) WriteTo(w io.Writer) (int64, error)

type StringResolver

type StringResolver struct{}

StringResolver resolves values as in-memory strings rather than external locations. This resolver ignores any scheme associated with the value, allowing it to be mapped to any desired scheme.

func (StringResolver) Resolve

func (r StringResolver) Resolve(v string) (Interface, error)

type TemplateResolver

type TemplateResolver struct {
	// Resolver is the decorated Resolver.  This resolver will receive expanded resource strings.
	// This field is required.
	Resolver Resolver

	// Template is the optional template for parsing.  If supplied, this template's Parse method is used
	// to expand resource strings.  If not supplied, a simple default template is created and used each
	// time a resource string needs to be resolved.
	//
	// When supplied, this template's Parse method is guarded by an internal mutex.  Care must be taken that
	// the same template is not used with multiple TemplateResolver instances.  It's safest to use template.Clone
	// for each TemplateResolver's Template field, thus ensuring no race conditions will occur.
	Template *template.Template

	// Data is the optional data passed to each template execution.  If supplied, this value is passed as is
	// to template.Execute.
	Data interface{}
	// contains filtered or unexported fields
}

TemplateResolver is a decorator that expands resource strings as text templates and passes the results to another Resolver. An arbitrary template can be used for parsing, which allows customization of delimiters, functions, etc.

func (*TemplateResolver) Resolve

func (tr *TemplateResolver) Resolve(v string) (Interface, error)

Resolve expands v using the configured templating (or a default) and passes the result to the decorated Resolver.

Jump to

Keyboard shortcuts

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