Documentation ¶
Overview ¶
Package api2go enables building REST servers for the JSONAPI.org standard.
See https://github.com/artpar/api2go for usage instructions.
Index ¶
- func ContextQueryParams(c *APIContext) map[string][]string
- func EndsWith(str string, endsWith string) (string, bool)
- func EndsWithCheck(str string, endsWith string) bool
- 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 Api2GoModel
- func (m *Api2GoModel) AddToManyIDs(name string, IDs []string) error
- func (g *Api2GoModel) BeforeCreate() (err error)
- func (m *Api2GoModel) DeleteToManyIDs(name string, IDs []string) error
- func (m Api2GoModel) GetAllAsAttributes() map[string]interface{}
- func (m Api2GoModel) GetAttributes() map[string]interface{}
- func (g Api2GoModel) GetAuditModel() Api2GoModel
- func (g Api2GoModel) GetChanges() map[string]Change
- func (a Api2GoModel) GetColumnMap() map[string]ColumnInfo
- func (m Api2GoModel) GetColumnNames() []string
- func (g Api2GoModel) GetColumnOriginalValue(columnName string) interface{}
- func (m Api2GoModel) GetColumns() []ColumnInfo
- func (g Api2GoModel) GetCurrentVersion() int64
- func (g Api2GoModel) GetDefaultPermission() int64
- func (g Api2GoModel) GetID() string
- func (g Api2GoModel) GetName() string
- func (g Api2GoModel) GetNextVersion() int64
- func (g Api2GoModel) GetReferenceId() string
- func (m Api2GoModel) GetReferencedIDs() []jsonapi.ReferenceID
- func (m Api2GoModel) GetReferencedStructs() []jsonapi.MarshalIdentifier
- func (model Api2GoModel) GetReferences() []jsonapi.Reference
- func (a Api2GoModel) GetRelations() []TableRelation
- func (g Api2GoModel) GetTableName() string
- func (g Api2GoModel) GetUnmodifiedAttributes() map[string]interface{}
- func (a Api2GoModel) HasColumn(colName string) bool
- func (a Api2GoModel) HasMany(colName string) bool
- func (g Api2GoModel) HasVersion() bool
- func (m Api2GoModel) InitializeObject(interface{})
- func (g Api2GoModel) IsDirty() bool
- func (g *Api2GoModel) Set(columnName string, value interface{})
- func (g *Api2GoModel) SetAttributes(attrs map[string]interface{})
- func (m *Api2GoModel) SetColumns(c []ColumnInfo)
- func (g *Api2GoModel) SetID(str string) error
- func (m *Api2GoModel) SetToManyReferenceIDs(name string, IDs []map[string]interface{}) error
- func (m Api2GoModel) SetToOneReferenceID(name, ID string) error
- func (g *Api2GoModel) SetType(typeName string)
- type CRUD
- type Change
- type ColumnInfo
- type DeleteReferenceInfo
- type EditToManyRelations
- type Error
- type ErrorLinks
- type ErrorSource
- type FindAll
- type ForeignKeyData
- type HTTPError
- type HandlerFunc
- type HasId
- 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 TableRelation
- func (tr *TableRelation) GetJoinString() string
- func (tr *TableRelation) GetJoinTableName() string
- func (tr *TableRelation) GetObject() string
- func (tr *TableRelation) GetObjectName() string
- func (tr *TableRelation) GetRelation() string
- func (tr *TableRelation) GetReverseJoinString() string
- func (tr *TableRelation) GetSubject() string
- func (tr *TableRelation) GetSubjectName() string
- func (tr *TableRelation) Hash() string
- func (tr *TableRelation) String() string
- type TableRelationInterface
- type URLResolver
- type ValueOptions
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
func EndsWithCheck ¶
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 Api2GoModel ¶
type Api2GoModel struct { DeleteIncludes map[string][]string Includes []jsonapi.MarshalIdentifier // contains filtered or unexported fields }
func NewApi2GoModel ¶
func NewApi2GoModel(name string, columns []ColumnInfo, defaultPermission int64, relations []TableRelation) Api2GoModel
func NewApi2GoModelWithData ¶
func NewApi2GoModelWithData( name string, columns []ColumnInfo, defaultPermission int64, relations []TableRelation, m map[string]interface{}, ) Api2GoModel
func (*Api2GoModel) AddToManyIDs ¶
func (m *Api2GoModel) AddToManyIDs(name string, IDs []string) error
func (*Api2GoModel) BeforeCreate ¶
func (g *Api2GoModel) BeforeCreate() (err error)
func (*Api2GoModel) DeleteToManyIDs ¶
func (m *Api2GoModel) DeleteToManyIDs(name string, IDs []string) error
func (Api2GoModel) GetAllAsAttributes ¶
func (m Api2GoModel) GetAllAsAttributes() map[string]interface{}
func (Api2GoModel) GetAttributes ¶
func (m Api2GoModel) GetAttributes() map[string]interface{}
func (Api2GoModel) GetAuditModel ¶
func (g Api2GoModel) GetAuditModel() Api2GoModel
func (Api2GoModel) GetChanges ¶
func (g Api2GoModel) GetChanges() map[string]Change
func (Api2GoModel) GetColumnMap ¶
func (a Api2GoModel) GetColumnMap() map[string]ColumnInfo
func (Api2GoModel) GetColumnNames ¶
func (m Api2GoModel) GetColumnNames() []string
func (Api2GoModel) GetColumnOriginalValue ¶
func (g Api2GoModel) GetColumnOriginalValue(columnName string) interface{}
func (Api2GoModel) GetColumns ¶
func (m Api2GoModel) GetColumns() []ColumnInfo
func (Api2GoModel) GetCurrentVersion ¶
func (g Api2GoModel) GetCurrentVersion() int64
func (Api2GoModel) GetDefaultPermission ¶
func (g Api2GoModel) GetDefaultPermission() int64
func (Api2GoModel) GetID ¶
func (g Api2GoModel) GetID() string
func (Api2GoModel) GetName ¶
func (g Api2GoModel) GetName() string
func (Api2GoModel) GetNextVersion ¶
func (g Api2GoModel) GetNextVersion() int64
func (Api2GoModel) GetReferenceId ¶
func (g Api2GoModel) GetReferenceId() string
func (Api2GoModel) GetReferencedIDs ¶
func (m Api2GoModel) GetReferencedIDs() []jsonapi.ReferenceID
func (Api2GoModel) GetReferencedStructs ¶
func (m Api2GoModel) GetReferencedStructs() []jsonapi.MarshalIdentifier
func (Api2GoModel) GetReferences ¶
func (model Api2GoModel) GetReferences() []jsonapi.Reference
func (Api2GoModel) GetRelations ¶
func (a Api2GoModel) GetRelations() []TableRelation
func (Api2GoModel) GetTableName ¶
func (g Api2GoModel) GetTableName() string
func (Api2GoModel) GetUnmodifiedAttributes ¶
func (g Api2GoModel) GetUnmodifiedAttributes() map[string]interface{}
func (Api2GoModel) HasColumn ¶
func (a Api2GoModel) HasColumn(colName string) bool
func (Api2GoModel) HasMany ¶
func (a Api2GoModel) HasMany(colName string) bool
func (Api2GoModel) HasVersion ¶
func (g Api2GoModel) HasVersion() bool
func (Api2GoModel) InitializeObject ¶
func (m Api2GoModel) InitializeObject(interface{})
func (Api2GoModel) IsDirty ¶
func (g Api2GoModel) IsDirty() bool
func (*Api2GoModel) Set ¶
func (g *Api2GoModel) Set(columnName string, value interface{})
func (*Api2GoModel) SetAttributes ¶
func (g *Api2GoModel) SetAttributes(attrs map[string]interface{})
func (*Api2GoModel) SetColumns ¶
func (m *Api2GoModel) SetColumns(c []ColumnInfo)
func (*Api2GoModel) SetID ¶
func (g *Api2GoModel) SetID(str string) error
func (*Api2GoModel) SetToManyReferenceIDs ¶
func (m *Api2GoModel) SetToManyReferenceIDs(name string, IDs []map[string]interface{}) error
func (Api2GoModel) SetToOneReferenceID ¶
func (m Api2GoModel) SetToOneReferenceID(name, ID string) error
func (*Api2GoModel) SetType ¶
func (g *Api2GoModel) SetType(typeName string)
type CRUD ¶
type CRUD interface { ResourceCreator ResourceDeleter ResourceUpdater }
The CRUD interface embed all interfaces at once: `ResourceCreator`, `ResourceDeleter`, `ResourceUpdater` (which includes `ResourceGetter`)
type ColumnInfo ¶
type ColumnInfo struct { Name string `db:"name"` ColumnName string `db:"column_name"` ColumnDescription string `db:"column_description"` ColumnType string `db:"column_type"` IsPrimaryKey bool `db:"is_primary_key"` IsAutoIncrement bool `db:"is_auto_increment"` IsIndexed bool `db:"is_indexed"` IsUnique bool `db:"is_unique"` IsNullable bool `db:"is_nullable"` Permission uint64 `db:"permission"` IsForeignKey bool `db:"is_foreign_key"` ExcludeFromApi bool `db:"include_in_api"` ForeignKeyData ForeignKeyData `db:"foreign_key_data"` DataType string `db:"data_type"` DefaultValue string `db:"default_value"` Options []ValueOptions }
type DeleteReferenceInfo ¶
type EditToManyRelations ¶
type EditToManyRelations interface { AddToManyIDs(name string, IDs []string) error DeleteToManyIDs(name string, IDs []string) error }
The EditToManyRelations interface can be optionally implemented to add and delete to-many relationships on a already unmarshalled struct. These methods are used by our API for the to-many relationship update routes.
There are 3 HTTP Methods to edit to-many relations:
PATCH /v1/posts/1/comments Content-Type: application/vnd.api+json Accept: application/vnd.api+json { "data": [ { "type": "comments", "id": "2" }, { "type": "comments", "id": "3" } ] }
This replaces all of the comments that belong to post with ID 1 and the SetToManyReferenceIDs method will be called.
POST /v1/posts/1/comments Content-Type: application/vnd.api+json Accept: application/vnd.api+json { "data": [ { "type": "comments", "id": "123" } ] }
Adds a new comment to the post with ID 1. The AddToManyIDs method will be called.
DELETE /v1/posts/1/comments Content-Type: application/vnd.api+json Accept: application/vnd.api+json { "data": [ { "type": "comments", "id": "12" }, { "type": "comments", "id": "13" } ] }
Deletes comments that belong to post with ID 1. The DeleteToManyIDs method will be called.
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 ForeignKeyData ¶
func (*ForeignKeyData) Scan ¶
func (f *ForeignKeyData) Scan(src interface{}) error
Parse format "namespace:tableName(column)"
func (ForeignKeyData) String ¶
func (f ForeignKeyData) String() string
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 Total uint64 PerPage uint64 CurrentPage uint64 LastPage uint64 NextPageUrl string PrevPageUrl string From uint64 To uint64 }
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 TableRelation ¶
type TableRelation struct { Subject string Object string Relation string SubjectName string ObjectName string Columns []ColumnInfo }
func NewTableRelation ¶
func NewTableRelation(subject, relation, object string) TableRelation
func NewTableRelationWithNames ¶
func NewTableRelationWithNames(subject, subjectName, relation, object, objectName string) TableRelation
func (*TableRelation) GetJoinString ¶
func (tr *TableRelation) GetJoinString() string
func (*TableRelation) GetJoinTableName ¶
func (tr *TableRelation) GetJoinTableName() string
func (*TableRelation) GetObject ¶
func (tr *TableRelation) GetObject() string
func (*TableRelation) GetObjectName ¶
func (tr *TableRelation) GetObjectName() string
func (*TableRelation) GetRelation ¶
func (tr *TableRelation) GetRelation() string
func (*TableRelation) GetReverseJoinString ¶
func (tr *TableRelation) GetReverseJoinString() string
func (*TableRelation) GetSubject ¶
func (tr *TableRelation) GetSubject() string
func (*TableRelation) GetSubjectName ¶
func (tr *TableRelation) GetSubjectName() string
func (*TableRelation) Hash ¶
func (tr *TableRelation) Hash() string
func (*TableRelation) String ¶
func (tr *TableRelation) String() string
type TableRelationInterface ¶
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
type ValueOptions ¶
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. |