Documentation ¶
Overview ¶
The Tideland Go REST Server Library provides the package rest for the implementation of servers with a RESTful API. The business has to be implemented in types fullfilling the ResourceHandler interface. This basic interface only allows the initialization of the handler. More interesting are the other interfaces like GetResourceHandler which defines the Get() method for the HTTP request method GET. Others are for PUT, POST, HEAD, PATCH, DELETE, and OPTIONS. Their according methods get a Job as argument. It provides convenient helpers for the processing of the job.
type myHandler struct { id string } func NewMyHandler(id string) rest.ResourceHandler { return &myHandler{id} } func (h *myHandler) ID() string { return h.id } func (h *myHandler) Init(env rest.Environment, domain, resource string) error { // Nothing to do in this example. return nil } // Get handles reading of resources, here simplified w/o // error handling. func (h *myHandler) Get(job rest.Job) (bool, error) { id := job.ResourceID() if id == "" { all := model.GetAllData() job.JSON(true).Write(all) return true, nil } one := model.GetOneData(id) job.JSON(true).Write(one) return true, nil }
The processing methods return two values: a boolean and an error. The latter is pretty clear, it signals a job processing error. The boolean is more interesting. Registering a handler is based on a domain and a resource. The URL
/<DOMAIN>/<RESOURCE>
leads to a handler, or even better, to a list of handlers. All are used as long as the returned boolean value is true. E.g. the first handler can check the authentication, the second one the authorization, and the third one does the business. Additionally the URL
/<DOMAIN>/<RESOURCE>/<ID>
provides the resource identifier via Job.ResourceID().
The handlers then are deployed to the Multiplexer which implements the Handler interface of the net/http package. So the typical order is
mux := rest.NewMultiplexer() mux.Register("domain", "resource-type-a", NewTypeAHandler("foo")) mux.Register("domain", "resource-type-b", NewTypeBHandler("bar")) mux.Register("admin", "user", NewUserManagementHandler()) http.ListenAndServe(":8000", mux)
Additionally further handlers can be registered or running once removed during runtime.
Index ¶
- Constants
- func NegativeFeedback(f Formatter, msg string, args ...interface{}) error
- func PackageVersion() version.Version
- func PositiveFeedback(f Formatter, payload interface{}, msg string, args ...interface{}) error
- type DeleteResourceHandler
- type Envelope
- type Environment
- type Formatter
- type GetResourceHandler
- type HeadResourceHandler
- type Job
- type KeyValue
- type KeyValues
- type Language
- type Languages
- type Multiplexer
- type Option
- type OptionsResourceHandler
- type PatchResourceHandler
- type PostResourceHandler
- type PutResourceHandler
- type Registration
- type Registrations
- type Renderer
- type ResourceHandler
- type TemplatesCache
Constants ¶
const ( ErrDuplicateHandler = iota + 1 ErrInitHandler ErrIllegalRequest ErrNoHandler ErrNoGetHandler ErrNoHeadHandler ErrNoPutHandler ErrNoPostHandler ErrNoPatchHandler ErrNoDeleteHandler ErrNoOptionsHandler ErrMethodNotSupported ErrUploadingFile ErrInvalidContentType ErrNoCachedTemplate )
const ( ContentTypePlain = "text/plain" ContentTypeHTML = "text/html" ContentTypeXML = "application/xml" ContentTypeJSON = "application/json" ContentTypeGOB = "application/vnd.tideland.gob" )
Variables ¶
This section is empty.
Functions ¶
func NegativeFeedback ¶
NegativeFeedback writes a negative feedback envelope to the formatter.
func PackageVersion ¶
PackageVersion returns the version of the version package.
func PositiveFeedback ¶
PositiveFeedback writes a positive feedback envelope to the formatter.
Types ¶
type DeleteResourceHandler ¶
DeleteResourceHandler is the additional interface for handlers understanding the verb DELETE.
type Envelope ¶
Envelope is a helper to give a qualified feedback in RESTful requests. It contains wether the request has been successful, in case of an error an additional message and the payload.
type Environment ¶
type Environment interface { // BasePath returns the configured base path. BasePath() string // DefaultDomain returns the configured default domain. DefaultDomain() string // DefaultResource returns the configured default resource. DefaultResource() string // Templates returns the template cache. Templates() TemplatesCache }
type Formatter ¶
type Formatter interface { // Write encodes the passed data to implementers format and writes // it to the response writer. Write(data interface{}) error // Read checks if the request content type matches the implementers // format, reads its body and decodes it to the value pointed to by // data. Read(data interface{}) error }
type GetResourceHandler ¶
GetResourceHandler is the additional interface for handlers understanding the verb GET.
type HeadResourceHandler ¶
HeadResourceHandler is the additional interface for handlers understanding the verb HEAD.
type Job ¶
type Job interface { // Return the Job as string. fmt.Stringer // Environment returns the server environment. Environment() Environment // Request returns the used Go HTTP request. Request() *http.Request // ResponseWriter returns the used Go HTTP response writer. ResponseWriter() http.ResponseWriter // Domain returns the requests domain. Domain() string // Resource returns the requests resource. Resource() string // ResourceID return the requests resource ID. ResourceID() string // Context returns a context containing the job. Context() context.Context // AcceptsContentType checks if the requestor accepts a given content type. AcceptsContentType(contentType string) bool // HasContentType checks if the sent content has the given content type. HasContentType(contentType string) bool // Languages returns the accepted language with the quality values. Languages() Languages // InternalPath builds an internal path out of the passed parts. InternalPath(domain, resource, resourceID string, query ...KeyValue) string // Redirect to a domain, resource and resource ID (optional). Redirect(domain, resource, resourceID string) // Renderer returns a template renderer. Renderer() Renderer // GOB returns a GOB formatter. GOB() Formatter // JSON returns a JSON formatter. JSON(html bool) Formatter // XML returns a XML formatter. XML() Formatter }
Job encapsulates all the needed information for handling a request.
type KeyValue ¶
type KeyValue struct { Key string Value interface{} }
KeyValue assigns a value to a key.
type Languages ¶
type Languages []Language
Languages is the ordered set of accepted languages.
type Multiplexer ¶
type Multiplexer interface { http.Handler // Register adds a resource handler for a given domain and resource. Register(domain, resource string, handler ResourceHandler) error // RegisterAll allows to register multiple handler in one run. RegisterAll(registrations Registrations) error // Deregister removes a resource handler for a given domain and resource. Deregister(domain, resource, id string) }
Multiplexer enhances the http.Handler interface by registration an deregistration of handlers.
func NewMultiplexer ¶
func NewMultiplexer(options ...Option) Multiplexer
NewMultiplexer creates a new HTTP multiplexer.
type Option ¶
type Option func(env Environment)
Option defines a function for setting an option.
func DefaultDomain ¶
DefaultDomain sets the default domain.
func DefaultResource ¶
DefaultResource sets the default resource.
func Templates ¶
func Templates(templates TemplatesCache) Option
Templates sets the templates cache.
type OptionsResourceHandler ¶
OptionsResourceHandler is the additional interface for handlers understanding the verb OPTION.
type PatchResourceHandler ¶
PatchResourceHandler is the additional interface for handlers understanding the verb PATCH.
type PostResourceHandler ¶
PostResourceHandler is the additional interface for handlers understanding the verb POST.
type PutResourceHandler ¶
PutResourceHandler is the additional interface for handlers understanding the verb PUT.
type Registration ¶
type Registration struct { Domain string Resource string Handler ResourceHandler }
Registration encapsulates one handler registration.
type Registrations ¶
type Registrations []Registration
Registrations is a number handler registratons.
type Renderer ¶
type Renderer interface { // Render executes the pre-parsed template with the data. // It also sets the content type header. Render(id string, data interface{}) error // LoadAndRender checks if the template with the given id // has already been parsed. In this case it will use it, // otherwise the template will be loaded, parsed, added // to the cache, and used then. LoadAndRender(id, filename, contentType string, data interface{}) error }
Renderer renders templates. It is returned by a Job and knows where to render it.
type ResourceHandler ¶
type ResourceHandler interface { // ID returns the deployment ID of the handler. ID() string // Init initializes the resource handler after registrations. Init(env Environment, domain, resource string) error }
ResourceHandler is the base interface for all resource handlers understanding the REST verbs. It allows the initialization and returns an id that has to be unique for the combination of domain and resource. So it can later be removed again.
type TemplatesCache ¶
type TemplatesCache interface { // Parse parses a raw template an stores it. Parse(id, rawTmpl, contentType string) error // LoadAndParse loads a template out of the filesystem, // parses and stores it. LoadAndParse(id, filename, contentType string) error // Render executes the pre-parsed template with the data. // It also sets the content type header. Render(rw http.ResponseWriter, id string, data interface{}) error // LoadAndRender checks if the template with the given id // has already been parsed. In this case it will use it, // otherwise the template will be loaded, parsed, added // to the cache, and used then. LoadAndRender(rw http.ResponseWriter, id, filename, contentType string, data interface{}) error }
TemplatesCache caches and renders templates.
func NewTemplatesCache ¶
func NewTemplatesCache() TemplatesCache
NewTemplates creates a new template cache.