Documentation

Overview

    Package rest is a `net/http` handler responsible for HTTP RESTful implementation for the REST Layer framework.

    This package is part of the rest-layer project. See http://rest-layer.io for full REST Layer documentation.

    Example
    Output:
    
    

    Index

    Examples

    Constants

    This section is empty.

    Variables

    View Source
    var (
    	// ErrNotFound represents a 404 HTTP error.
    	ErrNotFound = &Error{http.StatusNotFound, "Not Found", nil}
    	// ErrForbidden represents a 403 HTTP error.
    	ErrForbidden = &Error{http.StatusForbidden, "Forbidden", nil}
    	// ErrPreconditionFailed happens when a conditional request condition is not met.
    	ErrPreconditionFailed = &Error{http.StatusPreconditionFailed, "Precondition Failed", nil}
    	// ErrConflict happens when another thread or node modified the data
    	// concurrently with our own thread in such a way we can't securely apply
    	// the requested changes.
    	ErrConflict = &Error{http.StatusConflict, "Conflict", nil}
    	// ErrInvalidMethod happens when the used HTTP method is not supported for
    	// this resource.
    	ErrInvalidMethod = &Error{http.StatusMethodNotAllowed, "Invalid Method", nil}
    	// ErrClientClosedRequest is returned when the client closed the connection
    	// before the server was able to finish processing the request.
    	ErrClientClosedRequest = &Error{499, "Client Closed Request", nil}
    	// ErrNotImplemented happens when a requested feature is not implemented.
    	ErrNotImplemented = &Error{http.StatusNotImplemented, "Not Implemented", nil}
    	// ErrGatewayTimeout is returned when the specified timeout for the request
    	// has been reached before the server was able to process it.
    	ErrGatewayTimeout = &Error{http.StatusGatewayTimeout, "Deadline Exceeded", nil}
    	// ErrUnknown is thrown when the origin of the error can't be identified.
    	ErrUnknown = &Error{520, "Unknown Error", nil}
    )

    Functions

    func IndexFromContext

    func IndexFromContext(ctx context.Context) (resource.Index, bool)

      IndexFromContext extracts the router from the given net/context.

      Types

      type DefaultResponseFormatter

      type DefaultResponseFormatter struct {
      }

        DefaultResponseFormatter provides a base response formatter to be used by default. This formatter can easily be extended or replaced by implementing ResponseFormatter interface and setting it on Handler.ResponseFormatter.

        func (DefaultResponseFormatter) FormatError

        func (f DefaultResponseFormatter) FormatError(ctx context.Context, headers http.Header, err error, skipBody bool) (context.Context, interface{})

          FormatError implements ResponseFormatter.

          func (DefaultResponseFormatter) FormatItem

          func (f DefaultResponseFormatter) FormatItem(ctx context.Context, headers http.Header, i *resource.Item, skipBody bool) (context.Context, interface{})

            FormatItem implements ResponseFormatter.

            func (DefaultResponseFormatter) FormatList

            func (f DefaultResponseFormatter) FormatList(ctx context.Context, headers http.Header, l *resource.ItemList, skipBody bool) (context.Context, interface{})

              FormatList implements ResponseFormatter.

              type DefaultResponseSender

              type DefaultResponseSender struct {
              }

                DefaultResponseSender provides a base response sender to be used by default. This sender can easily be extended or replaced by implementing ResponseSender interface and setting it on Handler.ResponseSender.

                func (DefaultResponseSender) Send

                func (s DefaultResponseSender) Send(ctx context.Context, w http.ResponseWriter, status int, headers http.Header, body interface{})

                  Send sends headers with the given status and marshal the data in JSON.

                  type Error

                  type Error struct {
                  	// Code defines the error code to be used for the error and for the HTTP
                  	// status.
                  	Code int
                  	// Message is the error message.
                  	Message string
                  	// Issues holds per fields errors if any.
                  	Issues map[string][]interface{}
                  }

                    Error defines a REST error with optional per fields error details.

                    func NewError

                    func NewError(err error) *Error

                      NewError returns a rest.Error from an standard error.

                      If the the inputted error is recognized, the appropriate rest.Error is mapped.

                      func (*Error) Error

                      func (e *Error) Error() string

                        Error returns the error as string

                        type Handler

                        type Handler struct {
                        	// ResponseFormatter can be changed to extend the DefaultResponseFormatter.
                        	ResponseFormatter ResponseFormatter
                        	// ResponseSender can be changed to extend the DefaultResponseSender.
                        	ResponseSender ResponseSender
                        	// FallbackHandlerFunc is called when REST layer doesn't find a route for
                        	// the request. If not set, a 404 or 405 standard REST error is returned.
                        	FallbackHandlerFunc func(ctx context.Context, w http.ResponseWriter, r *http.Request)
                        	// contains filtered or unexported fields
                        }

                          Handler is a net/http compatible handler used to serve the configured REST API.

                          func NewHandler

                          func NewHandler(i resource.Index) (*Handler, error)

                            NewHandler creates an new REST API HTTP handler with the specified resource index.

                            func (*Handler) ServeHTTP

                            func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request)

                              ServeHTTP handles requests as a http.Handler.

                              func (*Handler) ServeHTTPC

                              func (h *Handler) ServeHTTPC(ctx context.Context, w http.ResponseWriter, r *http.Request)

                                ServeHTTPC handles requests as a xhandler.HandlerC (deprecated).

                                type ResourcePath

                                type ResourcePath []*ResourcePathComponent

                                  ResourcePath is the list of ResourcePathComponent leading to the requested resource

                                  func (ResourcePath) ParentsExist

                                  func (p ResourcePath) ParentsExist(ctx context.Context) error

                                    ParentsExist checks if the each intermediate parents in the path exist and return either a ErrNotFound or an error returned by on of the intermediate resource.

                                    func (ResourcePath) Path

                                    func (p ResourcePath) Path() string

                                      Path returns the path to the resource to be used with resource.Root.GetResource.

                                      func (*ResourcePath) Prepend

                                      func (p *ResourcePath) Prepend(rsrc *resource.Resource, field string, value interface{})

                                        Prepend add the given resource using the provided field and value as a "ghost" resource prefix to the resource path.

                                        The effect will be a 404 error if the doesn't have an item with the id matching to the provided value.

                                        This will also require that all subsequent resources in the path have this resource's "value" set on their "field" field.

                                        Finally, all created resources at this path will also have this field and value set by default.

                                        func (ResourcePath) Values

                                        func (p ResourcePath) Values() map[string]interface{}

                                          Values returns all the key=value pairs defined by the resource path.

                                          type ResourcePathComponent

                                          type ResourcePathComponent struct {
                                          	// Name is the endpoint name used to bind the resource
                                          	Name string
                                          	// Field is the resource's field used to filter targeted resource
                                          	Field string
                                          	// Value holds the resource's id value
                                          	Value interface{}
                                          	// Resource references the resource
                                          	Resource *resource.Resource
                                          }

                                            ResourcePathComponent represents the path of resource and sub-resources of a given request's resource

                                            type ResponseFormatter

                                            type ResponseFormatter interface {
                                            	// FormatItem formats a single item in a format ready to be serialized by the ResponseSender
                                            	FormatItem(ctx context.Context, headers http.Header, i *resource.Item, skipBody bool) (context.Context, interface{})
                                            	// FormatList formats a list of items in a format ready to be serialized by the ResponseSender
                                            	FormatList(ctx context.Context, headers http.Header, l *resource.ItemList, skipBody bool) (context.Context, interface{})
                                            	// FormatError formats a REST formated error or a simple error in a format ready to be serialized by the ResponseSender
                                            	FormatError(ctx context.Context, headers http.Header, err error, skipBody bool) (context.Context, interface{})
                                            }

                                              ResponseFormatter defines an interface responsible for formatting a the different types of response objects.

                                              type ResponseSender

                                              type ResponseSender interface {
                                              	// Send serialize the body, sets the given headers and write everything to
                                              	// the provided response writer.
                                              	Send(ctx context.Context, w http.ResponseWriter, status int, headers http.Header, body interface{})
                                              }

                                                ResponseSender defines an interface responsible for serializing and sending the response to the http.ResponseWriter.

                                                Example
                                                Output:
                                                
                                                

                                                type RouteMatch

                                                type RouteMatch struct {
                                                	// Method is the HTTP method used on the resource.
                                                	Method string
                                                	// ResourcePath is the list of intermediate resources followed by the
                                                	// targeted resource. Each intermediate resource much match all the previous
                                                	// resource components of this path and newly created resources will have
                                                	// their corresponding fields filled with resource path information
                                                	// (resource.field => resource.value).
                                                	ResourcePath ResourcePath
                                                	// Params is the list of client provided parameters (thru query-string or alias).
                                                	Params url.Values
                                                }

                                                  RouteMatch represent a REST request's matched resource with the method to apply and its parameters.

                                                  func FindRoute

                                                  func FindRoute(index resource.Index, req *http.Request) (*RouteMatch, error)

                                                    FindRoute returns the REST route for the given request.

                                                    func RouteFromContext

                                                    func RouteFromContext(ctx context.Context) (*RouteMatch, bool)

                                                      RouteFromContext extracts the matched route from the given net/context.

                                                      func (*RouteMatch) Query

                                                      func (r *RouteMatch) Query() (*query.Query, *Error)

                                                        Query builds a query object from the matched route

                                                        func (*RouteMatch) Release

                                                        func (r *RouteMatch) Release()

                                                          Release releases the route so it can be reused.

                                                          func (*RouteMatch) Resource

                                                          func (r *RouteMatch) Resource() *resource.Resource

                                                            Resource returns the last resource path's resource.

                                                            func (*RouteMatch) ResourceID

                                                            func (r *RouteMatch) ResourceID() interface{}

                                                              ResourceID returns the last resource path's resource id value if any.

                                                              If this method returns a non nil value, it means the route is an item request, otherwise it's a collection request.