goutil

package module
v0.7.2 Latest Latest
Warning

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

Go to latest
Published: Sep 18, 2024 License: MIT Imports: 22 Imported by: 4

README

GoUtil

icon

Utility functions for go.

Installation

go get github.com/tkdeng/goutil

Documentation

Index

Constants

This section is empty.

Variables

View Source
var HTML *encodeHtml = &encodeHtml{}
View Source
var JSON *encodeJson = &encodeJson{}

Functions

func AppendRoot added in v0.3.0

func AppendRoot(root string, paths ...*string) error

AppendRoot will append a root path to a list of paths

func Clean

func Clean[T interface{ string | []byte }](val T) T

Clean.Str will sanitizes a string to valid UTF-8

func CloneBytes added in v0.2.0

func CloneBytes(b []byte) []byte

CloneBytes is a simple method for copying a stuborn []byte that wants to be a reference

golang default:
	buf := make([]byte, 5)
	buf = []byte{'t', 'e', 's', 't', '1'}
	newBuf := buf
	newBuf[4] = 2
	string(buf) == string(newBuf)

using this method:
	buf := make([]byte, 5)
	buf = []byte{'t', 'e', 's', 't', '1'}
	newBuf := goutil.CloneBytes(buf)
	newBuf[4] = 2
	string(buf) != string(newBuf)

func Contains

func Contains[T any](search []T, value T) bool

Contains returns true if an array contains a value

func ContainsMap

func ContainsMap[T Hashable, J any](search map[T]J, value J) bool

ContainsMap returns true if a map contains a value

func ContainsMapKey

func ContainsMapKey[T Hashable, J any](search map[T]J, key T) bool

ContainsMapKey returns true if a map contains a key

func CopyFile

func CopyFile(src, dst string) (int64, error)

Copy lets you copy files from the src to the dst

func FormatMemoryUsage added in v0.2.0

func FormatMemoryUsage(b uint64) float64

FormatMemoryUsage converts bytes to megabytes

func GenUUID added in v0.1.0

func GenUUID(size uint, timezone ...string) string

GenUUID generates a Unique Identifier using a custom build method

Notice: This feature is currently in beta

@size: (minimum: 8) the bit size for the last part of the uuid (note: other parts may vary)

@timezone: optionally add a timezone string to the uuid (note: you could also pass random info into here for a more complex algorithm)

This method uses the following data:

  • A hash of the current year and day of year
  • A hash of the current timezone
  • A hash of the current unix time (in seconds)
  • A hash of the current unix time in nanoseconds and a random number

The returned value is url encoded and will look something like this: xxxx-xxxx-xxxx-xxxxxxxx

func IndexOf

func IndexOf[T any](search []T, value T) (int, error)

IndexOf returns the index of a value in an array

returns -1 and an error if the value is not found

func IndexOfMap

func IndexOfMap[T Hashable, J any](search map[T]J, value J) (T, error)

IndexOfMap returns the index of a value in a map

returns an error if the value is not found

func IsZeroOfUnderlyingType

func IsZeroOfUnderlyingType(x interface{}) bool

IsZeroOfUnderlyingType can be used to determine if an interface{} in null or empty

func JoinMap added in v0.7.2

func JoinMap[T Hashable](dest *map[T]any, m ...*map[T]any)

JoinMap merges 2 or more maps to the dest map

This method will also try to search for nested map values of the same key type, and append to array values if possible.

func JoinPath

func JoinPath(path ...string) (string, error)

JoinPath joins multiple file types with safety from backtracking

func MapArgs added in v0.2.0

func MapArgs(args ...[]string) map[string]string

MapArgs will convert a bash argument array ([]string) into a map (map[string]string)

When @args is left blank with no values, it will default to os.Args[1:]

-- Arg Conversions:

"--Key=value" will convert to "key:value"

"--boolKey" will convert to "boolKey:true"

"-flags" will convert to "f:true, l:true, a:true, g:true, s:true" (only if its alphanumeric [A-Za-z0-9]) if -flags is not alphanumeric (example: "-test.paniconexit0" "-test.timeout=10m0s") it will be treated as a --flag (--key=value --boolKey)

keys that match a number ("--1" or "-1") will start with a "-" ("--1=value" -> "-1:value", "-1" -> -1:true) this prevents a number key from conflicting with an index key

everything else is given a number value index starting with 0

this method will not allow --args to have their values modified after they have already been set

func RandBytes added in v0.1.0

func RandBytes(size uint, exclude ...[]byte) []byte

RandBytes generates random bytes using crypto/rand

@exclude[0] allows you can to pass an optional []byte to ensure that set of chars will not be included in the output string

@exclude[1] provides a replacement string to put in place of the unwanted chars

@exclude[2:] is currently ignored

func ReadConfig

func ReadConfig(path string, out interface{}) error

ReadConfig loads a config file into a struct

this method will read the buffer, and normalize names so '-' and '_' characters are optional, and everything is lowercase

this method will try different file types in the following order:

[yml, yaml, json]

you can specify the first file type to try, by adding a .ext of that file type to the path

by accepting moltiple file types, the user can choose what type of file they want to use for their config file

func ReadJson

func ReadJson(path string, out interface{}) error

ReadJson loads a json file into a struct

this method will read the buffer, and normalize names so '-' and '_' characters are optional, and everything is lowercase

this method is useful for loading a config file

func ReadYaml

func ReadYaml(path string, out interface{}) error

ReadYaml loads a yaml file into a struct

this method will read the buffer, and normalize names so '-' and '_' characters are optional, and everything is lowercase

this method is useful for loading a config file

func StepBytes added in v0.5.0

func StepBytes(buf *[]byte, cb func(i *int, b func(int) byte, m StepBytesMethod) bool)

StepBytes runs a for loop over []byte in a safer way.

This method is intended to read through a []byte, one byte at a time, and replace characters at a specific point. This method can be useful for building a small compiler.

@cb:

  • return true to continue loop
  • return false to break the loop

@*i: the current index of the loop

@b: returns the currend byte relative to the index

example:
 b(0) == b[i]
 b(1) == b[i+1]
 b(-1) == b[i-1]

@m: other useful methods

func Swap added in v0.3.0

func Swap[T any](val1 *T, val2 *T)

Swap will swap the values of 2 variables

func SysFreeMemory added in v0.2.0

func SysFreeMemory() float64

SysFreeMemory returns the amount of memory available in megabytes

func ToColumns added in v0.7.0

func ToColumns(list [][]string, charSize int, sep ...string) string

ToColumns sorts a list of strings into rows and columns

The column size will be wrapped by words first, and wrap to the specisied size.

This method is useful for printing help info to a terminal.

example:

stty := 80 // import "golang.org/x/term"
if width, _, err := term.GetSize(0); err == nil {
  stty = width
}

goutil.ToColumns([][]string{
  {"--opt1", "info"}
  {"--opt2, -o", "more info"}
}, stty, "    ", "\n\n")

@sep (optional): column separator || row separator

  • if "\n" is included: this will assume a row separator.
  • else: this will assume a column separator

func ToType

func ToType[T SupportedType](val interface{}) T

ToType attempts to converts an interface{} from the many possible types in golang, to a specific type of your choice

if it fails to convert, it will return a nil/zero value for the appropriate type

func TrimTabs added in v0.1.1

func TrimTabs(size uint8, buf []byte, tabSize ...uint8) []byte

TrimTabs trims exxess beginning tab characters from a multiline string

@size: number of tabs to trim

func URandBytes added in v0.1.0

func URandBytes(size uint, unique ...*[][]byte) []byte

URandBytes tries to generate a unique random bytes

This method uses the current microsecond and crypto random bytes to generate unique keys. This method also only returns alphanumeric characters [A-Za-z0-9]

@unique (optional): add a list pointer, to keep track of what keys were already used. This method will automattically append new keys to the list. If the same key is generated twice, the function will try again (using recursion).

Types

type ArgsReader added in v0.3.0

type ArgsReader struct {
	// contains filtered or unexported fields
}

ArgsReader is a structured way to read os.args

Note: you should call `args.New()` to get a populated list of arguments

func ReadArgs added in v0.3.0

func ReadArgs(args ...[]string) ArgsReader

ReadArgs returns a list of `os.args` in a structured ArgsReader

func (*ArgsReader) Get added in v0.3.0

func (args *ArgsReader) Get(def string, name string, alt ...string) string

Get returns a key value from os.args

@def: default value if no arg is found

@name: the name of the argument to search for

@alt: optional list of fallback names to search for

  • note: if you pass an empty value or `*` into @alt, it will assume the next integer arg that has not been returned yet.

type CPU added in v0.2.0

type CPU struct {
	// HighTemp is the highest temperature for the WaitToCool method to detect that the cpu is too hot
	//
	// note: if set to strict mode, LowTemp will take this variables place
	//
	// default: 64 (celsius)
	HighTemp uint16

	// LowTemp is the lowest temperature for the WaitToCool method to wait for, before deciding that the cpu has colled down,
	// if it was previously throttled by HighTemp (except in strict mode, where LowTemp takes the place of HighTemp)
	//
	// default: 56 (celsius)
	LowTemp uint16

	// when Logging is enabled, the WaitToCool method will log info to the console to report when it is waiting for the cpu to cool down
	//
	// you can set this var to false to disable this feature
	//
	// default: true
	Logging bool
}

func (*CPU) GetTemp added in v0.2.0

func (cpu *CPU) GetTemp() uint16

GetTemp returns the average cpu temperature in celsius

func (*CPU) WaitToCool added in v0.2.0

func (cpu *CPU) WaitToCool(strict bool)

WaitToCool makes your function wait for the cpu to cool down

by default, if the temperature > HighTemp, it will wait until the temperature <= LowTemp

in strict mode, this will run if temperature > LowTemp

HighTemp = 64 LowTemp = 56

type CacheMap added in v0.4.0

type CacheMap[K Hashable, V any] struct {
	// contains filtered or unexported fields
}

func NewCache added in v0.4.0

func NewCache[K Hashable, V any](exp time.Duration) *CacheMap[K, V]

NewCache creates a new cache map

func (*CacheMap[K, V]) Del added in v0.4.0

func (cache *CacheMap[K, V]) Del(key K)

Del removes a cache item by key

func (*CacheMap[K, V]) DelOld added in v0.4.0

func (cache *CacheMap[K, V]) DelOld(cacheTime time.Duration)

DelOld removes old cache items

func (*CacheMap[K, V]) Expire added in v0.4.0

func (cache *CacheMap[K, V]) Expire(exp time.Duration) bool

Expire sets the ttl for all cache items

func (*CacheMap[K, V]) ForEach added in v0.4.0

func (cache *CacheMap[K, V]) ForEach(cb func(key K, value V) bool, touch ...bool)

ForEach runs a callback function for each cache item that has not expired

in the callback, return true to continue, and false to break the loop

func (*CacheMap[K, V]) Get added in v0.4.0

func (cache *CacheMap[K, V]) Get(key K) (V, error)

Get returns a value or an error if it exists

if the object key does not exist, it will return both a nil/zero value (of the relevant type) and nil error

func (*CacheMap[K, V]) Has added in v0.4.0

func (cache *CacheMap[K, V]) Has(key K) bool

Has returns true if a key value exists and is not an error

func (*CacheMap[K, V]) Set added in v0.4.0

func (cache *CacheMap[K, V]) Set(key K, value V, err error)

Set sets or adds a new key with either a value, or an error

func (*CacheMap[K, V]) Touch added in v0.4.0

func (cache *CacheMap[K, V]) Touch(key K) bool

Touch resets a cache items expiration so it will stay in the cache longer

type FSWatcher

type FSWatcher struct {

	// when a file changes
	//
	// @path: the file path the change happened to
	//
	// @op: the change operation
	OnFileChange func(path string, op string)

	// when a directory is added
	//
	// @path: the file path the change happened to
	//
	// @op: the change operation
	//
	// return false to prevent that directory from being watched
	OnDirAdd func(path string, op string) (addWatcher bool)

	// when a file or directory is removed
	//
	// @path: the file path the change happened to
	//
	// @op: the change operation
	//
	// return false to prevent that directory from no longer being watched
	OnRemove func(path string, op string) (removeWatcher bool)

	// every time something happens
	//
	// @path: the file path the change happened to
	//
	// @op: the change operation
	OnAny func(path string, op string)
	// contains filtered or unexported fields
}

A watcher instance for the `FS.FSWatcher` method

func FileWatcher

func FileWatcher() *FSWatcher

FileWatcher creates a new file watcher

func (*FSWatcher) CloseWatcher

func (fw *FSWatcher) CloseWatcher(root string) error

CloseWatcher will close the watcher by the root name you used

@root pass a file path for a specific watcher or "*" for all watchers that exist

func (*FSWatcher) Wait

func (fw *FSWatcher) Wait()

Wait for all Watchers to close

func (*FSWatcher) WatchDir

func (fw *FSWatcher) WatchDir(root string, nosub ...bool) error

WatchDir watches the files in a directory and its subdirectories for changes

@nosub: do not watch sub directories

type Hashable

type Hashable interface {
	int | int8 | int16 | int32 | int64 | uint | uint8 | uint16 | uint32 | uint64 | uintptr | float32 | float64 | string | complex64 | complex128
}

type NullType

type NullType[T any] struct {
	Null T
}

type StepBytesMethod added in v0.5.0

type StepBytesMethod struct {
	// contains filtered or unexported fields
}

func (*StepBytesMethod) End added in v0.5.0

func (m *StepBytesMethod) End() (next bool)

End breaks the loop

this method always returns false

func (*StepBytesMethod) GetBuf added in v0.5.0

func (m *StepBytesMethod) GetBuf(size int) []byte

GetBuf will return a []byte from the current `*i` index, to the size specified

func (*StepBytesMethod) Inc added in v0.5.0

func (m *StepBytesMethod) Inc(size int) (next bool)

Inc increments i and will break the loop if i >= len(buf)

this method also returns false, if the loop should break, and true if the loop should continue

func (*StepBytesMethod) Loop added in v0.5.0

func (m *StepBytesMethod) Loop(logic func() bool, cb func() bool)

Loop creates an inner loop that continues to verify the array length

if loop is not incramented after the callback, the loop will automatically break and log a warning

@cb:

  • return true to continue loop
  • return false to break the loop

func (*StepBytesMethod) Replace added in v0.5.0

func (m *StepBytesMethod) Replace(ind *[2]int, rep *[]byte)

Replace will replace bytes at a specific start and end point

this method will also modify the size of the []byte if needed, and automatically correct `*i` to the correct index if it changes

type SupportedType

type SupportedType interface {
	string | []byte | byte | bool |
		int | int64 | int32 | int16 | int8 |
		uint | uint64 | uint32 | uint16 | uintptr |
		float64 | float32
}

SupportedType is an interface containing the types which are supported by the ToType method

type SyncMap added in v0.6.0

type SyncMap[K Hashable, V any] struct {
	// contains filtered or unexported fields
}

func NewMap added in v0.6.0

func NewMap[K Hashable, V any]() *SyncMap[K, V]

NewMap creates a new synchronized map that uses sync.Mutex behind the scenes

func (*SyncMap[K, V]) Del added in v0.6.0

func (syncmap *SyncMap[K, V]) Del(key K)

Del removes an item by key

func (*SyncMap[K, V]) ForEach added in v0.6.0

func (syncmap *SyncMap[K, V]) ForEach(cb func(key K, value V) bool)

ForEach runs a callback function for each key value pair

in the callback, return true to continue, and false to break the loop

func (*SyncMap[K, V]) Get added in v0.6.0

func (syncmap *SyncMap[K, V]) Get(key K) (V, bool)

Get returns a value or an error if it exists

func (*SyncMap[K, V]) Has added in v0.6.0

func (syncmap *SyncMap[K, V]) Has(key K) bool

Has returns true if a key value exists in the list

func (*SyncMap[K, V]) Set added in v0.6.0

func (syncmap *SyncMap[K, V]) Set(key K, value V)

Set sets or adds a new key with a value

type ToInterface

type ToInterface struct {
	Val interface{}
}

Jump to

Keyboard shortcuts

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