app

package
v0.4.4 Latest Latest
Warning

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

Go to latest
Published: Jul 2, 2018 License: MIT Imports: 17 Imported by: 1

Documentation

Overview

Package app aims at providing very simple common application constructs and helpers.

Index

Constants

View Source
const (
	ProcessStateInitialized int32 = iota
	ProcessStateStarted
	ProcessStateTerminated
	ProcessStateAborted
)
View Source
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

View Source
var Logger = NewLogger("app")

Logger is the global logger

View Source
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

func ErrorCauses(err error) []string

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

func GetErrorData(err error) map[string]interface{}

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

func GetErrorStack(err error) []string

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

func MergeWithErrorData(data map[string]interface{}, err error) map[string]interface{}

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

func SetLogLevel(level string) bool

SetLogLevel updates the minimum log level, returns false if the provided level was not valid.

func StatsAverageAdd

func StatsAverageAdd(namespace string, value float64)

StatsAverageAdd recalcs the average using the incremental average algorythm.

func StatsCounterGet

func StatsCounterGet(namespace string) int64

StatsCounterGet returns the current value of the provided stat namespace.

func StatsCounterIncr

func StatsCounterIncr(namespace string, value int64)

StatsCounterIncr increment a counter stat.

func StatsCounterReset

func StatsCounterReset(namespace string)

StatsCounterReset resets the counter value back to 0.

func StatsDump

func StatsDump() ([]byte, error)

StatsDump converts stats into a JSON file.

func StatsDumpAndReset

func StatsDumpAndReset() ([]byte, error)

StatsDumpAndReset converts statistics to a JSON byte array and resets them.

func StatsTimeAverageAdd added in v0.3.0

func StatsTimeAverageAdd(namespace string, start time.Time)

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

func StringifyError(err error) string

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) Error

func (err *ApplicationError) Error() string

Error ...

func (*ApplicationError) GetCause

func (err *ApplicationError) GetCause() error

GetCause ...

func (*ApplicationError) GetCode

func (err *ApplicationError) GetCode() int

GetCode ...

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

type Error interface {
	error
	GetCode() int
	GetCause() error
}

Error interface for wrapping application errors with error codes for faster error type switching.

func NewError added in v0.1.7

func NewError(code int, message string, cause error) Error

NewError creates a new error struct which implements the Error interface.

func NewErrorf added in v0.2.0

func NewErrorf(code int, cause error, format string, args ...interface{}) Error

NewErrorf is a wrapper to facilitate creating error messages with unstructured context data.

type ErrorData added in v0.2.2

type ErrorData interface {
	Error
	GetData() map[string]interface{}
}

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.

func NewErrorData added in v0.2.2

func NewErrorData(code int, message string, cause error, data map[string]interface{}) ErrorData

NewErrorData creates a new error which implements the ErrorData interface.

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

func NewLogger

func NewLogger(component string, tags ...string) ILogger

NewLogger ...

type KV added in v0.2.2

type KV map[string]interface{}

KV is an alias for map[string]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

type ProcessManager struct {
	Logger log.Logger
	// contains filtered or unexported fields
}

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.

Directories

Path Synopsis
connectors

Jump to

Keyboard shortcuts

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