Documentation
¶
Overview ¶
Package utilities provides a collection of small, focused helper functions and type shortcuts used across services, including validation, CLI/table printing, JWT, filesystem, network, and more.
Index ¶
- func AmAdmin() bool
- func ConvertToJSONMap(input any) (datatypes.JSONMap, error)
- func CopyIfNotNil[T any](src, dest *T)
- func CopyIfNotZero[T any](src T, dest *T)
- func DaemonAlreadyRunning(appName string) bool
- func DbDSN(cfg DbDSNConfig) string
- func DirCreateIfNotExists(dir string) error
- func ExtractJwtClaims(tokenString string, secretKey []byte) (map[string]interface{}, error)
- func ExtractJwtClaimsInto(tokenString string, secretKey []byte, out interface{}) error
- func FindDaemonProcessPID(appName string) (int, error)
- func FindDaemonProcessPIDWithArg(appName string, argName string) (int, error)
- func FindProcessPIDMAC(appName string) (int, error)
- func GenerateJWT(claims interface{}, duration time.Duration, secretKey []byte) (string, error)
- func GetMacAddressFromIp(ipAddress string) (string, error)
- func IsAlphaNumeric(s string) bool
- func IsBase64(s string) bool
- func IsCreditCard(s string) bool
- func IsEmail(s string) bool
- func IsFQDN(s string) bool
- func IsHexColor(s string) bool
- func IsHostname(s string) bool
- func IsIP(s string) bool
- func IsIPv4(s string) bool
- func IsIPv6(s string) bool
- func IsMAC(s string) bool
- func IsPhone(s string) bool
- func IsURL(s string) bool
- func IsUUID(s string) bool
- func LitterCheckErr[T any](out T, err error) T
- func Merge[K comparable, V any](a, b map[K]V) map[K]V
- func MergeInto[K comparable, V any](a, b map[K]V)
- func MimeTypeFromExtension(filename string) string
- func MustFindDaemonProcessPID(appName string) int
- func NilIfEmpty[T any](in []T) *[]T
- func NilIfZeroPtr[T comparable](in *T) *T
- func PrintAnySlice(input any) error
- func PrintMap(input any, headers ...string) error
- func PrintMapArray(input any) error
- func PrintSlice(input any) error
- func PrintSortedStructMap(obj any) error
- func PrintStringSlice(input any) error
- func PrintStringsTable(headers []string, rows [][]string) error
- func PrintStructMap(obj any) error
- func PrintStructTable(obj any) error
- func Ptr[T any](v T) *T
- func PtrCompare[T comparable](p1, p2 *T) bool
- func PtrVal[T any](p *T) T
- func PtrZeroNil[T any](v T) *T
- func SetStructFieldByName(ptr interface{}, fieldName string, value interface{}) error
- func StructFieldNames(s interface{}) []string
- func StructToStringMap(s interface{}) map[string]string
- func ToValuers[T driver.Valuer](in []T) []driver.Valuer
- func ValidateJWT(tokenString string, secretKey []byte) (*jwt.Token, error)
- func ZeroStructFieldByName(ptr interface{}, fieldName string) error
- type AnyChan
- type AnyMap
- type Anys
- type Callback
- type DbDSNConfig
- type ErrChan
- type Floats
- type Handler
- type IntMap
- type Ints
- type JSON
- type Mapper
- type Predicate
- type StrAny
- type StrChan
- type StrMap
- type Strs
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func AmAdmin ¶
func AmAdmin() bool
AmAdmin checks if the current user has administrative (root) privileges by verifying if the effective user ID is 0. Returns true if the user is root; otherwise, false.
func ConvertToJSONMap ¶
ConvertToJSONMap marshals the input value to JSON and unmarshals it into a datatypes.JSONMap. Returns an error if marshaling or unmarshaling fails.
func CopyIfNotNil ¶
func CopyIfNotNil[T any](src, dest *T)
CopyIfNotNil copies the value from the source pointer to the destination pointer only if both pointers are non-nil. It uses PtrVal to dereference the source pointer safely.
func CopyIfNotZero ¶
func CopyIfNotZero[T any](src T, dest *T)
CopyIfNotZero copies the value of src to dest if src is not the zero value of its type and dest is not nil. It uses PtrZeroNil to determine if src is non-zero.
func DaemonAlreadyRunning ¶
DaemonAlreadyRunning checks if a daemon process with the given appName is already running on the system. Returns true if the process exists, otherwise false.
func DbDSN ¶
func DbDSN(cfg DbDSNConfig) string
DbDSN generates a database connection string (DSN) based on the provided configuration structure, including server, port, database name, user, password, SSL mode, and timezone. The SSL mode defaults to "enable" or "disable" based on the cfg.SSLMode flag.
func DirCreateIfNotExists ¶
DirCreateIfNotExists checks if a directory exists and creates it if it does not. It returns an error if there is an issue checking the directory or creating it.
func ExtractJwtClaims ¶
ExtractJwtClaims extracts claims from a JWT token string using the provided secret key. It returns the claims as a map if the token is valid, or an error if validation or extraction fails.
func ExtractJwtClaimsInto ¶
ExtractJwtClaimsInto extracts claims from a JWT token string, validates it using the provided secretKey, and maps the claims into the provided output struct. Returns an error if validation, marshalling, or unmarshalling fails.
func FindDaemonProcessPID ¶
FindDaemonProcessPID searches for the PID of a running daemon process matching the given appName. It checks the local process table on Linux and utilizes platform-specific logic for macOS. Returns the PID of the found process or an error if the process is not found or on failure.
func FindDaemonProcessPIDWithArg ¶
FindDaemonProcessPIDWithArg searches for the PID of a running daemon process matching the given appName and given argument. It checks the local process table on Linux and utilizes platform-specific logic for macOS. Returns the PID of the found process or an error if the process is not found or on failure.
func FindProcessPIDMAC ¶
FindProcessPIDMAC searches for a specific process by name on macOS and returns its PID. It filters processes using the `ps` command, ignoring the caller's own PID, and matches the process name and argument. Returns the PID of the found process or an error if the process is not found.
func GenerateJWT ¶
GenerateJWT creates a JSON Web Token (JWT) with the specified claims and expiration duration using the provided secret key. It embeds issued-at (iat) and expiration (exp) fields into the claims automatically. Returns the signed JWT string or an error if the operation fails.
func GetMacAddressFromIp ¶
GetMacAddressFromIp retrieves the MAC address associated with the given IP address by parsing the ARP table. Returns the MAC address as a string if found, otherwise returns an error if the IP is invalid or no matching MAC address is found.
revive:disable-next-line var-naming // keep exported name for API compatibility
func IsAlphaNumeric ¶
IsAlphaNumeric reports whether s is composed only of ASCII letters and digits.
func IsBase64 ¶
IsBase64 checks if s is valid base64 without requiring specific padding, ignoring whitespace.
func IsCreditCard ¶
IsCreditCard performs a format check (digits with optional separators) and Luhn checksum.
func IsEmail ¶
IsEmail returns true if s is a valid email address per net/mail parsing. It accepts common real-world emails but does not guarantee full RFC compliance.
func IsHexColor ¶
IsHexColor returns true if s represents a hex color in one of the supported forms: #RGB, #RRGGBB, #RGBA, #RRGGBBAA (with or without the leading #).
func IsHostname ¶
IsHostname allows single-label hostnames (non-FQDN), same label rules as FQDN labels.
func IsPhone ¶
IsPhone returns true for basic phone numbers: E.164 (+8..15 digits) or national digits (7..15).
func LitterCheckErr ¶
LitterCheckErr logs an error if present, outputs a debug dump of the provided value using the litter library, and then returns the value.
func Merge ¶
func Merge[K comparable, V any](a, b map[K]V) map[K]V
Merge returns a new map that contains all key-value pairs from a and b. If a key exists in both, the value from b takes precedence.
func MergeInto ¶
func MergeInto[K comparable, V any](a, b map[K]V)
MergeInto merges all key-value pairs from b into a in place. If a key exists in both, the value from b takes precedence.
func MimeTypeFromExtension ¶
MimeTypeFromExtension returns the MIME type based on the file extension. Defaults to "application/octet-stream" if unknown.
func MustFindDaemonProcessPID ¶
MustFindDaemonProcessPID retrieves the PID of a running daemon process for the given appName or returns 0 if not found. It panics if an error occurs during the search, enforcing that the process must be found.
func NilIfEmpty ¶
func NilIfEmpty[T any](in []T) *[]T
NilIfEmpty takes a slice of any type and returns nil if the slice is empty, or a pointer to the slice otherwise.
func NilIfZeroPtr ¶
func NilIfZeroPtr[T comparable](in *T) *T
NilIfZeroPtr returns nil if the input pointer is non-nil and the value it points to is zero; otherwise, it returns the input pointer unchanged.
func PrintAnySlice ¶
PrintAnySlice prints a one-column table of a []any or utilities.Anys with row numbers. Values are stringified using fmt.Sprintf("%v", v).
func PrintMap ¶
PrintMap prints a two-column table for any map type. It accepts maps with any key and value types (including pointers to maps). Keys are ordered by their string representation for stable output. Optional headers can be provided: headers[0] for the key column, headers[1] for the value column.
func PrintMapArray ¶
PrintMapArray takes an input of type any, attempts to interpret it as a slice of maps with string keys and values of any type, and prints it as a formatted table. Returns an error if the input is of unsupported type or is an empty slice.
func PrintSlice ¶
PrintSlice prints any slice or array (of basic types or structs) as a two-column table of index and value. For struct elements, it will use fmt.Sprintf("%v", elem). For slices of structs requiring field breakdown, use PrintStructTable instead.
func PrintSortedStructMap ¶
PrintSortedStructMap takes any map as input and prints its values in a tabular format by treating them as structs. It behaves like PrintStructMap but sorts the output by the map key before printing.
func PrintStringSlice ¶
PrintStringSlice prints a one-column table of a []string or utilities.Strs with row numbers. Returns an error if the input slice is empty or of unsupported type.
func PrintStringsTable ¶
PrintStringsTable prints a table for a [][]string with optional headers. If headers is nil or empty, rows are printed without a header. Returns an error if rows is empty or contains inconsistent column counts when headers are provided.
func PrintStructMap ¶
PrintStructMap takes any map as input and prints its values in a tabular format by treating them as structs. Returns an error if the input is not a map or if any issues occur during processing.
func PrintStructTable ¶
PrintStructTable prints a tabular representation of a struct or a slice/array of structs to the standard output. It requires the input to be a struct, or a slice/array containing structs or pointers to structs. Returns an error if input is invalid or processing fails.
func PtrCompare ¶
func PtrCompare[T comparable](p1, p2 *T) bool
PtrCompare compares two pointers of any comparable type and returns true if both are nil or if they point to equal values. Returns false if one pointer is nil or they point to unequal values.
func PtrVal ¶
func PtrVal[T any](p *T) T
PtrVal dereferences a pointer and returns its value; if the pointer is nil, it returns the zero value of the type.
func PtrZeroNil ¶
func PtrZeroNil[T any](v T) *T
PtrZeroNil returns a pointer to the input value if it is non-zero; otherwise, it returns nil. It uses reflection to determine whether the input value equals its type's zero value.
func SetStructFieldByName ¶
SetStructFieldByName sets the value of a field in a struct identified by its name. The function expects a pointer to a struct, the field name as a string, and the value to set. It returns an error if the pointer is not to a struct, the field does not exist or cannot be set, or if there is a type mismatch between the field and the value.
func StructFieldNames ¶
func StructFieldNames(s interface{}) []string
StructFieldNames returns a slice of field names for a given struct or a pointer to a struct. If the input is not a struct or a pointer to a struct, it returns an empty slice.
func StructToStringMap ¶
StructToStringMap converts a struct into a map with field names as keys and field values as strings. It supports nested pointers by dereferencing them and handles nil pointers, assigning "<nil>" as their value. The input must be a struct or a pointer to a struct; otherwise, behavior is undefined.
func ToValuers ¶
ToValuers converts a slice of types implementing driver.Valuer into a slice of driver.Valuer. Useful for building slices for parameterized queries (e.g., WHERE IN (...)).
func ValidateJWT ¶
ValidateJWT validates a JWT using the provided token string and secret key, returning the parsed token if successful or an error if validation fails.
func ZeroStructFieldByName ¶
ZeroStructFieldByName sets the specified field of a struct to its zero value. The `ptr` parameter must be a pointer to a struct, and `fieldName` is the name of the field to reset. Returns an error if the field does not exist, cannot be set, or `ptr` is not a pointer to a struct.
Types ¶
type AnyMap ¶
AnyMap is a shorthand for a map of string keys to arbitrary values (alias similar to StrAny).
type DbDSNConfig ¶
type DbDSNConfig struct {
Server string
Port int
Name string
User string
Password string
SSLMode bool
TimeZone string
}
DbDSNConfig contains the fields used to construct a database DSN string. Fields map to host, port, database name, user, password, SSL mode and timezone.
type Handler ¶
type Handler func() error
Handler is a function that returns an error; handy for composing small tasks.