helpers

package
v0.0.1-20260118-131225... Latest Latest
Warning

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

Go to latest
Published: Jan 18, 2026 License: Apache-2.0 Imports: 28 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AuthorizationHeaderFromNatsMsg

func AuthorizationHeaderFromNatsMsg(msg *nats.Msg) string

AuthorizationHeaderFromNatsMsg extracts the authorization header from NATS message. It returns the authorization token for authentication purposes.

func ConstructDiscoveryURL

func ConstructDiscoveryURL(URL string, serviceName string) string

ConstructDiscoveryURL builds a service discovery URL by combining base URL and service name. It returns a properly formatted URL for service discovery.

func ConstructURLWithParams

func ConstructURLWithParams(baseURL string, params map[string]any) (string, error)

ConstructURLWithParams builds a URL by appending query parameters to a base URL. It handles various parameter types and properly encodes them.

func ConvertToTimeDuration

func ConvertToTimeDuration(value int, unit string) time.Duration

ConvertToTimeDuration converts a value to time.Duration based on the specified unit. Supported units: "seconds", "minutes", "milliseconds", "hours".

func CorrelationIDFromNatsMsg

func CorrelationIDFromNatsMsg(msg *nats.Msg) string

CorrelationIDFromNatsMsg extracts the correlation ID from NATS message headers. It returns the correlation ID used for distributed tracing.

func CreateLogDirectory

func CreateLogDirectory() string

CreateLogDirectory creates the log directory and file for the service. It ensures proper permissions and returns the log file path.

func DetectInputType

func DetectInputType(input string) string

DetectInputType analyzes input to determine if it's a file path or JSON string. It returns "file", "json", or empty string for unknown types.

func ErrorHeadeFromNatsMsg

func ErrorHeadeFromNatsMsg(msg *nats.Msg) string

ErrorHeadeFromNatsMsg extracts the error header from NATS message. It returns error information passed through message headers.

func ExtractBearerToken

func ExtractBearerToken(authHeader string) string

ExtractBearerToken extracts the bearer token from the Authorization header

func FetchErrorStack

func FetchErrorStack(errs []error) string

FetchErrorStack joins multiple errors into a single error string. It returns an empty string if no errors are provided or all are nil.

func FetchErrorStrings

func FetchErrorStrings(errs []error) []string

FetchErrorStrings extracts error messages from a slice of errors. It filters out nil errors and returns only the error message strings.

func FetchHTTPStatusCode

func FetchHTTPStatusCode(response types.ResponseErrorType) int

FetchHTTPStatusCode maps response error types to their corresponding HTTP status codes. It returns 500 (Internal Server Error) for unknown response types.

func FormatRequestAndCorrelationIDs

func FormatRequestAndCorrelationIDs(requestId, correlationId string) string

FormatRequestAndCorrelationIDs formats the request ID and correlation ID into a human-readable string.

func GenerateReasonCode

func GenerateReasonCode(namespace string, code int) string

GenerateReasonCode generates a namespaced reason code as a string

func GetAvailablePort

func GetAvailablePort(protocol types.Protocol, preferredPort string) (string, error)

GetAvailablePort finds an available port for the given protocol (TCP or UDP).

func GetCountryInfoForCode

func GetCountryInfoForCode(countryCode int) (regionCode string, countryName string)

GetCountryInfoForCode returns both region code and country name for a dialing code. It provides human-readable country information for phone number display.

func GetDefaultLanguageTag

func GetDefaultLanguageTag() types.LanguageTag

GetDefaultLanguageTag returns the default language tag

func GetDefaultPort

func GetDefaultPort() string

GetDefaultPort returns the default port if DefaultAppPort is set in environment variables

func GetEnvironment

func GetEnvironment() string

GetEnvironment retrieves the current environment setting from various sources. It checks environment variables and viper configuration in order of priority.

func GetEnvironmentSlug

func GetEnvironmentSlug(environment string) string

GetEnvironmentSlug normalizes environment names to standard slugs. It maps various environment name variations to consistent short forms.

func GetGoROOT

func GetGoROOT() string

GetGoROOT returns the Go root directory

func GetHealthyMessageFor

func GetHealthyMessageFor(dependency string) string

GetHealthyMessageFor returns the healthy message for the given dependency

func GetIsLogRotationEnabled

func GetIsLogRotationEnabled() bool

GetIsLogRotationEnabled checks if log rotation is enabled via environment variables. It parses the LOG_ROTATION_ENABLED environment variable as a boolean.

func GetIsOpenSearchEnabled

func GetIsOpenSearchEnabled() bool

GetIsOpenSearchEnabled checks if OpenSearch logging is enabled via environment variable.

func GetIssuerFromConfig

func GetIssuerFromConfig() string

GetIssuerFromConfig retrieves the JWT issuer from configuration. It returns the issuer identifier used for token validation.

func GetMaxConns

func GetMaxConns(maxConn int) int

GetMaxConns returns the default value for MaxConns for postgres or sql.

func GetOpenSearchAddresses

func GetOpenSearchAddresses() []string

GetOpenSearchAddresses returns a list of OpenSearch node addresses.

func GetOpenSearchIndexName

func GetOpenSearchIndexName() string

GetOpenSearchIndexName returns the index name for logs.

func GetOpenSearchPassword

func GetOpenSearchPassword() string

GetOpenSearchPassword returns the password for authentication.

func GetOpenSearchUsername

func GetOpenSearchUsername() string

GetOpenSearchUsername returns the username for authentication.

func GetRegionForCountryCode

func GetRegionForCountryCode(countryCode int) string

GetRegionForCountryCode returns the primary region code for a given country dialing code. Note: Some country codes map to multiple regions (e.g., +1 for US, CA, etc.).

func GetServiceName

func GetServiceName() string

GetServiceName returns the service name from the app config or config files

func HostFromOrigin

func HostFromOrigin(origin string) string

HostFromOrigin extracts the host from an Origin header, handling ports and URL parsing.

func IPHeaderFromNatsMsg

func IPHeaderFromNatsMsg(msg *nats.Msg) string

IPHeaderFromNatsMsg extracts the IP address header from NATS message. It returns the client IP address for logging and security purposes.

func IsEmpty

func IsEmpty[T any](value T) bool

IsEmpty checks if the given interface value represents an empty or zero value. It supports custom EmptyCheck interface and handles all Go types recursively.

func IsFoundInSlice

func IsFoundInSlice[T []string | []*string](key string, slice T) bool

IsFoundInSlice checks if the given key is found in the slice IsFoundInSlice checks if a key exists in a slice of strings or a slice of string pointers, ignoring case.

func IsLocalhostHost

func IsLocalhostHost(host string) bool

IsLocalhostHost checks if the host is localhost, 127.0.0.1, or ::1.

func IsProdEnvironment

func IsProdEnvironment() bool

IsProdEnvironment checks if the current environment is production. It returns true for "prod" or "production" environment values.

func IsSuccess

func IsSuccess(status types.Status) bool

IsSuccess returns true if the given status is equal to constant.Success or constant.Completed

func IsURL

func IsURL(s string) bool

IsURL checks if the given string starts with http:// or https://. It performs a simple prefix check to identify URLs.

func JoinErrors

func JoinErrors(errs []error) error

JoinErrors combines multiple errors into a single error using errors.Join. It returns nil if no errors are provided or all errors are nil.

func MatchesAny

func MatchesAny(s string, patterns ...string) bool

MatchesAny checks if the string s contains any of the provided patterns. It performs substring matching using strings.Contains for each pattern.

func MessageIDFromNatsMsg

func MessageIDFromNatsMsg(msg *nats.Msg) string

MessageIDFromNatsMsg extracts the message ID from NATS message headers. It returns the unique message identifier for idempotency handling.

func MustGetEnv

func MustGetEnv(key string) string

MustGetEnv retrieves a required environment variable or exits the program. If the variable is not set or empty, it logs a fatal error and exits with code 1.

func NewBundle

func NewBundle(language types.LanguageTag) *i18n.Bundle

NewBundle creates a new i18n.Bundle

func NormalizePrecision

func NormalizePrecision(val float64, digits int) float64

NormalizePrecision rounds a float64 value to the specified number of decimal places. It uses math.Pow10 and math.Round for precise decimal rounding.

func ParseLanguageTag

func ParseLanguageTag(tagString string) types.LanguageTag

ParseLanguageTag parses a string into a language.Tag and returns a LanguageTag

func ParsePhoneNumber

func ParsePhoneNumber(rawNumber, defaultRegion string) (*structures.PhoneNumberInfo, error)

ParsePhoneNumber parses and validates a phone number string using libphonenumber. defaultRegion is a two-letter ISO country code used for numbers without country codes. It returns detailed phone number information including validation status.

func Printf

func Printf(mode types.LogMode, format string, args ...interface{})

Printf prints a formatted colored log message with timestamp and log level. It exits the program with code 1 if the mode is FATAL.

func Println

func Println(mode types.LogMode, args ...any)

Println prints a colored log message with timestamp and log level. It exits the program with code 1 if the mode is FATAL.

func RecoverException

func RecoverException(panic any)

RecoverException recovers from panics and logs the stack trace

func ReplacePlaceholders

func ReplacePlaceholders(src string, params map[string]any) (string, error)

replacePlaceholders replaces {{.key}} in src with values from params.

func SameSiteName

func SameSiteName(s http.SameSite) string

SameSiteName converts http.SameSite to a human-readable string.

func SplitAny

func SplitAny(s string, delims ...string) []string

SplitAny splits a string into parts using any of the specified separators. It returns a slice of non-empty strings after removing leading/trailing whitespace.

func TailCallerEncoder

func TailCallerEncoder(n int) zapcore.CallerEncoder

TailCallerEncoder creates a custom zap caller encoder that shows the last n path segments. It provides more readable file paths in log output by trimming deep directory structures.

func ToNetIPAddr

func ToNetIPAddr(remoteAddress string) (*netip.Addr, error)

ToNetIPAddr converts a remote address string to a netip.Addr. It handles addresses with or without ports and validates IP format.

func UserHomeDir

func UserHomeDir() string

UserHomeDir returns the user's home directory

func Valid

func Valid() *bool

Valid returns a pointer to true, commonly used for boolean pointer fields. It provides a convenient way to set boolean pointer values.

func ValidateURL

func ValidateURL(requestURL string) error

ValidateURL checks if the provided string is a valid URL. It uses url.ParseRequestURI for validation and returns an error if invalid.

Types

This section is empty.

Jump to

Keyboard shortcuts

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