api2go: github.com/manyminds/api2go Index | Files | Directories

package api2go

import "github.com/manyminds/api2go"

Package api2go enables building REST servers for the JSONAPI.org standard.

See https://github.com/manyminds/api2go for usage instructions.


Package Files

api.go api_interfaces.go api_public.go context.go doc.go error.go request.go resolver.go response.go

func ContextQueryParams Uses

func ContextQueryParams(c *APIContext) map[string][]string

ContextQueryParams fetches the QueryParams if Set

type API Uses

type API struct {
    ContentType string
    // contains filtered or unexported fields


func NewAPI Uses

func NewAPI(prefix string) *API

NewAPI returns an initialized API instance `prefix` is added in front of all endpoints.

func NewAPIWithBaseURL Uses

func NewAPIWithBaseURL(prefix string, baseURL string) *API

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 Uses

func NewAPIWithResolver(prefix string, resolver URLResolver) *API

NewAPIWithResolver can be used to create an API with a custom URL resolver.

func NewAPIWithRouting Uses

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 Uses

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) Handler Uses

func (api API) Handler() http.Handler

Handler returns the http.Handler instance for the API.

func (*API) NewAPIVersion Uses

func (api *API) NewAPIVersion(prefix string) *API

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) Router Uses

func (api API) Router() routing.Routeable

Router returns the specified router on an api instance

func (*API) SetContextAllocator Uses

func (api *API) SetContextAllocator(allocator APIContextAllocatorFunc)

SetContextAllocator custom implementation for making contexts

func (*API) UseMiddleware Uses

func (api *API) UseMiddleware(middleware ...HandlerFunc)

UseMiddleware registers middlewares that implement the api2go.HandlerFunc Middleware is run before any generated routes.

type APIContext Uses

type APIContext struct {
    // contains filtered or unexported fields

APIContext api2go context for handlers, nil implementations related to Deadline and Done.

func (*APIContext) Deadline Uses

func (c *APIContext) Deadline() (deadline time.Time, ok bool)

Deadline implements net/context

func (*APIContext) Done Uses

func (c *APIContext) Done() <-chan struct{}

Done implements net/context

func (*APIContext) Err Uses

func (c *APIContext) Err() error

Err implements net/context

func (*APIContext) Get Uses

func (c *APIContext) Get(key string) (value interface{}, exists bool)

Get a key value from the context

func (*APIContext) Reset Uses

func (c *APIContext) Reset()

Reset resets all values on Context, making it safe to reuse

func (*APIContext) Set Uses

func (c *APIContext) Set(key string, value interface{})

Set a string key value in the context

func (*APIContext) Value Uses

func (c *APIContext) Value(key interface{}) interface{}

Value implements net/context

type APIContextAllocatorFunc Uses

type APIContextAllocatorFunc func(*API) APIContexter

APIContextAllocatorFunc to allow custom context implementations

type APIContexter Uses

type APIContexter interface {
    Set(key string, value interface{})
    Get(key string) (interface{}, bool)

APIContexter embedding context.Context and requesting two helper functions

type CRUD Uses

type CRUD interface {

The CRUD interface embed all interfaces at once: `ResourceCreator`, `ResourceDeleter`, `ResourceUpdater` (which includes `ResourceGetter`)

type Error Uses

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 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 Uses

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 FindAll Uses

type FindAll interface {
    // FindAll returns all objects
    FindAll(req Request) (Responder, error)

The FindAll interface can be optionally implemented to fetch all records at once.

type HTTPError Uses

type HTTPError struct {
    Errors []Error `json:"errors,omitempty"`
    // contains filtered or unexported fields

HTTPError is used for errors

func NewHTTPError Uses

func NewHTTPError(err error, msg string, status int) HTTPError

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.

func (HTTPError) Error Uses

func (e HTTPError) Error() string

Error returns a nice string represenation including the status

type HandlerFunc Uses

type HandlerFunc func(APIContexter, http.ResponseWriter, *http.Request)

HandlerFunc for api2go middlewares

type LinksResponder Uses

type LinksResponder interface {
    Links(*http.Request, string) jsonapi.Links

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 Uses

type ObjectInitializer 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 Uses

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 Uses

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 Uses

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 Uses

type RequestAwareURLResolver interface {

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 Uses

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 Uses

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 Uses

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 Uses

type ResourceUpdater interface {
    // ResourceGetter must be implemented along with ResourceUpdater so that api2go can retrieve the single resource before update
    // 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 Uses

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 Uses

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 (r Response) Links(req *http.Request, baseURL string) (ret jsonapi.Links)

Links returns a jsonapi.Links object to include in the top-level response

func (Response) Metadata Uses

func (r Response) Metadata() map[string]interface{}

Metadata returns additional meta data

func (Response) Result Uses

func (r Response) Result() interface{}

Result returns the actual payload

func (Response) StatusCode Uses

func (r Response) StatusCode() int

StatusCode sets the return status code

type URLResolver Uses

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 Uses

func NewCallbackResolver(callback func(http.Request) string) URLResolver

NewCallbackResolver handles each resolve via your provided callback func

func NewStaticResolver Uses

func NewStaticResolver(baseURL string) URLResolver

NewStaticResolver returns a simple resolver that will always answer with the same url


examplesPackage examples shows how to implement a basic CRUD for two data structures with the api2go server functionality.

Package api2go imports 16 packages (graph) and is imported by 67 packages. Updated 2019-05-27. Refresh now. Tools for package owners.