Documentation ¶
Overview ¶
Package api2go enables building REST servers for the JSONAPI.org standard.
See https://github.com/manyminds/api2go for usage instructions.
Index ¶
- func ContextQueryParams(c *APIContext) map[string][]string
- type API
- func (api *API) AddResource(prototype jsonapi.MarshalIdentifier, source interface{})
- func (api API) Handler() http.Handler
- func (api *API) NewAPIVersion(prefix string) *API
- func (api API) Router() routing.Routeable
- func (api *API) SetContextAllocator(allocator APIContextAllocatorFunc)
- func (api *API) UseMiddleware(middleware ...HandlerFunc)
- type APIContext
- func (c *APIContext) Deadline() (deadline time.Time, ok bool)
- func (c *APIContext) Done() <-chan struct{}
- func (c *APIContext) Err() error
- func (c *APIContext) Get(key string) (value interface{}, exists bool)
- func (c *APIContext) Reset()
- func (c *APIContext) Set(key string, value interface{})
- func (c *APIContext) Value(key interface{}) interface{}
- type APIContextAllocatorFunc
- type APIContexter
- type CRUD
- type Error
- type ErrorLinks
- type ErrorSource
- type FindAll
- type HTTPError
- type HandlerFunc
- type LinksResponder
- type ObjectInitializer
- type PaginatedFindAll
- type Pagination
- type Request
- type RequestAwareURLResolver
- type ResourceCreator
- type ResourceDeleter
- type ResourceGetter
- type ResourceUpdater
- type Responder
- type Response
- type URLResolver
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func ContextQueryParams ¶
func ContextQueryParams(c *APIContext) map[string][]string
ContextQueryParams fetches the QueryParams if Set
Types ¶
type API ¶
type API struct { ContentType string // contains filtered or unexported fields }
API is a REST JSONAPI.
func NewAPI ¶
NewAPI returns an initialized API instance `prefix` is added in front of all endpoints.
func NewAPIWithBaseURL ¶
NewAPIWithBaseURL does the same as NewAPI with the addition of a baseURL which get's added in front of all generated URLs. For example http://localhost/v1/myResource/abc instead of /v1/myResource/abc
func NewAPIWithResolver ¶
func NewAPIWithResolver(prefix string, resolver URLResolver) *API
NewAPIWithResolver can be used to create an API with a custom URL resolver.
func NewAPIWithRouting ¶
func NewAPIWithRouting(prefix string, resolver URLResolver, router routing.Routeable) *API
NewAPIWithRouting allows you to use a custom URLResolver, marshalers and custom routing if you want to use the default routing, you should use another constructor.
If you don't need any of the parameters you can skip them with the defaults: the default for `prefix` would be `""`, which means there is no namespace for your api. although we suggest using one.
if your api only answers to one url you can use a NewStaticResolver() as `resolver`
func (*API) AddResource ¶
func (api *API) AddResource(prototype jsonapi.MarshalIdentifier, source interface{})
AddResource registers a data source for the given resource At least the CRUD interface must be implemented, all the other interfaces are optional. `resource` should be either an empty struct instance such as `Post{}` or a pointer to a struct such as `&Post{}`. The same type will be used for constructing new elements.
func (*API) NewAPIVersion ¶
NewAPIVersion can be used to chain an additional API version to the routing of a previous one. Use this if you have multiple version prefixes and want to combine all your different API versions. This reuses the baseURL or URLResolver
func (*API) SetContextAllocator ¶
func (api *API) SetContextAllocator(allocator APIContextAllocatorFunc)
SetContextAllocator custom implementation for making contexts
func (*API) UseMiddleware ¶
func (api *API) UseMiddleware(middleware ...HandlerFunc)
UseMiddleware registers middlewares that implement the api2go.HandlerFunc Middleware is run before any generated routes.
type APIContext ¶
type APIContext struct {
// contains filtered or unexported fields
}
APIContext api2go context for handlers, nil implementations related to Deadline and Done.
func (*APIContext) Deadline ¶
func (c *APIContext) Deadline() (deadline time.Time, ok bool)
Deadline implements net/context
func (*APIContext) Get ¶
func (c *APIContext) Get(key string) (value interface{}, exists bool)
Get a key value from the context
func (*APIContext) Reset ¶
func (c *APIContext) Reset()
Reset resets all values on Context, making it safe to reuse
func (*APIContext) Set ¶
func (c *APIContext) Set(key string, value interface{})
Set a string key value in the context
func (*APIContext) Value ¶
func (c *APIContext) Value(key interface{}) interface{}
Value implements net/context
type APIContextAllocatorFunc ¶
type APIContextAllocatorFunc func(*API) APIContexter
APIContextAllocatorFunc to allow custom context implementations
type APIContexter ¶
type APIContexter interface { context.Context Set(key string, value interface{}) Get(key string) (interface{}, bool) Reset() }
APIContexter embedding context.Context and requesting two helper functions
type CRUD ¶
type CRUD interface { ResourceCreator ResourceDeleter ResourceUpdater }
The CRUD interface embed all interfaces at once: `ResourceCreator`, `ResourceDeleter`, `ResourceUpdater` (which includes `ResourceGetter`)
type Error ¶
type Error struct { ID string `json:"id,omitempty"` Links *ErrorLinks `json:"links,omitempty"` Status string `json:"status,omitempty"` Code string `json:"code,omitempty"` Title string `json:"title,omitempty"` Detail string `json:"detail,omitempty"` Source *ErrorSource `json:"source,omitempty"` Meta interface{} `json:"meta,omitempty"` }
Error can be used for all kind of application errors e.g. you would use it to define form errors or any other semantical application problems for more information see http://jsonapi.org/format/#errors
type ErrorLinks ¶
type ErrorLinks struct {
About string `json:"about,omitempty"`
}
ErrorLinks is used to provide an About URL that leads to further details about the particular occurrence of the problem.
for more information see http://jsonapi.org/format/#error-objects
type ErrorSource ¶
type ErrorSource struct { Pointer string `json:"pointer,omitempty"` Parameter string `json:"parameter,omitempty"` }
ErrorSource is used to provide references to the source of an error.
The Pointer is a JSON Pointer to the associated entity in the request document. The Paramter is a string indicating which query parameter caused the error.
for more information see http://jsonapi.org/format/#error-objects
type HTTPError ¶
type HTTPError struct { Errors []Error `json:"errors,omitempty"` // contains filtered or unexported fields }
HTTPError is used for errors
func NewHTTPError ¶
NewHTTPError creates a new error with message and status code. `err` will be logged (but never sent to a client), `msg` will be sent and `status` is the http status code. `err` can be nil.
type HandlerFunc ¶
type HandlerFunc func(APIContexter, http.ResponseWriter, *http.Request)
HandlerFunc for api2go middlewares
type LinksResponder ¶
The LinksResponder interface may be used when the response object is able to return a set of links for the top-level response object.
type ObjectInitializer ¶
type ObjectInitializer interface {
InitializeObject(interface{})
}
The ObjectInitializer interface can be implemented to have the ability to change a created object before Unmarshal is called. This is currently only called on Create as the other actions go through FindOne or FindAll which are already controlled by the implementer.
type PaginatedFindAll ¶
type PaginatedFindAll interface {
PaginatedFindAll(req Request) (totalCount uint, response Responder, err error)
}
The PaginatedFindAll interface can be optionally implemented to fetch a subset of all records. Pagination query parameters must be used to limit the result. Pagination URLs will automatically be generated by the api. You can use a combination of the following 2 query parameters: page[number] AND page[size] OR page[offset] AND page[limit]
type Pagination ¶
type Pagination struct { Next map[string]string Prev map[string]string First map[string]string Last map[string]string }
Pagination represents information needed to return pagination links
type Request ¶
type Request struct { PlainRequest *http.Request QueryParams map[string][]string Pagination map[string]string Header http.Header Context APIContexter }
Request contains additional information for FindOne and Find Requests
type RequestAwareURLResolver ¶
type RequestAwareURLResolver interface { URLResolver SetRequest(http.Request) }
RequestAwareURLResolver allows you to dynamically change generated urls.
This is particulary useful if you have the same API answering to multiple domains, or subdomains e.g customer[1,2,3,4].yourapi.example.com
SetRequest will always be called prior to the GetBaseURL() from `URLResolver` so you have to change the result value based on the last request.
type ResourceCreator ¶
type ResourceCreator interface { // Create a new object. Newly created object/struct must be in Responder. // Possible Responder status codes are: // - 201 Created: Resource was created and needs to be returned // - 202 Accepted: Processing is delayed, return nothing // - 204 No Content: Resource created with a client generated ID, and no fields were modified by // the server Create(obj interface{}, req Request) (Responder, error) }
The ResourceCreator interface MUST be implemented in order to generate the POST route
type ResourceDeleter ¶
type ResourceDeleter interface { // Delete an object // Possible Responder status codes are: // - 200 OK: Deletion was a success, returns meta information, currently not implemented! Do not use this // - 202 Accepted: Processing is delayed, return nothing // - 204 No Content: Deletion was successful, return nothing Delete(id string, req Request) (Responder, error) }
The ResourceDeleter interface MUST be implemented in order to generate the DELETE route
type ResourceGetter ¶
type ResourceGetter interface { // FindOne returns an object by its ID // Possible Responder success status code 200 FindOne(ID string, req Request) (Responder, error) }
The ResourceGetter interface MUST be implemented in order to generate the single GET route and related
type ResourceUpdater ¶
type ResourceUpdater interface { // ResourceGetter must be implemented along with ResourceUpdater so that api2go can retrieve the single resource before update ResourceGetter // Update an object // Possible Responder status codes are: // - 200 OK: Update successful, however some field(s) were changed, returns updates source // - 202 Accepted: Processing is delayed, return nothing // - 204 No Content: Update was successful, no fields were changed by the server, return nothing Update(obj interface{}, req Request) (Responder, error) }
The ResourceUpdater interface MUST be implemented in order to generate the PATCH/PUT routes
type Responder ¶
type Responder interface { Metadata() map[string]interface{} Result() interface{} StatusCode() int }
The Responder interface is used by all Resource Methods as a container for the Response. Metadata is additional Metadata. You can put anything you like into it, see jsonapi spec. Result returns the actual payload. For FindOne, put only one entry in it. StatusCode sets the http status code.
type Response ¶
type Response struct { Res interface{} Code int Meta map[string]interface{} Pagination Pagination }
The Response struct implements api2go.Responder and can be used as a default implementation for your responses you can fill the field `Meta` with all the metadata your application needs like license, tokens, etc
func (Response) StatusCode ¶
StatusCode sets the return status code
type URLResolver ¶
type URLResolver interface {
GetBaseURL() string
}
URLResolver allows you to implement a static way to return a baseURL for all incoming requests for one api2go instance.
func NewCallbackResolver ¶
func NewCallbackResolver(callback func(http.Request) string) URLResolver
NewCallbackResolver handles each resolve via your provided callback func
func NewStaticResolver ¶
func NewStaticResolver(baseURL string) URLResolver
NewStaticResolver returns a simple resolver that will always answer with the same url
Source Files ¶
Directories ¶
Path | Synopsis |
---|---|
Package examples shows how to implement a basic CRUD for two data structures with the api2go server functionality.
|
Package examples shows how to implement a basic CRUD for two data structures with the api2go server functionality. |