fire

package module
v0.12.3 Latest Latest
Warning

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

Go to latest
Published: Jan 9, 2018 License: MIT Imports: 15 Imported by: 1

README

Logo

Go on Fire

Build Status Coverage Status GoDoc Release Go Report Card

An idiomatic micro-framework for building Ember.js compatible APIs with Go.

Go on Fire is built on top of the wonderful built-in http package, implements the JSON API specification through the dedicated jsonapi library, uses the very stable mgo driver for persisting resources with MongoDB and leverages the dedicated oauth2 library to provide out of the box support for OAuth2 authentication using JWT tokens.

The deliberate and tight integration of these components provides a very simple and extensible set of abstractions for rapidly building backend services for websites that use Ember.js as their frontend framework. Of course it can also be used in conjunction with any other single page application framework or as a backend for native mobile applications.

To quickly get started with building an API with Go on Fire follow the quickstart guide, read the detailed sections in this documentation and refer to the package documentation for more detailed information on the used types and methods.

License

The MIT License (MIT)

Copyright (c) 2016 Joël Gähwiler

Documentation

Overview

Package fire is an idiomatic micro-framework for building Ember.js compatible APIs with Go.

Index

Constants

View Source
const NoDefault noDefault = iota

NoDefault marks the specified field to have no default that needs to be enforced while executing the ProtectedFieldsValidator.

Variables

This section is empty.

Functions

func Compose added in v0.2.0

func Compose(chain ...interface{}) http.Handler

Compose is a short-hand for chaining the specified middleware and handler together.

func DataSize added in v0.11.1

func DataSize(str string) uint64

DataSize parses human readable data sizes (e.g. 4K, 20M or 5G) and returns the amount of bytes they represent.

func Fatal added in v0.2.0

func Fatal(err error) error

Fatal wraps an error and marks it as fatal.

func IsFatal added in v0.12.0

func IsFatal(err error) bool

IsFatal can be used to check if an error has been wrapped using Fatal.

func RootTracer added in v0.12.2

func RootTracer() func(http.Handler) http.Handler

RootTracer is a middleware that can be used to create root trace span for an incoming request.

Types

type Action added in v0.2.0

type Action struct {
	// The allowed methods for this action.
	Methods []string

	// The callback for this action.
	Callback *Callback

	// BodyLimit defines the maximum allowed size of the request body. It
	// defaults to 8M if set to zero. The DataSize helper can be used to set
	// the value.
	BodyLimit uint64
}

An Action defines a collection or resource action.

type Callback added in v0.2.0

type Callback struct {
	Matcher Matcher
	Handler Handler
}

A Callback is called during the request processing flow of a controller.

Note: If the callback returns an error wrapped using Fatal() the API returns an InternalServerError status and the error will be logged. All other errors are serialized to an error object and returned.

func BasicAuthorizer added in v0.8.1

func BasicAuthorizer(credentials map[string]string) *Callback

BasicAuthorizer authorizes requests based on a simple credentials list.

func C added in v0.2.5

func C(name string, m Matcher, h Handler) *Callback

C is a short-hand function to construct a callback. It will also add tracing code around the execution of the callback.

func Combine added in v0.2.0

func Combine(cbs ...*Callback) *Callback

Combine will return a callback that runs all the specified callbacks in order until an error is returned.

func DependentResourcesValidator added in v0.2.0

func DependentResourcesValidator(resources map[string]string) *Callback

DependentResourcesValidator counts documents in the supplied collections and returns an error if some get found. This callback is meant to protect resources from breaking relations when requested to be deleted.

Dependent resources are defined by passing pairs of collections and database fields that hold the current models id:

DependentResourcesValidator(map[string]string{
	C(&Post{}): F(&Post{}, "Author"),
	C(&Comment{}): F(&Comment{}, "Author"),
})

func MatchingReferencesValidator added in v0.2.0

func MatchingReferencesValidator(collection, reference string, matcher map[string]string) *Callback

MatchingReferencesValidator compares the model with one related model or all related models and checks if the specified references are exactly shared.

The target model is defined by passing its collection and the referencing field on the current model. The matcher is defined by passing pairs of database fields on the target and current model:

MatchingReferencesValidator(C(&Blog{}), F(&Post{}, "Blog"), map[string]string{
	F(&Blog{}, "Owner"): F(&Post{}, "Owner"),
})

To-many, optional to-many and has-many relationships are supported both for the initial reference and in the matchers.

func ModelValidator added in v0.2.0

func ModelValidator() *Callback

ModelValidator performs a validation of the model using the Validate function.

func ProtectedFieldsValidator added in v0.12.0

func ProtectedFieldsValidator(fields map[string]interface{}) *Callback

ProtectedFieldsValidator compares protected attributes against their default (during Create) or stored value (during Update) and returns an error if they have been changed.

Attributes are defined by passing pairs of fields and default values:

ProtectedFieldsValidator(map[string]interface{}{
	F(&Post{}, "Title"): NoDefault, // can only be set during Create
	F(&Post{}, "Link"):  "",        // is fixed and cannot be changed
})

The special NoDefault value can be provided to skip the default enforcement on Create.

func RelationshipValidator added in v0.8.4

func RelationshipValidator(model coal.Model, catalog *coal.Catalog, excludedFields ...string) *Callback

RelationshipValidator makes sure all relationships of a model are correct and in place. It does so by creating a DependentResourcesValidator and a VerifyReferencesValidator based on the specified model and catalog.

func UniqueAttributeValidator added in v0.5.1

func UniqueAttributeValidator(uniqueAttribute string, filters ...string) *Callback

UniqueAttributeValidator ensures that the specified attribute of the controllers Model will remain unique among the specified filters.

The unique attribute is defines as the first argument. Filters are defined by passing a list of database fields:

UniqueAttributeValidator(F(&Blog{}, "Name"), F(&Blog{}, "Creator"))

func VerifyReferencesValidator added in v0.2.0

func VerifyReferencesValidator(references map[string]string) *Callback

VerifyReferencesValidator makes sure all references in the document are existing by counting the references on the related collections.

References are defined by passing pairs of database fields and collections of models whose ids might be referenced on the current model:

VerifyReferencesValidator(map[string]string{
	F(&Comment{}, "Post"): C(&Post{}),
	F(&Comment{}, "Author"): C(&User{}),
})

The callbacks supports to-one, optional to-one and to-many relationships.

type Context added in v0.2.0

type Context struct {
	// The current operation in process (read only).
	Operation Operation

	// The query that will be used during an List, Find, Update, Delete or
	// ResourceAction operation to select a list of models or a specific model.
	//
	// On Find, Update and Delete operations, the "_id" key is preset to the
	// resource id, while on forwarded List operations a relationship filter is
	// preset.
	Selector bson.M

	// The query that will be used during an List, Find, Update, Delete or
	// ResourceAction operation to further filter the selection of a list of
	// models or a specific model.
	//
	// On List operations, attribute filters are preset.
	Filter bson.M

	// The Model that will be saved during Create, updated during Update or
	// deleted during Delete.
	Model coal.Model

	// The sorting that will be used during List.
	Sorting []string

	// The document that will be written to the client during List, Find, Create
	// and partially Update. The JSON API endpoints which modify a resources
	// relationships do only respond with a header as no other information should
	// be changed.
	//
	// Note: The document will be set before notifiers are run.
	Response *jsonapi.Document

	// The store that is used to retrieve and persist the model (read only).
	Store *coal.SubStore

	// The underlying JSON-API request (read only).
	JSONAPIRequest *jsonapi.Request

	// The underlying HTTP request (read only).
	//
	// Note: The path is not updated when a controller forwards a request to
	// another controller.
	HTTPRequest *http.Request

	// The underlying HTTP response writer. The response writer should only be
	// used during collection or resource actions to write a response or to set
	// custom headers.
	ResponseWriter http.ResponseWriter

	// The Controller that is managing the request (read only).
	Controller *Controller

	// The Group that received the request (read only).
	Group *Group

	// The Tracer used to tracer code execution (read only).
	Tracer *Tracer
	// contains filtered or unexported fields
}

A Context provides useful contextual information.

func (*Context) Original added in v0.2.0

func (c *Context) Original() (coal.Model, error)

Original will return the stored version of the model. This method is intended to be used to calculate the changed fields during an Update operation. Any returned error is already marked as fatal. This function will cache and reuse loaded models between multiple callbacks.

Note: The method will panic if being used during any other operation than Update.

func (*Context) Query added in v0.2.0

func (c *Context) Query() bson.M

Query returns the composite query of Selector and Filter.

type Controller added in v0.2.0

type Controller struct {
	// The model that this controller should provide (e.g. &Foo{}).
	Model coal.Model

	// The store that is used to retrieve and persist the model.
	Store *coal.Store

	// Filters defines the attributes and relationships that are filterable.
	// Only fields that are indexed should be made filterable.
	Filters []string

	// Sorters defines the attributes that are sortable. Only fields that are
	// indexed should be made sortable.
	Sorters []string

	// Authorizers authorize the requested operation on the requested resource
	// and are run before any models are loaded from the DB. Returned errors
	// will cause the abortion of the request with an unauthorized status.
	//
	// The callbacks are expected to return an error if the requester should be
	// informed about him being unauthorized to access the resource or modify the
	// context's filter query in such a way that only accessible resources are
	// returned. The later improves privacy as a protected resource would just
	// appear as being not found.
	Authorizers []*Callback

	// Validators are run to validate Create, Update and Delete operations
	// after the models are loaded and the changed attributes have been assigned
	// during an Update. Returned errors will cause the abortion of the request
	// with a bad request status.
	//
	// The callbacks are expected to validate the model being created, updated or
	// deleted and return errors if the presented attributes or relationships
	// are invalid or do not comply with the stated requirements. The preceding
	// authorization checks should be repeated and now also include the model's
	// attributes and relationships.
	Validators []*Callback

	// Notifiers are run before the final response is written to the client
	// and provide a chance to modify the response and notify other systems
	// about the applied changes. Returned errors will cause the abortion of the
	// request with an Internal Server Error status.
	Notifiers []*Callback

	// NoList can be set to true if the resource is only listed through
	// relationships from other resources. This is useful for resources like
	// comments that should never be listed alone.
	NoList bool

	// ListLimit can be set to a value higher than 1 to enforce paginated
	// responses and restrain the page size to be within one and the limit.
	ListLimit uint64

	// DocumentLimit defines the maximum allowed size of an incoming document.
	// It defaults to 8M if set to zero. The DataSize helper can be used to
	// set the value.
	DocumentLimit uint64

	// CollectionActions and ResourceActions are custom actions that are run
	// on the collection (e.g. "posts/delete-cache") or resource (e.g.
	// "posts/1/recover-password"). The request context is forwarded to
	// the specified callback after running the authorizers. No validators and
	// notifiers are run for the request.
	CollectionActions map[string]*Action
	ResourceActions   map[string]*Action
	// contains filtered or unexported fields
}

A Controller provides a JSON API based interface to a model.

Note: A controller must not be modified after being added to a group.

type Group added in v0.2.0

type Group struct {

	// The function gets invoked by the controller with occurring fatal errors.
	Reporter func(error)
	// contains filtered or unexported fields
}

A Group manages access to multiple controllers and their interconnections.

func NewGroup added in v0.2.0

func NewGroup() *Group

NewGroup creates and returns a new group.

func (*Group) Add added in v0.2.0

func (g *Group) Add(controllers ...*Controller)

Add will add a controller to the group.

func (*Group) Endpoint added in v0.2.0

func (g *Group) Endpoint(prefix string) http.Handler

Endpoint will return an http handler that serves requests for this group. The specified prefix is used to parse the requests and generate urls for the resources.

type Handler added in v0.12.0

type Handler func(*Context) error

Handler is function that takes a context, mutates is to modify the behaviour and response or return an error.

If a returned error is wrapped using Fatal, processing stops immediately and the error is logged.

type L added in v0.8.4

type L []*Callback

L is a short-hand type to create a list of callbacks.

type M added in v0.10.0

type M map[string]*Action

M is a short-hand type to create a map of actions.

type Matcher added in v0.12.3

type Matcher func(*Context) bool

The matcher should return true if the callback should be run for the presented action.

func Except added in v0.2.1

func Except(ops ...Operation) Matcher

Except will match if the operation is not present in the provided list.

func Only added in v0.2.1

func Only(ops ...Operation) Matcher

Only will match if the operation is present in the provided list.

type Operation added in v0.11.0

type Operation int

An Operation indicates the purpose of a yield to a callback in the processing flow of an API request by a controller. These operations may occur multiple times during a single request.

const (

	// The list operation will used to authorize the loading of multiple
	// resources from a collection.
	//
	// Note: This operation is also used to load related resources.
	List Operation

	// The find operation will be used to authorize the loading of a specific
	// resource from a collection.
	//
	// Note: This operation is also used to load a specific related resource.
	Find

	// The create operation will be used to authorize and validate the creation
	// of a new resource in a collection.
	Create

	// The update operation will be used to authorize the loading and validate
	// the updating of a specific resource in a collection.
	//
	// Note: Updates can include attributes, relationships or both.
	Update

	// The delete operation will be used to authorize the loading and validate
	// the deletion of a specific resource in a collection.
	Delete

	// The collection action operation will be used to authorize the execution
	// of a callback for a collection action.
	CollectionAction

	// The resource action operation will be used to authorize the execution
	// of a callback for a resource action.
	ResourceAction
)

All the available operations.

func (Operation) Action added in v0.11.0

func (o Operation) Action() bool

Action will return true when this operation is a collection or resource action.

func (Operation) Read added in v0.11.0

func (o Operation) Read() bool

Read will return true when this operations does only read data.

func (Operation) String added in v0.12.2

func (o Operation) String() string

String returns the name of the operation.

func (Operation) Write added in v0.11.0

func (o Operation) Write() bool

Write will return true when this operation does write data.

type S added in v0.10.0

type S []string

S is a short-hand type to create list of strings.

type Tester added in v0.8.0

type Tester struct {
	// The store to use for cleaning the database.
	Store *coal.Store

	// The registered models.
	Models []coal.Model

	// The handler to be tested.
	Handler http.Handler

	// A path prefix e.g. 'api'.
	Prefix string

	// The header to be set on all requests and contexts.
	Header map[string]string

	// Context to be set on fake requests.
	Context context.Context
}

A Tester provides facilities to the test a fire API.

func NewTester added in v0.8.1

func NewTester(store *coal.Store, models ...coal.Model) *Tester

NewTester returns a new tester.

func (*Tester) Assign added in v0.8.7

func (t *Tester) Assign(prefix string, controllers ...*Controller)

Assign will create a controller group with the specified controllers and assign in to the Handler attribute of the tester.

func (*Tester) Clean added in v0.8.0

func (t *Tester) Clean()

Clean will remove the collections of models that have been registered and reset the header map.

func (*Tester) DebugRequest added in v0.8.0

func (t *Tester) DebugRequest(r *http.Request, rr *httptest.ResponseRecorder) string

DebugRequest returns a string of information to debug requests.

func (*Tester) FindLast added in v0.8.0

func (t *Tester) FindLast(model coal.Model) coal.Model

FindLast will return the last saved model.

func (*Tester) Path added in v0.8.0

func (t *Tester) Path(path string) string

Path returns a root prefixed path for the supplied path.

func (*Tester) Request added in v0.8.0

func (t *Tester) Request(method, path string, payload string, callback func(*httptest.ResponseRecorder, *http.Request))

Request will run the specified request against the registered handler. This function can be used to create custom testing facilities.

func (*Tester) RunAuthorizer added in v0.8.1

func (t *Tester) RunAuthorizer(op Operation, selector, filter bson.M, model coal.Model, authorizer *Callback) error

RunAuthorizer is a helper to test validators. The caller should assert the returned error of the validator, the state of the supplied model and maybe other objects in the database.

Note: Only the Operation, Query, Model and Store are set since these are the only attributes an authorizer should rely on.

Note: A fake http request is set to allow access to request headers.

func (*Tester) RunHandler added in v0.12.2

func (t *Tester) RunHandler(op Operation, selector, filter bson.M, model coal.Model, sorting []string, response *jsonapi.Document, h Handler) error

RunHandler builds a context and runs the passed handler with it.

func (*Tester) RunNotifier added in v0.12.2

func (t *Tester) RunNotifier(op Operation, response *jsonapi.Document, notifier *Callback) error

RunNotifier is a helper to test notifiers. The caller should assert the returned error of the notifier and the state of the response or other triggered actions.

Note: Only the Response attribute of the context is set since this is the only attribute a notifier should rely on.

Note: A fake http request is set to allow access to request headers.

func (*Tester) RunValidator added in v0.8.1

func (t *Tester) RunValidator(op Operation, model coal.Model, validator *Callback) error

RunValidator is a helper to test validators. The caller should assert the returned error of the validator, the state of the supplied model and maybe other objects in the database.

Note: Only the Operation, Model and Store attribute of the context are set since these are the only attributes a validator should rely on.

Note: A fake http request is set to allow access to request headers.

func (*Tester) Save added in v0.8.0

func (t *Tester) Save(model coal.Model) coal.Model

Save will save the specified model.

func (*Tester) WithContext added in v0.12.2

func (t *Tester) WithContext(op Operation, selector, filter bson.M, model coal.Model, fn func(*Context))

WithContext runs the given function with a prepared context.

type Tracer added in v0.12.0

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

Tracer provides a simple wrapper around the opentracing API to instrument and trace code.

func NewTracer added in v0.12.0

func NewTracer(root opentracing.Span) *Tracer

NewTracer returns a new tracer with the specified root span.

func NewTracerFromRequest added in v0.12.0

func NewTracerFromRequest(r *http.Request, name string) *Tracer

NewTracerFromRequest returns a new tracer that has a root span derived from the specified request. A span previously added to the request context using Context is automatically used as the parent.

func NewTracerWithRoot added in v0.12.0

func NewTracerWithRoot(name string) *Tracer

NewTracerWithRoot returns a new tracer that has a root span created with the specified name.

func (*Tracer) Context added in v0.12.0

func (t *Tracer) Context(ctx context.Context) context.Context

Context returns a new context with the latest span stored as a reference for handlers that will call NewTracerFromRequest or similar.

func (*Tracer) Finish added in v0.12.0

func (t *Tracer) Finish(root bool)

Finish will finish all leftover spans and the root span if requested.

func (*Tracer) Last added in v0.12.0

func (t *Tracer) Last() opentracing.Span

Last returns the last pushed span or the root span.

func (*Tracer) Log added in v0.12.0

func (t *Tracer) Log(key string, value interface{})

Log adds a log to the last pushed span.

func (*Tracer) Pop added in v0.12.0

func (t *Tracer) Pop()

Pop finishes and removes the last pushed span.

func (*Tracer) Push added in v0.12.0

func (t *Tracer) Push(name string)

Push will add a new span on to the stack. Successful spans must be finished by calling Pop. If the code panics or an error is returned the last pushed span will be flagged with the error and a leftover spans are popped.

func (*Tracer) Tag added in v0.12.0

func (t *Tracer) Tag(key string, value interface{})

Tag adds a tag to the last pushed span.

Directories

Path Synopsis
Package ash implements a highly configurable and callback based ACL that can be used to authorize controller operations in a declarative way.
Package ash implements a highly configurable and callback based ACL that can be used to authorize controller operations in a declarative way.
Package coal provides a mini ORM for mongoDB.
Package coal provides a mini ORM for mongoDB.
Package flame implements an authenticator that provides OAuth2 compatible authentication with JWT tokens.
Package flame implements an authenticator that provides OAuth2 compatible authentication with JWT tokens.
Package wood implements helpful tools that support the developer experience.
Package wood implements helpful tools that support the developer experience.

Jump to

Keyboard shortcuts

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