utl

package module
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 29, 2024 License: MIT Imports: 20 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.

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 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 given filePath age in seconds int64

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) (e 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 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 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 InternetIsAvailable

func InternetIsAvailable() bool

Checks if internet is available. This is of course a very poor check relying on DNS resolution working and this particular URL being available.

func InternetNotAvailable

func InternetNotAvailable() bool

Inverse of above function.

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 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 LoadFileJson

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

Reads, load, and decode given filePath as a JSON object text file. Returns JSON object and err if any.

func LoadFileJsonGzip

func LoadFileJsonGzip(filePath string) (jsonObject interface{}, err error)

Reads, load, and decode given filePath as a gzipped JSON object text file. Returns JSON object and err if any. The compression helps 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)

Trys 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 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(x, y map[string]interface{}) (obj map[string]interface{})

Non-recursive merge of first-level attributes in JSON object y onto object x If attribute exists in y, it is overwritten

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)

Removes given filepath

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)

Save given JSON object as text file

func SaveFileJsonGzip

func SaveFileJsonGzip(jsonObject interface{}, filePath string)

Save given JSON object as gzipped text file

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 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(x interface{}) string

Return the best printable string value for given x variable

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 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 returns a string showing the current filepath line number and function name. See https://stackoverflow.com/questions/25927660/how-to-get-the-current-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 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, you can wrap it in a custom type with helper methods that align with set operations. This keeps your code clean and self-explanatory while leveraging Go’s simplicity and performance. See protip https://que.tips/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

Jump to

Keyboard shortcuts

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