Documentation ¶
Overview ¶
Package app aims at providing very simple common application constructs and helpers.
Index ¶
- Constants
- Variables
- func ConfigureLogger(format, level string)
- func ErrorCauses(err error) []string
- func GetEnvironment() string
- func GetErrorData(err error) map[string]interface{}
- func GetErrorStack(err error) []string
- func GetWorkingDir() string
- func MergeWithErrorData(data map[string]interface{}, err error) map[string]interface{}
- func SetLogFormat(format string)
- func SetLogLevel(level string) bool
- func StatsAverageAdd(namespace string, value float64)
- func StatsCounterGet(namespace string) int64
- func StatsCounterIncr(namespace string, value int64)
- func StatsCounterReset(namespace string)
- func StatsDump() ([]byte, error)
- func StatsDumpAndReset() ([]byte, error)
- func StatsTimeAverageAdd(namespace string, start time.Time)
- func StringifyError(err error) string
- type ApplicationError
- type Average
- type ConfigurationMeta
- func LoadConfig(namespace, appName string, configuration interface{}) (*ConfigurationMeta, error)
- func LoadConfigFile(path string, configuration interface{}) (*ConfigurationMeta, error)
- func LoadConfigFromPath(appName string, path string, configuration interface{}) (*ConfigurationMeta, error)
- func LoadEnvConfig(namespace, appName string, configuration interface{}) (*ConfigurationMeta, error)
- type Error
- type ErrorData
- type ILogger
- type KV
- type LoggerConfig
- type Process
- type ProcessManager
- func (manager *ProcessManager) AddProcess(name string, process Process)
- func (manager *ProcessManager) Destroy() map[string]int32
- func (manager *ProcessManager) IsStarted() bool
- func (manager *ProcessManager) Start()
- func (manager *ProcessManager) StatusCheck() (bool, map[string]int32)
- func (manager *ProcessManager) Stop()
- type Stats
- type StatsCollector
Constants ¶
const ( ProcessStateInitialized int32 = iota ProcessStateStarted ProcessStateTerminated ProcessStateAborted )
const ( // ErrorBadRequest should be used as when a request to a function is invalid and there is no other error code which makes more sense. ErrorBadRequest = 4000 // ErrorInvalidParameter should be used when a function parameter has an invalid value. ErrorInvalidParameter = 4001 // ErrorConflict should be used when attempting to save an entity which has a duplicate with conflicting information. ErrorConflict = 4090 // ErrorNotFound should be used when any resource does not exist. It is a generic version of the entity not found. ErrorNotFound = 4040 // ErrorDataInconsistency should be used when the data layer contains unexpected errors or inconsistencies. ErrorDataInconsistency = 5001 // ErrorUnexpected should be used when the error is caused by third party libraries which means that the error cause should be set. ErrorUnexpected = 5002 // ErrorDevPoo should be used when the most likely cause is developer error. ErrorDevPoo = 5003 // ErrorConcurrencyException should be used when an operation fails due to any concurrency issues (deadlock, another operation already running and can only have one, etc). ErrorConcurrencyException = 5004 // ErrorTimeout should be used when an operation exceeds the expected time. ErrorTimeout = 5005 // ErrorOverflow should be used when a buffer, queue, stack, etc limit is exceeded. ErrorOverflow = 5006 // ErrorBufferFull should be used when a buffer is full on a request to add data to the buffer. ErrorBufferFull = 5007 // ErrorBufferEmpty should be used when a buffer is empty on a request to fetch data from a buffer ErrorBufferEmpty = 5008 )
These are sample application errors.
Variables ¶
var Logger = NewLogger("app")
Logger is the global logger
var Util = new(util)
Util is a collection of utiliy tools.
Functions ¶
func ConfigureLogger ¶
func ConfigureLogger(format, level string)
ConfigureLogger sets the logger configuration for the default logger instance.
func ErrorCauses ¶ added in v0.2.0
ErrorCauses returns a slice of all error causes. If error does not implement the Error interface then a nil slice is returned.
func GetEnvironment ¶
func GetEnvironment() string
GetEnvironment returns GOAPP_ENV environment variable or 'local' if not defined.
func GetErrorData ¶ added in v0.2.2
GetErrorData checks the provided error and all subsequent error causes, in the case the error implements the Error interface, for the first error which implements the ErrorData interface and returns the associated data. If no data is found then nil is returned instead.
func GetErrorStack ¶ added in v0.2.5
GetErrorStack returns a slice of the error stack where each error is converted to string.
func GetWorkingDir ¶
func GetWorkingDir() string
GetWorkingDir returns the current working directory
func MergeWithErrorData ¶ added in v0.2.2
MergeWithErrorData merges the provided data with the error's data, if any. This will overwrite any map key with the same name.
func SetLogFormat ¶ added in v0.2.0
func SetLogFormat(format string)
SetLogFormat sets logger output format based on preset templates.
func SetLogLevel ¶ added in v0.2.0
SetLogLevel updates the minimum log level, returns false if the provided level was not valid.
func StatsAverageAdd ¶
StatsAverageAdd recalcs the average using the incremental average algorythm.
func StatsCounterGet ¶
StatsCounterGet returns the current value of the provided stat namespace.
func StatsCounterIncr ¶
StatsCounterIncr increment a counter stat.
func StatsCounterReset ¶
func StatsCounterReset(namespace string)
StatsCounterReset resets the counter value back to 0.
func StatsDumpAndReset ¶
StatsDumpAndReset converts statistics to a JSON byte array and resets them.
func StatsTimeAverageAdd ¶ added in v0.3.0
StatsTimeAverageAdd will take the provided time and calculate the time diference to the present time and add that to the named average. Time unit is miliseconds.
func StringifyError ¶ added in v0.1.4
StringifyError returns an error message, if the passed error is an app.Error then the full error stack is returned where each cause is separated by ';'.
Types ¶
type ApplicationError ¶
type ApplicationError struct { Code int `json:"code"` Message string `json:"message"` Cause error `json:"-"` Data map[string]interface{} `json:"data,omitempty"` }
ApplicationError is a generic implementation of a serializable application Error.The Code should be used instead of the usual type reflection for handling different types of error. There is also a Cause which is not serialized but can be used to wrap original cause of errors. This in turn allows a logger to go through the cause stack and print the whole trace of errors. You should always wrap errors each time you handle them and log the error stack when the error is irrelevant for the upstream.
func NewApplicationError ¶
func NewApplicationError(code int, message string, cause error) *ApplicationError
NewApplicationError creates a new ApplicationError. @deprecated
func NewUnexpectedError ¶ added in v0.1.4
func NewUnexpectedError(message string, cause error) *ApplicationError
NewUnexpectedError is a helper for generating an ApplicationError with error code set to ErrorUnexpected.
func (*ApplicationError) GetData ¶ added in v0.2.2
func (err *ApplicationError) GetData() map[string]interface{}
GetData ...
type Average ¶ added in v0.3.0
type Average struct { Min float64 `json:"min,omitempty"` Max float64 `json:"max,omitempty"` Average float64 `json:"average,omitempty"` Total int64 `json:"total,omitempty"` }
Average is a data structure containing basic statistical information around the notion of average value.
type ConfigurationMeta ¶
type ConfigurationMeta struct {
// contains filtered or unexported fields
}
ConfigurationMeta data structure contains configuration meta information and methods.
func LoadConfig ¶
func LoadConfig(namespace, appName string, configuration interface{}) (*ConfigurationMeta, error)
LoadConfig loads the configuration file for the applicatio name provided. ConfigurationMeta is always set even on error. The configuration must be a JSON file and it is searched in the following places
For remote deployment, container images, etc, use the absolute path
/etc/<namespace>/<GOAPP_ENV>.<appName>.json
For local/per-developer configurations ignore from version control and use
./.{configs,config,etc}/<GOAPP_ENV>.<appName>.json
For versioning configurations with the project for running integration tests or against test environments.
./{configs,config,etc}/<GOAPP_ENV>.<appName>.json
func LoadConfigFile ¶
func LoadConfigFile(path string, configuration interface{}) (*ConfigurationMeta, error)
LoadConfigFile loads a config except you can override the default paths the config is searched in.
func LoadConfigFromPath ¶
func LoadConfigFromPath(appName string, path string, configuration interface{}) (*ConfigurationMeta, error)
LoadConfigFromPath loads a config except you can override the default paths the config is searched in.
func LoadEnvConfig ¶ added in v0.4.2
func LoadEnvConfig(namespace, appName string, configuration interface{}) (*ConfigurationMeta, error)
LoadEnvConfig loads the configuration file for the applicatio name provided. ConfigurationMeta is always set even on error. The configuration must be a JSON file and it is searched in the following places
For remote deployment, container images, etc, use the absolute path
/etc/<namespace>/<appName>.json
For local/per-developer configurations ignore from version control and use
./.{configs,config,etc}/<GOAPP_ENV>/<appName>.json
For versioning configurations with the project for running integration tests or against test environments.
./{configs,config,etc}/<GOAPP_ENV>/<appName>.json
func (*ConfigurationMeta) GetConfigFile ¶
func (config *ConfigurationMeta) GetConfigFile() string
GetConfigFile returns the path to the configuration file used.
func (*ConfigurationMeta) GetConfigFolder ¶
func (config *ConfigurationMeta) GetConfigFolder() string
GetConfigFolder returns the dirname of the config file path.
type Error ¶
Error interface for wrapping application errors with error codes for faster error type switching.
type ErrorData ¶ added in v0.2.2
ErrorData interface is a an extension of the Error interface in order to provide structured data associated with an error. Useful for including identifiers and relevant information about the error.
type ILogger ¶ added in v0.2.0
type ILogger interface { log.Logger LogError(err error, msg string) LogErrorf(err error, format string, args ...interface{}) LogFatalError(err error, msg string) LogCallers(msg string, endDepth int) }
ILogger defines the application logging interface
type LoggerConfig ¶
type LoggerConfig struct { // Level defines the minimum log level, anything lower is not logged. Levels are: debug, info, warn and error. Level string `json:"level" mapstructure:"level"` // Mode is the named template to use for each log line. Valid templates: noob, dev, simple, json. Defaults to json. Mode string `json:"mode" mapstructure:"mode"` }
LoggerConfig structure.
type Process ¶
type Process interface { // Start should block while running the processes and right before terminating should write to the control chan. Start() error Stop() error }
Process is the basic interface for any assynchronous process launched and stopped by the process manager.
type ProcessManager ¶
ProcessManager handles your processes.
func NewProcessManager ¶
func NewProcessManager() *ProcessManager
NewProcessManager creates a new instance of a ProcessManager.
func (*ProcessManager) AddProcess ¶
func (manager *ProcessManager) AddProcess(name string, process Process)
AddProcess stores a proces in the list of processes controlled by the ProcessManager.
func (*ProcessManager) Destroy ¶ added in v0.2.7
func (manager *ProcessManager) Destroy() map[string]int32
Destroy removes all processes and closes all channels.
func (*ProcessManager) IsStarted ¶ added in v0.1.3
func (manager *ProcessManager) IsStarted() bool
IsStarted returns true if the ProcessManager has already started.
func (*ProcessManager) Start ¶
func (manager *ProcessManager) Start()
Start blocks until it receives a signal in its control channel or a SIGTERM, SIGINT or SIGUSR1, and should be the last method in your main.
func (*ProcessManager) StatusCheck ¶ added in v0.2.7
func (manager *ProcessManager) StatusCheck() (bool, map[string]int32)
StatusCheck returns a tupple where the first value is a bool indicating if all processes are OK, second value is a map for de individual status of each process.
func (*ProcessManager) Stop ¶
func (manager *ProcessManager) Stop()
Stop will signal the ProcessManager to stop.
type Stats ¶ added in v0.3.0
type Stats struct { Counters map[string]int64 `json:"counters,omitempty"` Averages map[string]Average `json:"averages,omitempty"` }
Stats is a data structure aggregating multiple statistical data.
func StatsGet ¶ added in v0.3.0
func StatsGet() Stats
StatsGet returns a copy of the current application statistics.
func StatsGetAndReset ¶ added in v0.3.0
func StatsGetAndReset() Stats
StatsGetAndReset returns a copy of the current application statistics and resets them.
type StatsCollector ¶ added in v0.3.0
type StatsCollector interface { // CounterReset will reset the named counter back to 0. CounterReset(name string) // CounterIncr will increment the named counter by the provided amount (can be a negative value). CounterIncr(name string, amount int64) // CounterGet will return the current value of the named counter. CounterGet(name string) int64 // TimeAverageAdd will take the provided time and calculate the time diference to the present time and add that to the named average. Time unit is miliseconds. TimeAverageAdd(name string, value time.Time) // AverageAdd will add the provided value to the named average collector. AverageAdd(name string, value float64) // AverageGet will return the named average. AverageGet(name string) Average // AverageReset will reset the named average back to the zero value. AverageReset(name string) // Dump converts stats into a JSON file. Dump() ([]byte, error) // DumpAndReset converts statistics to a JSON byte array and resets them. DumpAndReset() ([]byte, error) // Get returns all statistics. Get() Stats // GetAndReset returns all statistics and then resets all values. GetAndReset() Stats }
StatsCollector interface for a collector of statistical data such as counters and averages.
func NewStatsCollector ¶ added in v0.3.0
func NewStatsCollector() StatsCollector
NewStatsCollector creates a new instance of a StatsCollector.