commons

package
v2.4.0 Latest Latest
Warning

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

Go to latest
Published: Oct 30, 2025 License: Apache-2.0 Imports: 33 Imported by: 5

Documentation

Index

Constants

This section is empty.

Variables

View Source
var CustomContextKey = customContextKey("custom_context")

Functions

func AccountingRoutesInternalKey

func AccountingRoutesInternalKey(organizationID, ledgerID, key uuid.UUID) string

AccountingRoutesInternalKey returns a key with the following format to be used on redis cluster: "accounting_routes:{organizationID:ledgerID:key}"

func AttributesFromContext added in v2.3.0

func AttributesFromContext(ctx context.Context) []attribute.KeyValue

AttributesFromContext returns a shallow copy of the AttrBag slice, safe to reuse by processors.

func BalanceInternalKey

func BalanceInternalKey(organizationID, ledgerID, key string) string

BalanceInternalKey returns a key with the following format to be used on redis cluster: "balance:{organizationID:ledgerID:key}"

func CamelToSnakeCase

func CamelToSnakeCase(str string) string

CamelToSnakeCase converts a given camelCase string to snake_case format.

func CheckMetadataKeyAndValueLength

func CheckMetadataKeyAndValueLength(limit int, metadata map[string]any) error

CheckMetadataKeyAndValueLength check the length of key and value to a limit pass by on field limit

func Contains

func Contains[T comparable](slice []T, item T) bool

Contains checks if an item is in a slice. This function uses type parameters to work with any slice type.

func ContextWithHeaderID

func ContextWithHeaderID(ctx context.Context, headerID string) context.Context

ContextWithHeaderID returns a context within a HeaderID in "headerID" value.

func ContextWithLogger

func ContextWithLogger(ctx context.Context, logger log.Logger) context.Context

ContextWithLogger returns a context within a Logger in "logger" value.

func ContextWithMetricFactory

func ContextWithMetricFactory(ctx context.Context, metricFactory *metrics.MetricsFactory) context.Context

ContextWithMetricFactory returns a context within a MetricsFactory in "metricFactory" value.

func ContextWithSpanAttributes added in v2.3.0

func ContextWithSpanAttributes(ctx context.Context, kv ...attribute.KeyValue) context.Context

ContextWithSpanAttributes appends one or more attributes to the request's AttrBag. Call this once at the ingress (HTTP/gRPC middleware) and avoid per-layer duplication. Example keys: tenant.id, enduser.id, request.route, region, plan.

func ContextWithTracer

func ContextWithTracer(ctx context.Context, tracer trace.Tracer) context.Context

ContextWithTracer returns a context within a trace.Tracer in "tracer" value.

func EnsureConfigFromEnvVars

func EnsureConfigFromEnvVars(s any) any

EnsureConfigFromEnvVars ensures that an interface will be settled using SetConfigFromEnvVars anyway.

func GenerateUUIDv7

func GenerateUUIDv7() uuid.UUID

GenerateUUIDv7 generate a new uuid v7 using google/uuid package and return it. If an error occurs, it will return the error.

func GenericInternalKey

func GenericInternalKey(name, organizationID, ledgerID, key string) string

GenericInternalKey returns a key with the following format to be used on redis cluster: "name:{organizationID:ledgerID:key}"

func GetCPUUsage

func GetCPUUsage(ctx context.Context, cpuGauge metric.Int64Gauge)

GetCPUUsage get the current CPU usage

func GetMapNumKinds

func GetMapNumKinds() map[reflect.Kind]bool

GetMapNumKinds get the map of numeric kinds to use in validations and conversions.

The numeric kinds are: - int - int8 - int16 - int32 - int64 - float32 - float64

func GetMemUsage

func GetMemUsage(ctx context.Context, memGauge metric.Int64Gauge)

GetMemUsage get the current memory usage

func GetenvBoolOrDefault

func GetenvBoolOrDefault(key string, defaultValue bool) bool

GetenvBoolOrDefault returns the value of os.Getenv(key string) value as bool or defaultValue if error Is the environment variable (key) is not defined, it returns the given defaultValue If the environment variable (key) is not a valid bool format, it returns the given defaultValue If any error occurring during bool parse, it returns the given defaultValue.

func GetenvIntOrDefault

func GetenvIntOrDefault(key string, defaultValue int64) int64

GetenvIntOrDefault returns the value of os.Getenv(key string) value as int or defaultValue if error If the environment variable (key) is not defined, it returns the given defaultValue If the environment variable (key) is not a valid int format, it returns the given defaultValue If any error occurring during int parse, it returns the given defaultValue.

func GetenvOrDefault

func GetenvOrDefault(key string, defaultValue string) string

GetenvOrDefault encapsulate built-in os.Getenv behavior but if key is not present it returns the defaultValue.

func HashSHA256

func HashSHA256(input string) string

HashSHA256 generate a hash sha-256 to create idempotency on redis

func IdempotencyInternalKey

func IdempotencyInternalKey(organizationID, ledgerID uuid.UUID, key string) string

IdempotencyInternalKey returns a key with the following format to be used on redis cluster: "idempotency:{organizationID:ledgerID:key}"

func IsDateRangeWithinMonthLimit

func IsDateRangeWithinMonthLimit(initial, final time.Time, limit int) bool

IsDateRangeWithinMonthLimit checks if the date range is within the permitted range in months.

func IsInitialDateBeforeFinalDate

func IsInitialDateBeforeFinalDate(initial, final time.Time) bool

IsInitialDateBeforeFinalDate checks if the initial date is before or equal to the final date.

func IsNilOrEmpty

func IsNilOrEmpty(s *string) bool

IsNilOrEmpty returns a boolean indicating if a *string is nil or empty. It's use TrimSpace so, a string " " and "" and "null" and "nil" will be considered empty

func IsUUID

func IsUUID(s string) bool

IsUUID Validate if the string pass through is an uuid

func IsValidDate

func IsValidDate(date string) bool

IsValidDate checks if the provided date string is in the format "YYYY-MM-DD".

func MergeMaps

func MergeMaps(source, target map[string]any) map[string]any

MergeMaps Following the JSON Merge Patch

func NewHeaderIDFromContext deprecated

func NewHeaderIDFromContext(ctx context.Context) string

Deprecated: use NewTrackingFromContext instead

NewHeaderIDFromContext returns a HeaderID from the context.

func NewLoggerFromContext

func NewLoggerFromContext(ctx context.Context) log.Logger

NewLoggerFromContext extract the Logger from "logger" value inside context

func NewMetricFactoryFromContext deprecated

func NewMetricFactoryFromContext(ctx context.Context) *metrics.MetricsFactory

Deprecated: use NewTrackingFromContext instead

NewMetricFactoryFromContext returns a new metric factory from the context.

func NewTracerFromContext deprecated

func NewTracerFromContext(ctx context.Context) trace.Tracer

Deprecated: use NewTrackingFromContext instead

NewTracerFromContext returns a new tracer from the context.

func NewTrackingFromContext added in v2.3.0

func NewTrackingFromContext(ctx context.Context) (log.Logger, trace.Tracer, string, *metrics.MetricsFactory)

NewTrackingFromContext extracts tracking components from context with intelligent fallback. It follows the fail-safe principle: preserve valid components, provide sensible defaults for invalid ones.

func NormalizeDate

func NormalizeDate(date time.Time, days *int) string

NormalizeDate normalizes a date adding or subtracting days without time to make it match the query requirements and string format.

func NormalizeDateTime

func NormalizeDateTime(date time.Time, days *int, endOfDay bool) string

NormalizeDateTime normalizes a date adding or subtracting days with time to make it match the query requirements and string format.

func RegexIgnoreAccents

func RegexIgnoreAccents(regex string) string

RegexIgnoreAccents receives a regex, then, for each char it's adds the accents variations to expression Ex: Given "a" -> "aáàãâ" Ex: Given "c" -> "ç"

func RemoveAccents

func RemoveAccents(word string) (string, error)

RemoveAccents removes accents of a given word and returns it

func RemoveChars

func RemoveChars(str string, chars map[string]bool) string

RemoveChars from a string

func RemoveSpaces

func RemoveSpaces(word string) string

RemoveSpaces removes spaces of a given word and returns it

func ReplaceAttributes added in v2.3.0

func ReplaceAttributes(ctx context.Context, kv ...attribute.KeyValue) context.Context

ReplaceAttributes resets the current AttrBag with a new set (rarely needed; provided for completeness).

func ReplaceUUIDWithPlaceholder

func ReplaceUUIDWithPlaceholder(path string) string

ReplaceUUIDWithPlaceholder replaces UUIDs with a placeholder in a given path string.

func Reverse

func Reverse[T any](s []T) []T

Reverse reverses a slice of any type.

func SafeInt64ToInt

func SafeInt64ToInt(val int64) int

SafeInt64ToInt safely converts int64 to int

func SafeIntToUint32 added in v2.4.0

func SafeIntToUint32(value int, defaultVal uint32, logger log.Logger, fieldName string) uint32

SafeIntToUint32 safely converts int to uint32 with overflow protection. Returns the converted value if in valid range [0, MaxUint32], otherwise returns defaultVal. This prevents G115 (CWE-190) integer overflow vulnerabilities.

func SafeIntToUint64

func SafeIntToUint64(val int) uint64

SafeIntToUint64 safe mode to converter int to uint64

func SafeUintToInt

func SafeUintToInt(val uint) int

SafeUintToInt converts a uint to int64 safely by capping values at math.MaxInt64.

func SetConfigFromEnvVars

func SetConfigFromEnvVars(s any) error

SetConfigFromEnvVars builds a struct by setting it fields values using the "var" tag Constraints: s any - must be an initialized pointer Supported types: String, Boolean, Int, Int8, Int16, Int32 and Int64.

func StringToInt

func StringToInt(s string) int

StringToInt func that convert string to int.

func StructToJSONString

func StructToJSONString(s any) (string, error)

StructToJSONString convert a struct to json string

func TransactionInternalKey

func TransactionInternalKey(organizationID, ledgerID uuid.UUID, key string) string

TransactionInternalKey returns a key with the following format to be used on redis cluster: "transaction:{organizationID:ledgerID:key}"

func UUIDsToStrings added in v2.3.0

func UUIDsToStrings(uuids []uuid.UUID) []string

UUIDsToStrings converts a slice of UUIDs to a slice of strings. It's optimized to minimize allocations and iterations.

func ValidateAccountType

func ValidateAccountType(t string) error

ValidateAccountType validate type values of accounts

func ValidateBusinessError

func ValidateBusinessError(err error, entityType string, args ...any) error

ValidateBusinessError validates the error and returns the appropriate business error code, title, and message.

Parameters:

Returns:

  • error: The appropriate business error with code, title, and message.

func ValidateCode

func ValidateCode(code string) error

func ValidateCountryAddress

func ValidateCountryAddress(country string) error

ValidateCountryAddress validate if country in object address contains in countries list using ISO 3166-1 alpha-2

func ValidateCurrency

func ValidateCurrency(code string) error

ValidateCurrency validate if code contains in currencies list using ISO 4217

func ValidateServerAddress

func ValidateServerAddress(value string) string

ValidateServerAddress checks if the value matches the pattern <some-address>:<some-port> and returns the value if it does.

func ValidateType

func ValidateType(t string) error

ValidateType validate type values of currencies

func WithTimeout added in v2.4.0

func WithTimeout(parent context.Context, timeout time.Duration) (context.Context, context.CancelFunc)

WithTimeout creates a context with the specified timeout, but respects any existing deadline in the parent context. If the parent context has a deadline that would expire sooner than the requested timeout, the parent's deadline is used instead.

This prevents the common mistake of extending a context's deadline beyond what the caller intended.

Example:

// Parent has 5s deadline, we request 10s -> gets 5s
ctx, cancel := commons.WithTimeout(parentCtx, 10*time.Second)
defer cancel()

Types

type App

type App interface {
	Run(launcher *Launcher) error
}

App represents an application that will run as a deployable component. It's an entrypoint at main.go. RedisRepository provides an interface for redis.

type CustomContextKeyValue

type CustomContextKeyValue struct {
	HeaderID      string
	Tracer        trace.Tracer
	Logger        log.Logger
	MetricFactory *metrics.MetricsFactory

	// AttrBag holds request-wide attributes to be applied to every span.
	// Keep low/medium cardinality attributes here (tenant.id, plan, region, request_id, route).
	AttrBag []attribute.KeyValue
}

CustomContextKeyValue holds all request-scoped facilities we attach to context.

type Launcher

type Launcher struct {
	Logger log.Logger

	Verbose bool
	// contains filtered or unexported fields
}

Launcher manages apps.

func NewLauncher

func NewLauncher(opts ...LauncherOption) *Launcher

NewLauncher create an instance of Launch.

func (*Launcher) Add

func (l *Launcher) Add(appName string, a App) *Launcher

Add runs an application in a goroutine.

func (*Launcher) Run

func (l *Launcher) Run()

Run every application registered before with Run method.

type LauncherOption

type LauncherOption func(l *Launcher)

LauncherOption defines a function option for Launcher.

func RunApp

func RunApp(name string, app App) LauncherOption

RunApp start all process registered before to the launcher.

func WithLogger

func WithLogger(logger log.Logger) LauncherOption

WithLogger adds a log.Logger component to launcher.

type LocalEnvConfig

type LocalEnvConfig struct {
	Initialized bool
}

LocalEnvConfig is used to automatically call the InitLocalEnvConfig method using Dependency Injection So, if a func parameter or a struct field depends on LocalEnvConfig, when DI starts, it will call InitLocalEnvConfig as the LocalEnvConfig provider.

func InitLocalEnvConfig

func InitLocalEnvConfig() *LocalEnvConfig

InitLocalEnvConfig load a .env file to set up local environment vars It's called once per application process.

type RateLimitError added in v2.4.0

type RateLimitError struct {
	EntityType string `json:"entityType,omitempty"`
	Title      string `json:"title,omitempty"`
	Message    string `json:"message,omitempty"`
	Code       string `json:"code,omitempty"`
	Err        error  `json:"err,omitempty"`
}

RateLimitError records an error indicating an entity was not found in any case that caused it.

func ValidateRateLimitError added in v2.4.0

func ValidateRateLimitError(err error, entityType string) *RateLimitError

func (RateLimitError) Error added in v2.4.0

func (e RateLimitError) Error() string

Error implements the error interface.

func (RateLimitError) Unwrap added in v2.4.0

func (e RateLimitError) Unwrap() error

Unwrap implements the error interface introduced in Go 1.13 to unwrap the internal error.

type Response

type Response struct {
	EntityType string `json:"entityType,omitempty"`
	Title      string `json:"title,omitempty"`
	Message    string `json:"message,omitempty"`
	Code       string `json:"code,omitempty"`
	Err        error  `json:"err,omitempty"`
}

Response represents a business error with code, title, and message.

func (Response) Error

func (e Response) Error() string

type Syscmd

type Syscmd struct{}

func (*Syscmd) ExecCmd

func (r *Syscmd) ExecCmd(name string, arg ...string) ([]byte, error)

type SyscmdI

type SyscmdI interface {
	ExecCmd(name string, arg ...string) ([]byte, error)
}

type TrackingComponents added in v2.3.0

type TrackingComponents struct {
	Logger        log.Logger
	Tracer        trace.Tracer
	HeaderID      string
	MetricFactory *metrics.MetricsFactory
}

TrackingComponents represents the complete set of tracking components extracted from context. This struct encapsulates all telemetry-related dependencies in a single, cohesive unit.

Directories

Path Synopsis
Package log is a generated GoMock package.
Package log is a generated GoMock package.
net

Jump to

Keyboard shortcuts

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