Documentation ¶
Overview ¶
Package api provides an API for integration with other components of the same software package and also third party components.
It provides direct database access as well as a simpler way to register API endpoints. You can of course also register raw `http.Handler`s directly.
Optional authentication guards registered handlers. This is achieved by attaching functions to the `http.Handler`s that are registered, which allow them to specify the required permissions for the handler.
The permissions are divided into the roles and assume a single user per host. The Roles are User, Admin and Self. User roles are expected to have mostly read access and react to notifications or system events, like a system tray program. The Admin role is meant for advanced components that also change settings, but are restricted so they cannot break the software. Self is reserved for internal use with full access.
Index ¶
- Constants
- Variables
- func ErrorWithStatus(err error, code int) error
- func MarshalRecord(r record.Record, withDSDIdentifier bool) ([]byte, error)
- func RegisterEndpoint(e Endpoint) error
- func RegisterHandleFunc(path string, handleFunc func(http.ResponseWriter, *http.Request)) *mux.Route
- func RegisterHandler(path string, handler http.Handler) *mux.Route
- func RequestLogger(next http.Handler) http.Handler
- func SetAuthenticator(fn AuthenticatorFunc) error
- func SetDefaultAPIListenAddress(address string)
- func TextResponse(w http.ResponseWriter, r *http.Request, text string)
- func WrapInAuthHandler(fn http.HandlerFunc, read, write Permission) http.Handler
- type API
- type ActionFunc
- type AuthToken
- type AuthenticatedHandler
- type AuthenticatorFunc
- type DataFunc
- type DatabaseAPI
- type DatabaseWebsocketAPI
- type Endpoint
- type EndpointBridgeRequest
- type EndpointBridgeResponse
- type HTTPStatusError
- type HTTPStatusProvider
- type LoggingResponseWriter
- type Parameter
- type Permission
- type RecordFunc
- type Request
- type StructFunc
Constants ¶
const ( CfgDefaultListenAddressKey = "core/listenAddress" CfgAPIKeys = "core/apiKeys" )
Config Keys.
const ( MimeTypeJSON string = "application/json" MimeTypeText string = "text/plain" )
MIME Types.
Variables ¶
var ( // ErrInvalidEndpoint is returned when an invalid endpoint is registered. ErrInvalidEndpoint = errors.New("endpoint is invalid") // ErrAlreadyRegistered is returned when there already is an endpoint with // the same path registered. ErrAlreadyRegistered = errors.New("an endpoint for this path is already registered") )
var ( ErrAuthenticationAlreadySet = errors.New("the authentication function has already been set") ErrAuthenticationImmutable = errors.New("the authentication function can only be set before the api has started") )
API Errors.
var EnableServer = true
EnableServer defines if the HTTP server should be started.
var ( // ErrAPIAccessDeniedMessage should be wrapped by errors returned by // AuthenticatorFunc in order to signify a blocked request, including a error // message for the user. This is an empty message on purpose, as to allow the // function to define the full text of the error shown to the user. ErrAPIAccessDeniedMessage = errors.New("") )
var RequestContextKey = apiRequestContextKey{}
RequestContextKey is the key used to add the API request to the context.
Functions ¶
func ErrorWithStatus ¶
ErrorWithStatus adds the HTTP status code to the error.
func MarshalRecord ¶
MarshalRecord locks and marshals the given record, additionally adding metadata and returning it as json.
func RegisterEndpoint ¶
RegisterEndpoint registers a new endpoint. An error will be returned if it does not pass the sanity checks.
func RegisterHandleFunc ¶
func RegisterHandleFunc(path string, handleFunc func(http.ResponseWriter, *http.Request)) *mux.Route
RegisterHandleFunc registers a handle function with the API endpoint.
func RegisterHandler ¶
RegisterHandler registers a handler with the API endpoint.
func RequestLogger ¶
RequestLogger is a logging middleware.
func SetAuthenticator ¶
func SetAuthenticator(fn AuthenticatorFunc) error
SetAuthenticator sets an authenticator function for the API endpoint. If none is set, all requests will be permitted.
func SetDefaultAPIListenAddress ¶
func SetDefaultAPIListenAddress(address string)
SetDefaultAPIListenAddress sets the default listen address for the API.
func TextResponse ¶
func TextResponse(w http.ResponseWriter, r *http.Request, text string)
TextResponse writes a text response.
func WrapInAuthHandler ¶
func WrapInAuthHandler(fn http.HandlerFunc, read, write Permission) http.Handler
WrapInAuthHandler wraps a simple http.HandlerFunc into a handler that exposes the required API permissions for this handler.
Types ¶
type API ¶
type API struct {
// contains filtered or unexported fields
}
API is the HTTP/Websockets API module.
type ActionFunc ¶
ActionFunc is for simple actions with a return message for the user.
type AuthToken ¶
type AuthToken struct { Read Permission Write Permission ValidUntil *time.Time }
AuthToken represents either a set of required or granted permissions. All attributes must be set when the struct is built and must not be changed later. Functions may be called at any time. The Write permission implicitly also includes reading.
type AuthenticatedHandler ¶
type AuthenticatedHandler interface { ReadPermission(r *http.Request) Permission WritePermission(r *http.Request) Permission }
AuthenticatedHandler defines the handler interface to specify custom permission for an API handler. The returned permission is the required permission for the request to proceed.
type AuthenticatorFunc ¶
AuthenticatorFunc is a function that can be set as the authenticator for the API endpoint. If none is set, all requests will have full access. The returned AuthToken represents the permissions that the request has.
type DatabaseAPI ¶
type DatabaseAPI struct {
// contains filtered or unexported fields
}
DatabaseAPI is a generic database API interface.
func CreateDatabaseAPI ¶
func CreateDatabaseAPI(sendFunction func(data []byte)) DatabaseAPI
CreateDatabaseAPI creates a new database interface.
func (*DatabaseAPI) Handle ¶
func (api *DatabaseAPI) Handle(msg []byte)
Handle handles a message for the database API.
type DatabaseWebsocketAPI ¶
type DatabaseWebsocketAPI struct { DatabaseAPI // contains filtered or unexported fields }
DatabaseWebsocketAPI is a database websocket API interface.
type Endpoint ¶
type Endpoint struct { // Name is the human reabable name of the endpoint. Name string // Description is the human readable description and documentation of the endpoint. Description string // Parameters is the parameter documentation. Parameters []Parameter `json:",omitempty"` // Path describes the URL path of the endpoint. Path string // MimeType defines the content type of the returned data. MimeType string // Read defines the required read permission. Read Permission `json:",omitempty"` // ReadMethod sets the required read method for the endpoint. // Available methods are: // GET: Returns data only, no action is taken, nothing is changed. // If omitted, defaults to GET. // // This field is currently being introduced and will only warn and not deny // access if the write method does not match. ReadMethod string `json:",omitempty"` // Write defines the required write permission. Write Permission `json:",omitempty"` // WriteMethod sets the required write method for the endpoint. // Available methods are: // POST: Create a new resource; Change a status; Execute a function // PUT: Update an existing resource // DELETE: Remove an existing resource // If omitted, defaults to POST. // // This field is currently being introduced and will only warn and not deny // access if the write method does not match. WriteMethod string `json:",omitempty"` // ActionFunc is for simple actions with a return message for the user. ActionFunc ActionFunc `json:"-"` // DataFunc is for returning raw data that the caller for further processing. DataFunc DataFunc `json:"-"` // StructFunc is for returning any kind of struct. StructFunc StructFunc `json:"-"` // RecordFunc is for returning a database record. It will be properly locked // and marshalled including metadata. RecordFunc RecordFunc `json:"-"` // HandlerFunc is the raw http handler. HandlerFunc http.HandlerFunc `json:"-"` }
Endpoint describes an API Endpoint. Path and at least one permission are required. As is exactly one function.
func ExportEndpoints ¶
func ExportEndpoints() []*Endpoint
ExportEndpoints exports the registered endpoints. The returned data must be treated as immutable.
func GetEndpointByPath ¶
GetEndpointByPath returns the endpoint registered with the given path.
type EndpointBridgeRequest ¶
type EndpointBridgeRequest struct { record.Base sync.Mutex Method string Path string Query map[string]string Data []byte MimeType string }
EndpointBridgeRequest holds a bridged request API request.
type EndpointBridgeResponse ¶
EndpointBridgeResponse holds a bridged request API response.
type HTTPStatusError ¶
type HTTPStatusError struct {
// contains filtered or unexported fields
}
HTTPStatusError represents an error with an HTTP status code.
func (*HTTPStatusError) Error ¶
func (e *HTTPStatusError) Error() string
Error returns the error message.
func (*HTTPStatusError) HTTPStatus ¶
func (e *HTTPStatusError) HTTPStatus() int
HTTPStatus returns the HTTP status code this error.
func (*HTTPStatusError) Unwrap ¶
func (e *HTTPStatusError) Unwrap() error
Unwrap return the wrapped error.
type HTTPStatusProvider ¶
type HTTPStatusProvider interface {
HTTPStatus() int
}
HTTPStatusProvider is an interface for errors to provide a custom HTTP status code.
type LoggingResponseWriter ¶
type LoggingResponseWriter struct { ResponseWriter http.ResponseWriter Request *http.Request Status int }
LoggingResponseWriter is a wrapper for http.ResponseWriter for better request logging.
func NewLoggingResponseWriter ¶
func NewLoggingResponseWriter(w http.ResponseWriter, r *http.Request) *LoggingResponseWriter
NewLoggingResponseWriter wraps a http.ResponseWriter.
func (*LoggingResponseWriter) Header ¶
func (lrw *LoggingResponseWriter) Header() http.Header
Header wraps the original Header method.
func (*LoggingResponseWriter) Hijack ¶
func (lrw *LoggingResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error)
Hijack wraps the original Hijack method, if available.
func (*LoggingResponseWriter) Write ¶
func (lrw *LoggingResponseWriter) Write(b []byte) (int, error)
Write wraps the original Write method.
func (*LoggingResponseWriter) WriteHeader ¶
func (lrw *LoggingResponseWriter) WriteHeader(code int)
WriteHeader wraps the original WriteHeader method to extract information.
type Permission ¶
type Permission int8
Permission defines an API requests permission.
const ( // NotFound declares that the operation does not exist. NotFound Permission = -2 // Dynamic declares that the operation requires permission to be processed, // but anyone can execute the operation, as it reacts to permissions itself. Dynamic Permission = -1 // NotSupported declares that the operation is not supported. NotSupported Permission = 0 // PermitAnyone declares that anyone can execute the operation without any // authentication. PermitAnyone Permission = 1 // PermitUser declares that the operation may be executed by authenticated // third party applications that are categorized as representing a simple // user and is limited in access. PermitUser Permission = 2 // PermitAdmin declares that the operation may be executed by authenticated // third party applications that are categorized as representing an // administrator and has broad in access. PermitAdmin Permission = 3 // PermitSelf declares that the operation may only be executed by the // software itself and its own (first party) components. PermitSelf Permission = 4 )
func (Permission) Role ¶
func (p Permission) Role() string
Role returns a string representation of the permission role.
func (Permission) String ¶
func (p Permission) String() string
type RecordFunc ¶
RecordFunc is for returning a database record. It will be properly locked and marshalled including metadata.
type Request ¶
type Request struct { // Request is the http request. *http.Request // InputData contains the request body for write operations. InputData []byte // Route of this request. Route *mux.Route // URLVars contains the URL variables extracted by the gorilla mux. URLVars map[string]string // AuthToken is the request-side authentication token assigned. AuthToken *AuthToken // ResponseHeader holds the response header. ResponseHeader http.Header // HandlerCache can be used by handlers to cache data between handlers within a request. HandlerCache interface{} }
Request is a support struct to pool more request related information.
func GetAPIRequest ¶
GetAPIRequest returns the API Request of the given http request.
type StructFunc ¶
StructFunc is for returning any kind of struct.