Documentation ¶
Overview ¶
Package utils provides some utility functions for internal usage.
Index ¶
- Variables
- func BytesDecode(coding encoding.Encoding, s []byte) ([]byte, string, error)
- func BytesToHex(src []byte) []byte
- func BytesToNumber[T any](nbytes []byte, bigEndian ...bool) (data T)
- func CaseFoldIn(target string, str_array []string) bool
- func CaseIn(target string, str_array []string) bool
- func CharsetDecode(coding encoding.Encoding, src []byte) []byte
- func CharsetEncode(coding encoding.Encoding, src []byte) []byte
- func ChdirToPos(p ...string) (err error)
- func CopyDir(srcPath, desPath string) error
- func CopyFile(src, des string) (written int64, err error)
- func CopyToNewDir(srcPath, desPath string) error
- func CreateFile(path string, data string, mode fs.FileMode) error
- func Cwd(child ...string) string
- func DeleteFiles(path string, regexpr string)
- func DeletePath(path string) error
- func DeleteThingsInDir(targetDir string) error
- func DetermineDecode(s []byte, contentType ...string) ([]byte, string, error)
- func EqualFoldWithoutChars(s1, s2 string) bool
- func Error(layer int, format string, args ...interface{})
- func ErrorWithoutHeader(format string, args ...interface{})
- func Exec(name string, args ...string) error
- func ExitIfError(err error, fn ...any) error
- func ExitIfErrorWithoutHeader(err error, fn ...any) error
- func FileIsExisted(filename string) bool
- func FormatCmdKey(s string) string
- func FormatEnvKey(s string) string
- func GetCurrentAbPath() string
- func HexDump(src []byte, show ...func(fmt string, args ...any))
- func HexString(src []byte) string
- func HexToBytes(src []byte) []byte
- func HexToString(src []byte) string
- func HomePath() string
- func IfError(err error, fn ...any) error
- func IfErrorWithoutHeader(err error, fn ...any) error
- func Impt(layer int, format string, args ...interface{})
- func ImptWithoutHeader(format string, args ...interface{})
- func Info(layer int, format string, args ...interface{})
- func InfoIfError(err error, fn ...any) error
- func InfoIfErrorWithoutHeader(err error, fn ...any) error
- func InfoWithoutHeader(format string, args ...interface{})
- func IsArray(value interface{}) bool
- func IsDir(name string) bool
- func IsEmpty(value interface{}) bool
- func IsFloat(value interface{}) bool
- func IsInt(value interface{}) bool
- func IsLetter(b byte) bool
- func IsLetterLower(b byte) bool
- func IsLetterUpper(b byte) bool
- func IsMap(value interface{}) bool
- func IsNil(value interface{}, traceSource ...bool) bool
- func IsNumeric(s string) bool
- func IsSlice(value interface{}) bool
- func IsStruct(value interface{}) bool
- func IsUint(value interface{}) bool
- func ListDir(dirPth string, suffix ...string) (dirs []string, files []string, err error)
- func ListToMapByKey(list []map[string]interface{}, key string) map[string]interface{}
- func MakeDir(path string, perm fs.FileMode, isfile ...bool) error
- func MapContainsPossibleKey(data map[string]interface{}, key string) bool
- func MapPossibleItemByKey(data map[string]interface{}, key string) (foundKey string, foundValue interface{})
- func MoveFile(src, des string)
- func NumberToBytes[T any](n T, bigEndian ...bool) []byte
- func NumberToString[T any](n T) string
- func Param[T any](p []T, def T) T
- func PatchClean(p string) string
- func PathFix(p string) string
- func PathJoin(elem ...string) string
- func PathReplace(path string, from string, to string) string
- func ProgressBar(max int64, spin int, theme string, descPrefix ...string) *progressbar.ProgressBar
- func ReadChanWithTimeout[T any](ctx context.Context, c <-chan T, timeouts ...time.Duration) (T, error)
- func RemoveSymbols(s string) string
- func ReplaceByMap(origin string, replaces map[string]string) string
- func RunIn(dir string, c string, args ...string) error
- func RunInDir(dir string, cmd *exec.Cmd) (err error)
- func SessionId(length ...int) string
- func SetupExitNotify(done chan os.Signal)
- func SplitAndTrim(str, delimiter string, characterMask ...string) []string
- func StringConvert(from string, to string, src string) (string, error)
- func StringToHex(s string) []byte
- func StripSlashes(str string) string
- func TailToHead(a []any) []any
- func TempPath(p string) string
- func Trim(str string, characterMask ...string) string
- func UUID() string
- func UUIDV1() string
- func UcFirst(s string) string
- func ValueToInterface(v reflect.Value) (value interface{}, ok bool)
- func WalkDir(dirPth string, suffix ...string) (dirs []string, files []string, err error)
- func Warn(layer int, format string, args ...interface{})
- func WarnIfError(err error, fn ...any) error
- func WarnIfErrorWithoutHeader(err error, fn ...any) error
- func WarnWithoutHeader(format string, args ...interface{})
- func WriteChanWithTimeout[T any](ctx context.Context, c chan T, data T, timeouts ...time.Duration) error
- type Loggerf
- type OriginTypeAndKindOutput
- type OriginValueAndKindOutput
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( // Chinese GB2312 = simplifiedchinese.HZGB2312 GB18030 = simplifiedchinese.GB18030 GBK = simplifiedchinese.GBK Big5 = traditionalchinese.Big5 // Korean EUCKR = korean.EUCKR // Japanese EUCJP = japanese.EUCJP ISO2022JP = japanese.ISO2022JP ShiftJIS = japanese.ShiftJIS // Unicode UTF8 = unicode.UTF8 UTF8BOM = unicode.UTF16(unicode.BigEndian, unicode.UseBOM) UCS2BigEndian = unicode.UTF16(unicode.BigEndian, unicode.IgnoreBOM) UCS2LittleEndian = unicode.UTF16(unicode.LittleEndian, unicode.IgnoreBOM) )
var ( ErrEOF = errors.New("EOF") ErrUnexpectedEOF = errors.New("unexpected EOF") ErrNoProgress = errors.New("multiple Read calls return no data or error") ErrSrcPathInvalid = errors.New("srcPath is not a valid directory path") ErrDstPathInvalid = errors.New("destPath is not a valid directory path") ErrSrcSameAsDst = errors.New("destPath must be different from srcPath") ErrChanWriteTimeout = errors.New("write chan time out") ErrChanReadTimeout = errors.New("read chan time out") ErrChanOptCanceled = errors.New("chan operation canceled") ErrNotFound = errors.New("404") )
var ( ANSI_CYAN = "\x1b[36;1m" ANSI_RESET = "\x1b[0m" ANSI_DEFAULT = "\x1b[39;1m" ANSI_BLUE = "\x1b[34;1m" ANSI_BLACK = "\x1b[30;1m" ANSI_RED = "\x1b[31;1m" ANSI_GREEN = "\x1b[32;1m" ANSI_YELLOW = "\x1b[33;1m" ANSI_WHITE = "\x1b[37;1m" ANSI_MAGENTA = "\x1b[35;1m" )
var ( // DefaultTrimChars are the characters which are stripped by Trim* functions in default. DefaultTrimChars = string([]byte{ '\t', '\v', '\n', '\r', '\f', ' ', 0x00, 0x85, 0xA0, }) )
var Ord = func(char byte) int { return int(char) }
ord use char as parameter, rerturn ascii number
var PBTheme = map[string]progressbar.Option{
"=>": progressbar.OptionSetTheme(progressbar.Theme{
Saucer: "[green]=[reset]",
SaucerHead: "[green]>[reset]",
SaucerPadding: " ",
BarStart: "[",
BarEnd: "]",
}),
"█": progressbar.OptionSetTheme(progressbar.Theme{
Saucer: "[green]█[reset]",
SaucerHead: "[green] [reset]",
SaucerPadding: " ",
BarStart: "|",
BarEnd: "|",
}),
}
Functions ¶
func BytesToHex ¶
Covert bytes to hex bytes, aim to make []byte{0x5B, 0x47, 0x4F, 0x5D}) ==> []byte("5b474f5d")
func BytesToNumber ¶
T can be bool, int8/16/32/64, uint8/16/32/64, float32/64 T also could be slice of type bool/int8~64, uint8~64, float32~64
func CaseFoldIn ¶
CaseFoldIn check if str_array contains target case insensitively, return true if contains, otherwise false.
func CaseIn ¶
CaseIn check if str_array contains target case sensitively, return true if contains, otherwise false.
func CopyDir ¶
Only the contents of the source directory are recursively copied to the destination path, source directory itself not copied. Returns error if source/destination path does not exist. And srcPath must be different from desPath.
func DeleteFiles ¶
func DeleteThingsInDir ¶
Delete all files in the directory, left an empty directory(targetDir)
func DetermineDecode ¶
Probe the bytes encoding and try to convert to UTF-8
func EqualFoldWithoutChars ¶
EqualFoldWithoutChars checks string `s1` and `s2` equal case-insensitively, with/without chars '-'/'_'/'.'/' '.
func ErrorWithoutHeader ¶
func ErrorWithoutHeader(format string, args ...interface{})
func ExitIfError ¶
CheckIfError should be used to naively panics if an error is not nil. Eg: utils.ExitIfError(errTest, log.Warningf, "%s %s", "warning", "message")
Example ¶
package main import ( "errors" "github.com/lovelacelee/clsgo/v1/log" "github.com/lovelacelee/clsgo/v1/utils" ) var errMessage = "ok" var errTest = errors.New(errMessage) func main() { utils.ExitIfError(errTest, log.Infof, "%s %s", "ERROR", "message") }
Output:
func ExitIfErrorWithoutHeader ¶
Example ¶
package main import ( "errors" "github.com/lovelacelee/clsgo/v1/utils" ) var errMessage = "ok" var errTest = errors.New(errMessage) func main() { utils.ExitIfErrorWithoutHeader(errTest) }
Output:
func FileIsExisted ¶
func FormatCmdKey ¶
FormatCmdKey formats string `s` as command key using uniformed format.
func FormatEnvKey ¶
FormatEnvKey formats string `s` as environment key using uniformed format.
func HexToBytes ¶
BytesToHex BytesToHex, aim to make []byte("5b474f5d")) ==> []byte{0x5B, 0x47, 0x4F, 0x5D}
func HexToString ¶
func IfError ¶
Only output in terminal in Error message, Eg: utils.IfError(errTest, log.Errorf, "%s %s", "error", "error message")
func IfErrorWithoutHeader ¶
func ImptWithoutHeader ¶
func ImptWithoutHeader(format string, args ...interface{})
func InfoIfError ¶
Only output in terminal in [INFO] message, Eg: utils.InfoIfError(errTest, log.Infof, "%s %s", "warning", "message")
Example ¶
package main import ( "errors" "github.com/lovelacelee/clsgo/v1/log" "github.com/lovelacelee/clsgo/v1/utils" ) var errMessage = "ok" var errTest = errors.New(errMessage) func main() { utils.InfoIfErrorWithoutHeader(errTest, log.Green, "%s %s", "INFO", "message") utils.InfoIfError(errTest, log.Infof, "%s %s", "INFO", "message") }
Output:
func InfoWithoutHeader ¶
func InfoWithoutHeader(format string, args ...interface{})
func IsArray ¶
func IsArray(value interface{}) bool
IsArray checks whether given value is array/slice. Note that it uses reflect internally implementing this feature.
func IsEmpty ¶
func IsEmpty(value interface{}) bool
IsEmpty checks whether given `value` empty. It returns true if `value` is in: 0, nil, false, "", len(slice/map/chan) == 0, or else it returns false.
func IsFloat ¶
func IsFloat(value interface{}) bool
IsFloat checks whether `value` is type of float.
func IsLetterLower ¶
IsLetterLower checks whether the given byte b is in lower case.
func IsLetterUpper ¶
IsLetterUpper checks whether the given byte b is in upper case.
func IsNil ¶
IsNil checks whether given `value` is nil, especially for interface{} type value. Parameter `traceSource` is used for tracing to the source variable if given `value` is type of pinter that also points to a pointer. It returns nil if the source is nil when `traceSource` is true. Note that it might use reflect feature which affects performance a little.
func IsNumeric ¶
IsNumeric checks whether the given string s is numeric. Note that float string like "123.456" is also numeric.
func IsSlice ¶
func IsSlice(value interface{}) bool
IsSlice checks whether `value` is type of slice.
func IsStruct ¶
func IsStruct(value interface{}) bool
IsStruct checks whether `value` is type of struct.
func ListDir ¶
Return all files and dirs in [dirPath], optional matching suffix, sub directories ignored
func ListToMapByKey ¶
ListToMapByKey converts `list` to a map[string]interface{} of which key is specified by `key`. Note that the item value may be type of slice.
func MakeDir ¶
Create directory: The path parameter can be a directory or a file. If it is a file path, it will be truncated by the Dir function
func MapContainsPossibleKey ¶
MapContainsPossibleKey checks if the given `key` is contained in given map `data`. It checks the key ignoring cases and symbols.
Note that this function might be of low performance.
func MapPossibleItemByKey ¶
func MapPossibleItemByKey(data map[string]interface{}, key string) (foundKey string, foundValue interface{})
MapPossibleItemByKey tries to find the possible key-value pair for given key ignoring cases and symbols.
Note that this function might be of low performance.
func NumberToBytes ¶
T can be bool, int8/16/32/64, uint8/16/32/64, float32/64 T also could be slice of type bool/int8~64, uint8~64, float32~64
func NumberToString ¶
func PatchClean ¶
func ProgressBar ¶
If max == -1, enable spinner progress bar, theme if one of PBTheme key
func ReadChanWithTimeout ¶
func RemoveSymbols ¶
RemoveSymbols removes all symbols from string and lefts only numbers and letters.
func ReplaceByMap ¶
ReplaceByMap returns a copy of `origin`, which is replaced by a map in unordered way, case-sensitively.
func RunInDir ¶
cmd := exec.Command("git", "push", remote, "--tags", "--force") utils.RunInDir(w.Filesystem.Root(), cmd)
func SetupExitNotify ¶
Set up channel on which to send signal notifications. We must use a buffered channel or risk missing the signal if we're not ready to receive when the signal is sent.
Example ¶
package main import ( "os" "testing" "time" "github.com/gogf/gf/v2/test/gtest" "github.com/lovelacelee/clsgo/v1/utils" ) func main() { gtest.C(&testing.T{}, func(t *gtest.T) { exit := make(chan os.Signal, 1) utils.SetupExitNotify(exit) go func(x chan os.Signal) { time.Sleep(time.Second * 2) x <- os.Interrupt }(exit) e := <-exit t.Assert(e, os.Interrupt) }) }
Output:
func SplitAndTrim ¶
SplitAndTrim splits string `str` by a string `delimiter` to an array, and calls Trim to every element of this array. It ignores the elements which are empty after Trim.
func StringConvert ¶
Wrapper for gcharset of goframe
func StringToHex ¶
func StripSlashes ¶
StripSlashes un-quotes a quoted string by AddSlashes.
func TailToHead ¶
func Trim ¶
Trim strips whitespace (or other characters) from the beginning and end of a string. The optional parameter `characterMask` specifies the additional stripped characters.
func UcFirst ¶
UcFirst returns a copy of the string s with the first letter mapped to its upper case.
func ValueToInterface ¶
ValueToInterface converts reflect value to its interface type.
func WalkDir ¶
Get all files in the specified directory and all subdirectories, matching suffix filtering.
func WarnIfError ¶
Only output in terminal in [WARN] message, Eg: utils.WarnIfError(errTest, log.Warningf, "%s %s", "warning", "message")
Example ¶
package main import ( "errors" "github.com/lovelacelee/clsgo/v1/log" "github.com/lovelacelee/clsgo/v1/utils" ) var errMessage = "ok" var errTest = errors.New(errMessage) func main() { utils.WarnIfError(errTest) utils.WarnIfError(errTest, log.Warningf, "%s %s", "warning", "message") }
Output:
func WarnWithoutHeader ¶
func WarnWithoutHeader(format string, args ...interface{})
Types ¶
type OriginTypeAndKindOutput ¶
type OriginTypeAndKindOutput struct { InputType reflect.Type InputKind reflect.Kind OriginType reflect.Type OriginKind reflect.Kind }
func OriginTypeAndKind ¶
func OriginTypeAndKind(value interface{}) (out OriginTypeAndKindOutput)
OriginTypeAndKind retrieves and returns the original reflect type and kind.
type OriginValueAndKindOutput ¶
type OriginValueAndKindOutput struct { InputValue reflect.Value InputKind reflect.Kind OriginValue reflect.Value OriginKind reflect.Kind }
func OriginValueAndKind ¶
func OriginValueAndKind(value interface{}) (out OriginValueAndKindOutput)
OriginValueAndKind retrieves and returns the original reflect value and kind.