server

package
v0.0.0-...-60f5d5a Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 18, 2024 License: MIT Imports: 31 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// ConfigKeyValidateSchemaLocation - Directory location of JSON schema's
	ConfigKeyValidateSchemaLocation string = "validateSchemaLocation"
	// ConfigKeyValidateMainSchema - Main schema that can include reference schema's
	ConfigKeyValidateMainSchema string = "validateMainSchema"
	// ConfigKeyValidateReferenceSchemas - Schema referenced from the main schema
	ConfigKeyValidateReferenceSchemas string = "validateReferenceSchemas"
)
View Source
const (
	HeaderXPagination = "X-Pagination"
)
View Source
const HeaderXTxLockWaitTimeoutSeconds = "X-Tx-Lock-Wait-Timeout-Seconds"

HeaderXTxLockWaitTimeoutSeconds is used to specify the lock wait timeout for database locks. The value cannot exceed the WriteTimeout set on the server. This can be used to test locking behaviour by first making an API request that explicitly or implicitly acquires a lock (i.e., UPDATE, DELETE) with HeaderXWaitSeconds with a value greater than HeaderXTxLockWaitTimeoutSeconds, and, in that intervening period, make another request that explicitly or implicitly attempts to acquire a lock on the same rows.

View Source
const HeaderXTxRollback = "X-Tx-Rollback"

HeaderXTxRollback is used to rollback API transactions during testing.

The only handler tests where the API Server must commit the DB transaction are those that contain further DB queries, which must be able to see changes made by the API server tx. This is due to the current default transaction isolation level (read committed).

View Source
const HeaderXWaitSeconds = "X-Wait-Seconds"

HeaderXWaitSeconds causes the request to take at least some amount of time to complete. The value cannot exceed the WriteTimeout set on the server. This can be used to:

1) simulate server load; or

2) test locking behaviour.

Variables

This section is empty.

Functions

func GetCorrelationID

func GetCorrelationID(l logger.Logger, r *http.Request) (string, error)

func Logger

func Logger(l logger.Logger, functionName string) logger.Logger

func ReadRequest

func ReadRequest[T any](l logger.Logger, r *http.Request, s *T) (*T, error)

ReadRequest -

func ReadXMLRequest

func ReadXMLRequest(l logger.Logger, r *http.Request, s interface{}) (*string, error)

ReadXMLRequest -

func RequestData

func RequestData(l logger.Logger, r *http.Request) *string

RequestData -

func ToAuthenticationSet

func ToAuthenticationSet(authen ...AuthenticationType) map[AuthenticationType]struct{}

func ToAuthorizationPermissionsSet

func ToAuthorizationPermissionsSet(permissions ...AuthorizedPermission) map[AuthorizedPermission]struct{}

func ValidateAuthenticationTypes

func ValidateAuthenticationTypes(handlerConfig map[string]HandlerConfig) error

func WriteError

func WriteError(l logger.Logger, w http.ResponseWriter, errs ...error)

func WriteMalformedError

func WriteMalformedError(l logger.Logger, w http.ResponseWriter, err error)

func WriteNotFoundError

func WriteNotFoundError(l logger.Logger, w http.ResponseWriter, entity string, id string)

func WritePaginatedResponse

func WritePaginatedResponse[R any, D any](l logger.Logger, w http.ResponseWriter, recs []R, mapper func(R) (D, error), pageSize int) error

func WriteResponse

func WriteResponse(l logger.Logger, w http.ResponseWriter, status int, r interface{}, options ...WriteResponseOption) error

WriteResponse -

func WriteSystemError

func WriteSystemError(l logger.Logger, w http.ResponseWriter, err error)

func WriteUnauthorizedError

func WriteUnauthorizedError(l logger.Logger, w http.ResponseWriter, err error)

func WriteUnavailableError

func WriteUnavailableError(l logger.Logger, w http.ResponseWriter, err error)

func WriteXMLErrorResponse

func WriteXMLErrorResponse(l logger.Logger, w http.ResponseWriter, s interface{}, e error)

WriteXMLErrorResponse responds with an 200 HTTP Status Code. For Service Cloud to retry message delivery, a nack (false) should be sent instead.

func WriteXMLResponse

func WriteXMLResponse(l logger.Logger, w http.ResponseWriter, s interface{}) error

func XPaginationHeader

func XPaginationHeader(collectionLen int, pageSize int) func(http.ResponseWriter) error

func XPaginationHeaderValue

func XPaginationHeaderValue(hasMore bool) string

Types

type AuthenticatedRequest

type AuthenticatedRequest struct {
	Type        AuthenticatedType      `json:"type"`
	User        AuthenticatedUser      `json:"user"`
	Permissions []AuthorizedPermission `json:"permissions"`
}

type AuthenticatedType

type AuthenticatedType string
const (
	AuthenticatedTypeUser   AuthenticatedType = "User"
	AuthenticatedTypeAPIKey AuthenticatedType = "APIKey"
)

type AuthenticatedUser

type AuthenticatedUser struct {
	ID    any    `json:"id"`
	Name  string `json:"name"`
	Email string `json:"email"`
}

type AuthenticationType

type AuthenticationType string
const (
	AuthenticationTypePublic     AuthenticationType = "Public"
	AuthenticationTypeRestricted AuthenticationType = "Restricted"
	AuthenticationTypeAPIKey     AuthenticationType = "API Key"
	AuthenticationTypeJWT        AuthenticationType = "JWT"
)

type AuthorizedPermission

type AuthorizedPermission string

type Config

type Config struct {
	AppServerEnv             string
	AppServerHost            string
	AppServerHome            string
	AppServerPort            string
	AppImageTagFeatureBranch string
	AppImageTagSHA           string
}

func NewConfig

func NewConfig(c configurer.Configurer) (*Config, error)

func (*Config) ValidateHTTP

func (c *Config) ValidateHTTP() error

ValidateHTTP validates the minimum required configuration has been provided to run the HTTP server.

type DocumentationConfig

type DocumentationConfig struct {
	Document    bool
	Summary     string // used for API doc endpoint title
	Description string // used for API doc endpoint description
}

DocumentationConfig - Configuration describing how to document a route

type HTTPCORSConfig

type HTTPCORSConfig struct {
	AllowedOrigins   []string
	AllowedHeaders   []string
	ExposedHeaders   []string
	AllowCredentials bool
}

type Handle

Handle - custom service handle

type HandlerConfig

type HandlerConfig struct {
	Name string
	// Method - The HTTP method
	Method string
	// Path - The HTTP request URI including :parameter placeholders
	Path string
	// HandlerFunc - Function to handle requests for this method and path
	HandlerFunc Handle
	// MiddlewareConfig -
	MiddlewareConfig MiddlewareConfig
	// DocumentationConfig -
	DocumentationConfig DocumentationConfig
}

HandlerConfig - configuration for routes, handlers and middleware

type HttpMethod

type HttpMethod string
const (
	HttpMethodGet     HttpMethod = http.MethodGet
	HttpMethodHead    HttpMethod = http.MethodHead
	HttpMethodPost    HttpMethod = http.MethodPost
	HttpMethodPut     HttpMethod = http.MethodPut
	HttpMethodPatch   HttpMethod = http.MethodPatch
	HttpMethodDelete  HttpMethod = http.MethodDelete
	HttpMethodConnect HttpMethod = http.MethodConnect
	HttpMethodOptions HttpMethod = http.MethodOptions
	HttpMethodTrace   HttpMethod = http.MethodTrace
)

type MiddlewareConfig

type MiddlewareConfig struct {
	AuthenTypes            []AuthenticationType
	AuthzPermissions       []AuthorizedPermission
	ValidateRequestSchema  *jsonschema.SchemaWithReferences
	ValidateResponseSchema *jsonschema.SchemaWithReferences
	ValidateParamsConfig   *ValidateParamsConfig
}

MiddlewareConfig - configuration for global default middleware

type MiddlewareFunc

type MiddlewareFunc func(hc HandlerConfig, h Handle) (Handle, error)

type Response

type Response struct {
	Error      *ResponseError      `json:"error,omitempty"`
	Pagination *ResponsePagination `json:"pagination,omitempty"`
}

Response -

type ResponseError

type ResponseError struct {
	Code   string `json:"code"`
	Detail string `json:"detail"`
}

ResponseError -

type ResponsePagination

type ResponsePagination struct {
	Number int `json:"page_number"`
	Size   int `json:"page_size"`
	Count  int `json:"page_count"`
}

ResponsePagination -

type Runner

type Runner struct {
	Config             configurer.Configurer
	Log                logger.Logger
	Store              storer.Storer
	RepositoryPreparer preparer.Repository
	QueryPreparer      preparer.Query

	// HTTPCORSConfig
	HTTPCORSConfig HTTPCORSConfig

	// Handler and message configuration
	HandlerConfig map[string]HandlerConfig

	// Run functions
	RunHTTPFunc   func(args map[string]interface{}) (*http.Server, error)
	RunDaemonFunc func(args map[string]interface{}) error

	// RouterFunc
	RouterFunc func(router *httprouter.Router) (*httprouter.Router, error)

	// HandlerFunc is the default handler function. It is used for liveness and healthz. Therefore, it should execute quickly.
	HandlerFunc Handle

	// HandlerMiddlewareFuncs returns a list of middleware functions to apply to routes
	HandlerMiddlewareFuncs func() []MiddlewareFunc

	// Service feature callbacks
	AuthenticateRequestFunc func(l logger.Logger, m modeller.Modeller, apiKey string) (AuthenticatedRequest, error)

	// Domain layer
	ModellerFunc func(l logger.Logger) (modeller.Modeller, error)

	// Data layer
	RepositoryPreparerFunc func(l logger.Logger) (preparer.Repository, error)
	QueryPreparerFunc      func(l logger.Logger) (preparer.Query, error)
	// contains filtered or unexported fields
}

Runner - implements the runnerer interface

func NewRunner

func NewRunner(c configurer.Configurer, l logger.Logger) (*Runner, error)

func (*Runner) ApplyMiddleware

func (rnr *Runner) ApplyMiddleware(hc HandlerConfig, h Handle) (httprouter.Handle, error)

ApplyMiddleware applies middleware by the assigned middleware function

func (*Runner) AuthenMiddleware

func (rnr *Runner) AuthenMiddleware(hc HandlerConfig, h Handle) (Handle, error)

AuthenMiddleware -

func (*Runner) AuthzMiddleware

func (rnr *Runner) AuthzMiddleware(hc HandlerConfig, h Handle) (Handle, error)

AuthzMiddleware -

func (*Runner) CorrelationMiddleware

func (rnr *Runner) CorrelationMiddleware(hc HandlerConfig, h Handle) (Handle, error)

CorrelationMiddleware -

func (*Runner) DataMiddleware

func (rnr *Runner) DataMiddleware(hc HandlerConfig, h Handle) (Handle, error)

DataMiddleware -

func (*Runner) HttpRouterHandlerWrapper

func (rnr *Runner) HttpRouterHandlerWrapper(h Handle) httprouter.Handle

HttpRouterHandlerWrapper wraps a Handle function in an httprouter.Handle function while also providing a new logger for every request. Typically this function should be used to wrap the final product of applying all middleware to Handle function.

func (*Runner) Init

func (rnr *Runner) Init(s storer.Storer) error

Init - override to perform custom initialization

func (*Runner) InitTx

func (rnr *Runner) InitTx(l logger.Logger) (modeller.Modeller, error)

InitTx initialises a new database transaction returning a prepared modeller

func (*Runner) ParamMiddleware

func (rnr *Runner) ParamMiddleware(hc HandlerConfig, h Handle) (Handle, error)

ParamMiddleware -

func (*Runner) RegisterDefaultHealthzRoute

func (rnr *Runner) RegisterDefaultHealthzRoute(r *httprouter.Router) (*httprouter.Router, error)

func (*Runner) RegisterDefaultLivenessRoute

func (rnr *Runner) RegisterDefaultLivenessRoute(r *httprouter.Router) (*httprouter.Router, error)

func (*Runner) ResolveHandlerSchemaLocations

func (rnr *Runner) ResolveHandlerSchemaLocations() error

func (*Runner) Run

func (rnr *Runner) Run(args map[string]interface{}) error

Run starts the HTTP server and daemon processes. Override to implement a custom run function.

func (*Runner) RunDaemon

func (rnr *Runner) RunDaemon(args map[string]interface{}) error

RunDaemon - Starts the daemon process. Override to implement a custom daemon run function. The daemon process is a long running background process intended to listen or poll for events and then process those events.

func (*Runner) RunHTTP

func (rnr *Runner) RunHTTP(args map[string]interface{}) (*http.Server, error)

RunHTTP - Starts the HTTP server process. Override to implement a custom HTTP server run function. The server process exposes a REST API and is intended for clients to manage resources and perform actions.

func (*Runner) TxMiddleware

func (rnr *Runner) TxMiddleware(hc HandlerConfig, h Handle) (Handle, error)

TxMiddleware -

func (*Runner) WaitMiddleware

func (rnr *Runner) WaitMiddleware(hc HandlerConfig, h Handle) (Handle, error)

type Server

type Server struct {
	Config configurer.Configurer
	Log    logger.Logger
	Store  storer.Storer
	Runner runnable.Runnable
}

Server -

func NewServer

NewServer -

func (*Server) Init

func (svr *Server) Init() error

Init -

func (*Server) Run

func (svr *Server) Run(args map[string]interface{}) error

Run -

type ValidateParamsConfig

type ValidateParamsConfig struct {
	ExcludePathParamsFromQueryParams bool
	RemoveParamPrefixes              []string
	PathParamSchema                  *jsonschema.SchemaWithReferences
	QueryParamSchema                 *jsonschema.SchemaWithReferences
}

ValidateParamsConfig defines how route path parameters should be validated

ExcludePathParamsFromQueryParams - By default path parameters will be added as query parameters and validated as part of query parameter validation. When disabled path parameters will need to be validated in handler functions

RemoveParamPrefixes - TODO: Removes the specified prefixes from parameters

PathParamSchema - Validate path parameters using this JSON schema set

QueryParamSchema - Validate query parameters using this JSON schema set

type WriteResponseOption

type WriteResponseOption = func(http.ResponseWriter) error

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL