utl

package module
v1.3.6 Latest Latest
Warning

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

Go to latest
Published: Mar 18, 2025 License: MIT Imports: 22 Imported by: 4

README

utl

Package utl is a library of very common housekeeping functions. Many of these functions seem very simple and almost unnecessary, but they make the calling code much easier to read and digest.

Releases

See releases

Documentation

Overview

Package utl is a library of very common housekeeping functions. Many of these functions seem very simple and almost unnecessary, but they can make code much easier to read and digest.

Index

Constants

This section is empty.

Variables

View Source
var (
	Red = color.FgLightRed.Render
	Blu = color.FgLightBlue.Render
	Gre = color.FgGreen.Render
	Yel = color.FgYellow.Render
	Whi = color.FgWhite.Render
	Cya = color.FgCyan.Render
	Mag = color.FgLightMagenta.Render
	Gra = color.FgDarkGray.Render

	Red2 = color.FgRed.Render
	Blu2 = color.FgBlue.Render
	Gre2 = color.FgLightGreen.Render
	Yel2 = color.FgLightYellow.Render
	Whi2 = color.FgLightWhite.Render
	Cya2 = color.FgLightCyan.Render
	Mag2 = color.FgMagenta.Render
)

Functions

func Bool added in v1.2.0

func Bool(obj interface{}) bool

Returns the boolean value of the object, supporting bool, string, and int types. This is a controlled assertion to safely extract and convert the value to a boolean. For strings, it parses common true/false values (e.g., "true", "1"). Returns false for unsupported types, invalid strings, or nil input.

func BytesToYamlObject

func BytesToYamlObject(yamlBytes []byte) (yamlObject interface{}, err error)

Convert byte slice to YAML interface object

func ConvertDateFormat

func ConvertDateFormat(dateString, srcFormat, dstFormat string) (string, error)

Converts dateString from source format to destination format. Returns date string in destination format and an error if the conversion fails.

func DateStringToEpocInt64

func DateStringToEpocInt64(dateString, dateFormat string) (int64, error)

Convert dateString, given in dateFormat, to Unix Epoc seconds int64

func Die

func Die(format string, args ...interface{})

Same as regular Printf function but always exits, with a return code of 1

func EpocInt64ToTime

func EpocInt64ToTime(epocInt int64) time.Time

Converts an epoch timestamp in int64 format to a time.Time object.

func EpocStringToTime

func EpocStringToTime(epocString string) (time.Time, error)

Converts an epoch timestamp in string format to a time.Time object. Returns a time.Time object and an error if the conversion fails.

func FileAge

func FileAge(filePath string) int64

Returns the age of the given filePath in seconds as int64. If the file does not exist or is empty, it returns -1.

func FileExist

func FileExist(filePath string) (e bool)

Returns true if given filePath exists. False otherwise.

func FileModTime

func FileModTime(filePath string) int

Returns given filePath modified time in Unix epoch int

func FileNotExist

func FileNotExist(filePath string) (e bool)

Returns true is given filePath does not exist. False otherwise.

func FileSize

func FileSize(filePath string) int64

Returns size of given filePath as int64

func FileUsable

func FileUsable(filePath string) bool

Returns true if filepath exists and has some content. False otherwise.

func FirstN

func FirstN(s string, n int) string

Return first N chars of string n

func GenerateRandomString added in v1.2.0

func GenerateRandomString(length int) string

Generates a random string of the given length

func GetDateInDays

func GetDateInDays(days string) time.Time

Print yyyy-mm-dd date for given number of +/- days in future or past

func GetDaysBetween

func GetDaysBetween(date1, date2 string) int64

Return number of days between 2 dates

func GetDaysSinceOrTo

func GetDaysSinceOrTo(date1 string) int64

Calculate and return number of +/- days from NOW to date given Note: Calculations are all in UTC time. And it takes leap year into account.

func GetType

func GetType(v interface{}) string

func Int2StrWithCommas added in v1.2.0

func Int2StrWithCommas(num interface{}) string

Int2StrWithCommas converts an integer (arbitrarily large) to a string with commas as thousand separators.

func Int64 added in v1.3.3

func Int64(obj interface{}) int64

Returns the int64 value of the object, supporting int, int64, float64, and string types. This is a controlled assertion to safely extract and convert the value to an int64. For strings, it parses numeric values (e.g., "42"). Returns 0 for unsupported types, invalid strings, or nil input.

func Int64Abs

func Int64Abs(x int64) int64

Returns absolute value of int64 value

func Int64ToString

func Int64ToString(i int64) string

Converts int64 number to string

func IntAbs

func IntAbs(x int) int

Return absolute value of int value

func IsAlpha

func IsAlpha(c rune) bool

Checks if given rune is an alphabetic character (either uppercase or lowercase). Returns true if it is, false otherwise.

func IsDigit

func IsDigit(c rune) bool

Returns true if rune is a numerical digit. False otherwise.

func IsHexDigit

func IsHexDigit(c rune) bool

Returns true if rune is a hexadeximal digit. False otherwise.

func IsInternetAvailable added in v1.3.1

func IsInternetAvailable() bool

Checks if internet is available by attempting to reach reliable URLs.

func IsInternetNotAvailable added in v1.3.1

func IsInternetNotAvailable() bool

Checks if internet is not available.

func IsIpPortStrReachable

func IsIpPortStrReachable(ipPortStr string) bool

Checks if IP_Address:Port string is reachable

func IsLeapYear

func IsLeapYear(year int64) bool

Returns true if given year is a leap year. False otherwise.

func ItemInList

func ItemInList(arg string, argList []string) bool

ItemInList checks if a given string (arg) is present in a list of strings (argList). Returns true if found, false otherwise. Consider using utl.NewStringSet() type instead.

func JsonBytesReindent

func JsonBytesReindent(jsonBytes []byte, indent int) (jsonBytes2 []byte, err error)

Convert JSON interface object to byte slice, with option to indent spacing

func JsonBytesToJsonObj

func JsonBytesToJsonObj(jsonBytes []byte) (jsonObject interface{}, err error)

Convert JSON byte slice to JSON interface object, with default 2-space indentation

func JsonToBytes

func JsonToBytes(jsonObject interface{}) (jsonBytes []byte, err error)

Convert JSON interface object to byte slice, with default 2-space indentation

func JsonToBytesIndent

func JsonToBytesIndent(jsonObject interface{}, indent int) (jsonBytes []byte, err error)

Convert JSON interface object to byte slice, with option to indent spacing

func LastElem

func LastElem(s, splitter string) string

Split the string and return last element

func LoadFileAuto added in v1.3.4

func LoadFileAuto(filePath string) (interface{}, string, error)

LoadFileAuto reads a file, detects compression (gzip), and decodes it as JSON, YAML, or plain text. Returns raw object, format string ('json', 'yaml', or 'text' ), and error.

func LoadFileJson

func LoadFileJson(filePath string, compressed bool) (jsonObject interface{}, err error)

Reads, load, and decode given filePath as a JSON object text file. Returns JSON object and err if any. The compression option can sometimes help speed things up for some very large objects.

func LoadFileText

func LoadFileText(filePath string) (rawBytes []byte, err error)

Read and recode given filePath as text byte slice. Returns the byte slice and error if any.

func LoadFileYaml

func LoadFileYaml(filePath string) (yamlObject interface{}, err error)

Tries to read, load, and decode given filePath as some YAML object. Returns YAML object and error if any.

func LoadFileYamlBytes

func LoadFileYamlBytes(filePath string) (yamlBytes []byte, err error)

Tries to read, load, and recode given filePath as some YAML object as byte slice. Returns YAML object as byte slice. and error if any.

func Map added in v1.3.5

func Map(obj interface{}) map[string]interface{}

Returns a map[string]interface{} if the object is a map of that type. This is a controlled assertion to safely extract and convert the map value. It returns nil for unsupported types or nil input.

func MergeJsonObjects added in v1.2.0

func MergeJsonObjects(a, b map[string]interface{}) map[string]interface{}

Alias for MergeObjects function.

func MergeMaps

func MergeMaps(m1, m2 map[string]string) (result map[string]string)

Combines two string-to-string maps, with keys from the second map overwriting those from the first if duplicates exist. Returns the merged map.

func MergeObjects

func MergeObjects(a, b map[string]interface{}) map[string]interface{}

Recursively merges the keys from object a into object b. Existing object b attributes are overwritten if there's a conflict.

func PadSpaces

func PadSpaces(targetWidth, stringWidth int) string

Return string of spaces for padded printing. Needed when printing terminal colors. Colorize output uses % sequences that conflict with Printf's own formatting with %

func PostSpc

func PostSpc(value interface{}, width int) string

Return value as a string, padded with trailing spaces, totalling width size wide. This is needed when printing terminal colors, because they conflict with Printf's own '%' formatting

func PreSpc

func PreSpc(value interface{}, width int) string

Return value as a string, padded with leading spaces, totalling width size wide. This is needed when printing terminal colors, because they conflict with Printf's own '%' formatting

func Prettify

func Prettify(jsonObject interface{}) (pretty string, err error)

NOTE: To be replaced by JsonToBytes()

func PrintColorSamples

func PrintColorSamples()

PrintColorSamples is a dormant function and not actively used anywhere. It is left around for those times when someone wants to test and see what the colors would look like.

func PrintDays

func PrintDays(days int64)

Print number of days, also in years and days

func PrintJson

func PrintJson(jsonObject interface{})

Prints JSON object, flushing the output buffer

func PrintJsonBytesColor

func PrintJsonBytesColor(jsonBytes []byte)

Prints JSON byte slice in color. Just an alias of yaml.go:PrintYamlBytesColor().

func PrintJsonColor

func PrintJsonColor(jsonObject interface{})

Print JSON object in color

func PrintYaml

func PrintYaml(yamlObject interface{})

Print YAML object

func PrintYamlBytesColor

func PrintYamlBytesColor(yamlBytes []byte)

Print YAML bytes in color, includes comments Also prints JSON byte slice in color, but use json.go:PrintJsonBytesColor() alias instead. Caller must ensure yamlBytes is proper YAML/JSON

func PrintYamlColor

func PrintYamlColor(yamlObject interface{})

Print YAML object (that don't usually include comments) in color

func PromptMsg

func PromptMsg(msg string) rune

Print prompt message and return single rune character input

func RemoveFile

func RemoveFile(filePath string) error

Removes the given filepath if it exists.

func SameType

func SameType(a, b interface{}) bool

Check if two variables are of the same type

func SaveFileJson

func SaveFileJson(jsonObject interface{}, filePath string, compress bool)

Saves given JSON object as a text file, with compression as an option which can sometimes help to speed things up for some very large objects.

func SaveFileText

func SaveFileText(filePath string, rawBytes []byte) error

Saves given byte slice as text file. Returns error is any.

func SaveFileYaml

func SaveFileYaml(yamlObject interface{}, filePath string)

Save given YAML object to given filePath

func Slice added in v1.3.6

func Slice(obj interface{}) []interface{}

Returns a []interface{} if the object is a slice of that type. This is a controlled assertion to safely extract and convert the slice value. It returns nil for unsupported types or nil input.

func SortMapStringKeys

func SortMapStringKeys(obj map[string]string) (sortedKeys []string)

Return the map string object's keys sorted

func SortObjStringKeys

func SortObjStringKeys(obj map[string]interface{}) (sortedKeys []string)

Return the object's keys sorted

func Str

func Str(obj interface{}) string

Returns a string representation of the object for supported types (bool, string). This is a controlled assertion to safely extract and convert the value to a string. It returns an empty string for unsupported types or nil input.

func StrSingleQuote

func StrSingleQuote(x interface{}) string

Returns string value of unknown variable, wrapped in single quotes. This is a special function to lookout for leading '*', which YAML does not allow and must be single-quoted

func StringInJson

func StringInJson(jsonObject interface{}, filter string) bool

Recursive function returns True if filter string value is anywhere within jsonObject

func StringToInt64

func StringToInt64(s string) (int64, error)

Converts string number to int64

func StripColor added in v1.3.0

func StripColor(s string) string

StripColor removes color codes from a string.

func SubString

func SubString(large, small string) bool

Case insensitive substring check

func ToStr

func ToStr(value interface{}) string

Converts any value to its string representation using default formatting.

func Trace

func Trace() string

Returns a string showing the current filepath line number and function name.

func ValidDate

func ValidDate(dateString, expectedFormat string) bool

Check if string is a valid date in expectedFormat. Return true if so, false otherwise. See https://pkg.go.dev/time

func ValidIpStr

func ValidIpStr(ipStr string) bool

Returns true if given string is a valid IP address. False otherwise.

func ValidUuid

func ValidUuid(s string) bool

Returns true if given string is a valid UUID number. False otherwise.

func ValidateJson added in v1.2.0

func ValidateJson(filePath string) error

Checks if a given file contains valid JSON

func ValidateYaml added in v1.2.0

func ValidateYaml(filePath string) error

Checks if a given file contains valid YAML

func YamlToBytes

func YamlToBytes(yamlObject interface{}) (yamlBytes []byte, err error)

With default 2 space indent

func YamlToBytesIndent

func YamlToBytesIndent(yamlObject interface{}, indent int) (yamlBytes []byte, err error)

Convert YAML interface object to byte slice, with option indent spacing

Types

type StringSet added in v1.1.0

type StringSet map[string]struct{}

While Go doesn’t have a built-in 'Set' type, 'map' is a natural and efficient substitute. For better clarity, we wrap it in a custom type with helper methods that align with set operations. This keeps the code clean and self-explanatory while leveraging Go’s simplicity and performance. See protip https://que.one/golang/#using-struct-for-efficient-maps

func NewStringSet added in v1.1.0

func NewStringSet() StringSet

Create a new set

func (StringSet) Add added in v1.1.0

func (s StringSet) Add(item string)

Add an item to the set

func (StringSet) Exists added in v1.1.0

func (s StringSet) Exists(item string) bool

Check if an item exists in the set

func (StringSet) Remove added in v1.1.0

func (s StringSet) Remove(item string)

Remove an item from the set

func (StringSet) Size added in v1.1.0

func (s StringSet) Size() int

Get the size of the set

type TraceInfo added in v1.2.0

type TraceInfo struct {
	FuncName string
	File     string
	Line     int
}

Trace type

func Trace2 added in v1.2.0

func Trace2(depth int) TraceInfo

Improved Trace v2 with depth and with more flexible TraceInfo type return

Jump to

Keyboard shortcuts

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