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 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 Serve()
- 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 ActionFunc
- type AuthToken
- type AuthenticatedHandler
- type AuthenticatorFunc
- type DataFunc
- type DatabaseAPI
- type Endpoint
- type EndpointBridgeRequest
- type EndpointBridgeResponse
- type LoggingResponseWriter
- type ModuleHandler
- 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 ( // 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("") )
Functions ¶
func RegisterEndpoint ¶ added in v0.9.4
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 endoint.
func RegisterHandler ¶ added in v0.3.0
RegisterHandler registers a handler with the API endoint.
func RequestLogger ¶
RequestLogger is a logging middleware.
func SetAuthenticator ¶ added in v0.3.0
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 ¶ added in v0.9.4
func TextResponse(w http.ResponseWriter, r *http.Request, text string)
TextResponse writes a text response.
func WrapInAuthHandler ¶ added in v0.9.4
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 ActionFunc ¶ added in v0.9.4
ActionFunc is for simple actions with a return message for the user.
type AuthToken ¶ added in v0.9.4
type AuthToken struct { Read Permission Write Permission }
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 ¶ added in v0.9.4
type AuthenticatedHandler interface { ReadPermission(*http.Request) Permission WritePermission(*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 ¶ added in v0.9.4
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 DataFunc ¶ added in v0.9.4
DataFunc is for returning raw data that the caller for further processing.
type DatabaseAPI ¶
type DatabaseAPI struct {
// contains filtered or unexported fields
}
DatabaseAPI is a database API instance.
type Endpoint ¶ added in v0.9.4
type Endpoint struct { Path string MimeType string Read Permission Write Permission BelongsTo *modules.Module // 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:"-"` Name string Description string Parameters []Parameter }
Endpoint describes an API Endpoint. Path and at least one permission are required. As is exactly one function.
func ExportEndpoints ¶ added in v0.9.4
func ExportEndpoints() []*Endpoint
ExportEndpoints exports the registered endpoints. The returned data must be treated as immutable.
type EndpointBridgeRequest ¶ added in v0.10.0
type EndpointBridgeResponse ¶ added in v0.10.0
type LoggingResponseWriter ¶ added in v0.3.0
type LoggingResponseWriter struct { ResponseWriter http.ResponseWriter Request *http.Request Status int }
LoggingResponseWriter is a wrapper for http.ResponseWriter for better request logging.
func NewLoggingResponseWriter ¶ added in v0.3.0
func NewLoggingResponseWriter(w http.ResponseWriter, r *http.Request) *LoggingResponseWriter
NewLoggingResponseWriter wraps a http.ResponseWriter.
func (*LoggingResponseWriter) Header ¶ added in v0.3.0
func (lrw *LoggingResponseWriter) Header() http.Header
Header wraps the original Header method.
func (*LoggingResponseWriter) Hijack ¶ added in v0.3.0
func (lrw *LoggingResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error)
Hijack wraps the original Hijack method, if available.
func (*LoggingResponseWriter) Write ¶ added in v0.3.0
func (lrw *LoggingResponseWriter) Write(b []byte) (int, error)
Write wraps the original Write method.
func (*LoggingResponseWriter) WriteHeader ¶ added in v0.3.0
func (lrw *LoggingResponseWriter) WriteHeader(code int)
WriteHeader wraps the original WriteHeader method to extract information.
type ModuleHandler ¶ added in v0.10.2
type Permission ¶ added in v0.9.4
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 ¶ added in v0.9.4
func (p Permission) Role() string
Role returns a string representation of the permission role.
func (Permission) String ¶ added in v0.9.4
func (p Permission) String() string
type RecordFunc ¶ added in v0.9.4
RecordFunc is for returning a database record. It will be properly locked and marshalled including metadata.
type Request ¶ added in v0.9.4
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 // 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 ¶ added in v0.9.4
GetAPIRequest returns the API Request of the given http request.
type StructFunc ¶ added in v0.9.4
StructFunc is for returning any kind of struct.