fire

package module
v0.8.0 Latest Latest
Warning

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

Go to latest
Published: Nov 15, 2017 License: MIT Imports: 12 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

Index

Constants

View Source
const NoDefault value = iota

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

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 Fatal added in v0.2.0

func Fatal(err error) error

Fatal wraps an error and marks it as fatal.

Types

type Action added in v0.2.0

type Action int

An Action describes the currently called action on the API.

const (
	List Action
	Find
	Create
	Update
	Delete
)

All the available actions.

func (Action) Read added in v0.2.0

func (a Action) Read() bool

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

func (Action) Write added in v0.2.0

func (a Action) Write() bool

Write will return true when this action does write data.

type Callback added in v0.2.0

type Callback func(*Context) error

A Callback is called during execution 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 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 Except added in v0.2.1

func Except(cb Callback, actions ...Action) Callback

Except will return a callback that runs the specified callback only when none of the supplied actions match.

func MatchingReferencesValidator added in v0.2.0

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

MatchingReferencesValidator compares the model with a related model and checks if certain references are 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"),
})

func ModelValidator added in v0.2.0

func ModelValidator() Callback

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

func Only added in v0.2.1

func Only(cb Callback, actions ...Action) Callback

Only will return a callback that runs the specified callback only when one of the supplied actions match.

func ProtectedAttributesValidator added in v0.2.0

func ProtectedAttributesValidator(attributes map[string]interface{}) Callback

ProtectedAttributesValidator 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:

ProtectedAttributesValidator(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 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 `bson.ObjectId', `*bson.ObjectId` and `[]bson.ObjectId` fields.

type Context added in v0.2.0

type Context struct {
	// The current action in process.
	Action Action

	// The query that will be used during List, Find, Update or Delete to fetch
	// a list of models or the specific requested model.
	//
	// On Find, Update and Delete, the "_id" key is preset to the document ID
	// while on List all field and relationship filters are preset.
	Query 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 to 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.
	Store *coal.SubStore

	// The underlying JSON API request.
	JSONAPIRequest *jsonapi.Request

	// The underlying HTTP request.
	HTTPRequest *http.Request

	// The Controller that is managing the request.
	Controller *Controller

	// The Group that received the request.
	Group *Group
	// 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 action. Any returned error is already marked as fatal.

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

type Controller added in v0.2.0

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

	// Filters defines the attributes that are filterable.
	Filters []string

	// Sorters defines the attributes that are sortable.
	Sorters []string

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

	// The Authorizers authorize the requested action 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 Query attribute 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

	// The Validators are run to validate Create, Update and Delete actions after
	// the models are loaded from the DB 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

	// The 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

	// The NoList property 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

	// The 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
}

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

Note: Controllers must not be modified after adding to an application.

type Group added in v0.2.0

type Group struct {

	// The Reporter function gets invoked by the controller with any 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 controller group. The specified prefix is used to parse the requests and generate urls for the resources.

func (*Group) Find added in v0.5.0

func (g *Group) Find(pluralName string) *Controller

Find will return the controller with the matching plural name if found.

func (*Group) List added in v0.5.0

func (g *Group) List() []*Controller

List will return a list of all added controllers.

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 headers to be set on all requests.
	Headers map[string]string
}

A Tester provides facilities to the test a fire API.

func (*Tester) Clean added in v0.8.0

func (t *Tester) Clean()

Clean will remove the collections of models that have been registered.

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) Register added in v0.8.0

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

Register will register the specified model with the tester.

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) Save added in v0.8.0

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

Save will save the specified model.

func (*Tester) SaveAll added in v0.8.0

func (t *Tester) SaveAll(models ...coal.Model)

SaveAll will save the specified models.

Directories

Path Synopsis
Package ash implements a highly configurable and callback based ACL that can be used to authorize controller actions in a declarative way.
Package ash implements a highly configurable and callback based ACL that can be used to authorize controller actions in a declarative way.
Package coal provides a mini ORM for mongoDB.
Package coal provides a mini ORM for mongoDB.
Package flame implements an authentication manager that provides OAuth2 compatible authentication with JWT tokens.
Package flame implements an authentication manager that provides OAuth2 compatible authentication with JWT tokens.
Package wood implements various helpful tools for developing apps.
Package wood implements various helpful tools for developing apps.

Jump to

Keyboard shortcuts

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