Helper Utils(900+): int, byte, string, array/slice, map, struct, dump, convert/format, error, web/http, cli/flag, OS/ENV, filesystem, system, test/assert, ti
Helper Utils(900+): int, byte, string, array/slice, map, struct, dump, convert/format, error, web/http, cli/flag, OS/ENV, filesystem, system, test/assert, ti
Useful utils(900+) package for the Go: int, string, array/slice, map, struct, reflect, error, time, format, CLI, ENV, filesystem, system, testing and more.
arrutil: Array/Slice util functions. eg: check, convert, formatting, enum, collectionsbyteutil: Provide some common bytes util functions. eg: convert, check and moremaputil Map data util functions. eg: convert, sub-value get, simple mergemathutil Math(int, number) util functions. eg: convert, math calc, randomreflects Provide extends reflect util functions.structs Provide some extends util functions for struct. eg: tag parse, struct data initstrutil String util functions. eg: bytes, check, convert, encode, format and moresysutil System util functions. eg: sysenv, exec, user, processcliutil Command-line util functions. eg: colored print, read input, exec commandenvutil ENV util for current runtime env information. eg: get one, get info, parse varfsutil Filesystem util functions, quick create, read and write file. eg: file and dir check, operatejsonutil Provide some util functions for quick read, write, encode, decode JSON data.dump: GO value printing tool. print slice, map will auto wrap each element and display the call locationerrorx Provide an enhanced error implements for go, allow with stacktrace and wrap another error.assert Provides commonly asserts functions for help testingtestutil Test help util functions. eg: http test, mock ENV valuefakeobj provides a fake object for testing. such as fake fs.File, fs.FileInfo, fs.DirEntry etc.cflag: Wraps and extends go flag.FlagSet to build simple command line applicationsccolor: Simple command-line color output library that uses ANSI color codes to output text with colors.timex Provides an enhanced time.Time implementation. Add more commonly used functional methodsY-m-d H:i:sMore ...
cmdline Provide cmdline parse, args build to cmdlineencodes: Provide some encoding/decoding, hash, crypto util functions. eg: base64, hex, etc.finder Provides a simple and convenient file/dir lookup function, supports filtering, excluding, matching, ignoring, etc.netutil Network util functions. eg: Ip, IpV4, IpV6, Mac, Port, Hostname, etc.textutil Provide some extensions text handle util functions. eg: text replace, etc.textscan Implemented a parser that quickly scans and analyzes text content. It can be used to parse INI, Properties and other formatscmdr Provide for quick build and run a cmd, batch run multi cmd tasksclipboard Provide a simple clipboard read and write operations.process Provide some process handle util functions.fmtutil Format data util functions. eg: data, size, timegoinfo provide some standard util functions for go.Please see Go doc. Wiki docs on ZRead.ai - gookit/goutil
go get github.com/gookit/goutil// github.com/gookit/goutil
is.True(goutil.IsEmpty(nil))
is.False(goutil.IsEmpty("abc"))
is.True(goutil.IsEqual("a", "a"))
is.True(goutil.IsEqual([]string{"a"}, []string{"a"}))
is.True(goutil.IsEqual(23, 23))
is.True(goutil.Contains("abc", "a"))
is.True(goutil.Contains([]string{"abc", "def"}, "abc"))
is.True(goutil.Contains(map[int]string{2: "abc", 4: "def"}, 4))
// convert type
str = goutil.String(23) // "23"
iVal = goutil.Int("-2") // 2
i64Val = goutil.Int64("-2") // -2
u64Val = goutil.Uint("2") // 2dump.Print(somevar, somevar2, ...)dump nested struct
Click to see functionsPackage
github.com/gookit/goutil/arrutil
…check value:
arrutil.IntsHas([]int{2, 4, 5}, 2) // True
arrutil.Int64sHas([]int64{2, 4, 5}, 2) // True
arrutil.StringsHas([]string{"a", "b"}, "a") // True
// list and val interface{}
arrutil.Contains(list, val)
arrutil.Contains([]uint32{9, 2, 3}, 9) // Trueconvert:
ints, err := arrutil.ToInt64s([]string{"1", "2"}) // ints: []int64{1, 2}
ss, err := arrutil.ToStrings([]int{1, 2}) // ss: []string{"1", "2"}Click to see functionsPackage
github.com/gookit/goutil/byteutil
…Package
github.com/gookit/goutil/cflag
cflag - Wraps and extends go flag.FlagSet to build simple command line applications
…cflag Usagecflag usage please see cflag/README.md
Click to see functionsPackage
github.com/gookit/goutil/cliutil
…helper functions:
cliutil.Workdir() // current workdir
cliutil.BinDir() // the program exe file dir
cliutil.ReadInput("Your name?")
cliutil.ReadPassword("Input password:")
ans, _ := cliutil.ReadFirstByte("continue?[y/n] ")cmdline parse:
package main
import (
"fmt"
"github.com/gookit/goutil/cliutil"
"github.com/gookit/goutil/dump"
)
func main() {
args := cliutil.ParseLine(`./app top sub --msg "has multi words"`)
dump.P(args)
s := cliutil.BuildLine("./myapp", []string{
"-a", "val0",
"-m", "this is message",
"arg0",
})
fmt.Println("Build line:", s)
}output:
PRINT AT github.com/gookit/goutil/cliutil_test.TestParseLine(line_parser_test.go:30)
[]string [ #len=5
string("./app"), #len=5
string("top"), #len=3
string("sub"), #len=3
string("--msg"), #len=5
string("has multi words"), #len=15
]
Build line: ./myapp -a val0 -m "this is message" arg0More, please see ./cliutil/README
Click to see functionsPackage
github.com/gookit/goutil/dump
…example code:
package main
import "github.com/gookit/goutil/dump"
// rum demo:
// go run ./dump/_examples/demo1.go
func main() {
otherFunc1()
}
func otherFunc1() {
dump.P(
23,
[]string{"ab", "cd"},
[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}, // len > 10
map[string]interface{}{
"key": "val", "sub": map[string]string{"k": "v"},
},
struct {
ab string
Cd int
}{
"ab", 23,
},
)
}Preview:
nested struct
source code at
dump/dumper_test.TestStruct_WithNested
Click to see functionsPackage
github.com/gookit/goutil/envutil
…helper functions:
envutil.IsWin()
envutil.IsMac()
envutil.IsLinux()
// get ENV value by key, can with default value
envutil.Getenv("APP_ENV", "dev")
envutil.GetInt("LOG_LEVEL", 1)
envutil.GetBool("APP_DEBUG", true)
// parse ENV var value from input string, support default value.
envutil.ParseValue("${ENV_NAME | defValue}")Package
github.com/gookit/goutil/errorx
errorx provides an enhanced error reporting implementation that contains call stack information and can wrap the previous level of error.
Click to see functionsAdditional call stack information is included when printing errors, making it easy to log and find problems.
…Create error with call stack info
errorx.New instead errors.Newfunc doSomething() error {
if false {
// return errors.New("a error happen")
return errorx.New("a error happen")
}
}errorx.Newf or errorx.Errorf instead fmt.Errorffunc doSomething() error {
if false {
// return fmt.Errorf("a error %s", "happen")
return errorx.Newf("a error %s", "happen")
}
}Wrap the previous error
used like this before:
if err := SomeFunc(); err != nil {
return err
}can be replaced with:
if err := SomeFunc(); err != nil {
return errors.Stacked(err)
}Print the errorx.New() error
Examples for use errorx package, more please see ./errorx/README
err := errorx.New("the error message")
fmt.Println(err)
// fmt.Printf("%v\n", err)
// fmt.Printf("%#v\n", err)from the test:
errorx/errorx_test.TestNew()
Output:
the error message
STACK:
github.com/gookit/goutil/errorx_test.returnXErr()
/Users/inhere/Workspace/godev/gookit/goutil/errorx/errorx_test.go:21
github.com/gookit/goutil/errorx_test.returnXErrL2()
/Users/inhere/Workspace/godev/gookit/goutil/errorx/errorx_test.go:25
github.com/gookit/goutil/errorx_test.TestNew()
/Users/inhere/Workspace/godev/gookit/goutil/errorx/errorx_test.go:29
testing.tRunner()
/usr/local/Cellar/go/1.18/libexec/src/testing/testing.go:1439
runtime.goexit()
/usr/local/Cellar/go/1.18/libexec/src/runtime/asm_amd64.s:1571Package
github.com/gookit/goutil/fsutil
Package fsutil Filesystem util functions: quick check, create, read and write file. eg: file and dir check, operate
…files finder:
package main
import (
"fmt"
"io/fs"
"github.com/gookit/goutil/fsutil"
)
func main() {
// find all files in dir
fsutil.FindInDir("./", func(filePath string, de fs.DirEntry) error {
fmt.Println(filePath)
return nil
})
// find files with filters
fsutil.FindInDir("./", func(filePath string, de fs.DirEntry) error {
fmt.Println(filePath)
return nil
}, fsutil.ExcludeDotFile)
}Package
github.com/gookit/goutil/jsonutil
…Click to see functionsPackage
github.com/gookit/goutil/maputil
…Package
github.com/gookit/goutil/mathutil
Package mathutil provide math(int, number) util functions. eg: convert, math calc, random
…Package
github.com/gookit/goutil/reflects
Package reflects Provide extends reflection util functions. eg: check, convert, value set, etc.
…Package
github.com/gookit/goutil/structs
Package structs Provide some extends util functions for struct. eg: tag parse, struct init, value set/get
…Click to see functionsPackage
github.com/gookit/goutil/strutil
…Click to see functionsPackage
github.com/gookit/goutil/sysutil
…Click to see functionsPackage
github.com/gookit/goutil/testutil
…Package
github.com/gookit/goutil/timex
Provides an enhanced time.Time implementation,
No open issues yet, or sync has not completed.