项目作者: gookit

项目描述 :
? Helper Utils For The Go: string, array/slice, map, format, cli, env, filesystem, test and more. Go 的一些工具函数,格式化,特殊处理,常用信息获取等等
高级语言: Go
项目地址: git://github.com/gookit/goutil.git


Go Util

GitHub go.mod Go version
GitHub tag (latest SemVer)
Go Report Card
Unit-Tests
Coverage Status
Go Reference

💪 Useful utils(700+) package for the Go: int, string, array/slice, map, error, time, format, CLI, ENV, filesystem, system, testing and more.

中文说明

Basic packages:

  • arrutil: Array/Slice util functions. eg: check, convert, formatting, enum, collections
  • cliutil Command-line util functions. eg: colored print, read input, exec command
  • envutil ENV util for current runtime env information. eg: get one, get info, parse var
  • fmtutil Format data util functions. eg: data, size, time
  • fsutil Filesystem util functions, quick create, read and write file. eg: file and dir check, operate
  • goinfo provide some standard util functions for go.
  • jsonutil Provide some util functions for quick read, write, encode, decode JSON data.
  • maputil Map data util functions. eg: convert, sub-value get, simple merge
  • mathutil Math(int, number) util functions. eg: convert, math calc, random
  • netutil Network util functions. eg: Ip, IpV4, IpV6, Mac, Port, Hostname, etc.
  • reflects Provide extends reflect util functions.
  • structs Provide some extends util functions for struct. eg: tag parse, struct data init
  • strutil String util functions. eg: bytes, check, convert, encode, format and more
  • sysutil System util functions. eg: sysenv, exec, user, process

Extra packages:

  • cflag: Wraps and extends go flag.FlagSet to build simple command line applications
  • cli util:
    • cmdline Provide cmdline parse, args build to cmdline
  • dump: GO value printing tool. print slice, map will auto wrap each element and display the call location
  • encodes: Provide some encoding/decoding, hash, crypto util functions. eg: base64, hex, etc.
  • errorx Provide an enhanced error implements for go, allow with stacktrace and wrap another error.
  • file util:
    • finder Provides a simple and convenient filedir lookup function, supports filtering, excluding, matching, ignoring, etc.
  • net util:
    • httpreq An easier-to-use HTTP client that wraps http.Client, and with some http utils.
  • string util:
    • textscan Implemented a parser that quickly scans and analyzes text content. It can be used to parse INI, Properties and other formats
    • textutil Provide some extensions text handle util functions. eg: text replace, etc.
  • syncs Provides synchronization primitives util functions.
  • system util:
    • clipboard Provide a simple clipboard read and write operations.
    • cmdr Provide for quick build and run a cmd, batch run multi cmd tasks
    • process Provide some process handle util functions.
  • testutil Test help util functions. eg: http test, mock ENV value
    • assert Provides commonly asserts functions for help testing
    • fakeobj provides a fake object for testing. such as fake fs.File, fs.FileInfo, fs.DirEntry etc.
  • timex Provides an enhanced time.Time implementation. Add more commonly used functional methods
    • such as: DayStart(), DayAfter(), DayAgo(), DateFormat() and more.

Go Doc

Please see Go doc

Install

  1. go get github.com/gookit/goutil

Usage

  1. // github.com/gookit/goutil
  2. is.True(goutil.IsEmpty(nil))
  3. is.False(goutil.IsEmpty("abc"))
  4. is.True(goutil.IsEqual("a", "a"))
  5. is.True(goutil.IsEqual([]string{"a"}, []string{"a"}))
  6. is.True(goutil.IsEqual(23, 23))
  7. is.True(goutil.Contains("abc", "a"))
  8. is.True(goutil.Contains([]string{"abc", "def"}, "abc"))
  9. is.True(goutil.Contains(map[int]string{2: "abc", 4: "def"}, 4))
  10. // convert type
  11. str = goutil.String(23) // "23"
  12. iVal = goutil.Int("-2") // 2
  13. i64Val = goutil.Int64("-2") // -2
  14. u64Val = goutil.Uint("2") // 2

Dump go variable

  1. dump.Print(somevar, somevar2, ...)

dump nested struct

preview-nested-struct

Packages

Array and Slice

Package github.com/gookit/goutil/arrutil

  1. // source at arrutil/arrutil.go
  2. func GetRandomOne[T any](arr []T) T
  3. func RandomOne[T any](arr []T) T
  4. // source at arrutil/check.go
  5. func SliceHas[T comdef.ScalarType](slice []T, val T) bool
  6. func IntsHas[T comdef.Integer](ints []T, val T) bool
  7. func Int64sHas(ints []int64, val int64) bool
  8. func StringsHas[T ~string](ss []T, val T) bool
  9. func InStrings[T ~string](elem T, ss []T) bool
  10. func NotIn[T comdef.ScalarType](value T, list []T) bool
  11. func In[T comdef.ScalarType](value T, list []T) bool
  12. func ContainsAll[T comdef.ScalarType](list, values []T) bool
  13. func IsSubList[T comdef.ScalarType](values, list []T) bool
  14. func IsParent[T comdef.ScalarType](values, list []T) bool
  15. func HasValue(arr, val any) bool
  16. func Contains(arr, val any) bool
  17. func NotContains(arr, val any) bool
  18. // source at arrutil/collection.go
  19. func StringEqualsComparer(a, b string) int
  20. func ValueEqualsComparer[T comdef.Compared](a, b T) int
  21. func ReflectEqualsComparer[T any](a, b T) int
  22. func ElemTypeEqualsComparer[T any](a, b T) int
  23. func TwowaySearch[T any](data []T, item T, fn Comparer[T]) (int, error)
  24. func CloneSlice[T any](data []T) []T
  25. func Diff[T any](first, second []T, fn Comparer[T]) []T
  26. func Differences[T any](first, second []T, fn Comparer[T]) []T
  27. func Excepts[T any](first, second []T, fn Comparer[T]) []T
  28. func Intersects[T any](first, second []T, fn Comparer[T]) []T
  29. func Union[T any](first, second []T, fn Comparer[T]) []T
  30. func Find[T any](source []T, fn Predicate[T]) (v T, err error)
  31. func FindOrDefault[T any](source []T, fn Predicate[T], defaultValue T) T
  32. func TakeWhile[T any](data []T, fn Predicate[T]) []T
  33. func ExceptWhile[T any](data []T, fn Predicate[T]) []T
  34. // source at arrutil/convert.go
  35. func JoinStrings(sep string, ss ...string) string
  36. func StringsJoin(sep string, ss ...string) string
  37. func JoinTyped[T any](sep string, arr ...T) string
  38. func JoinSlice(sep string, arr ...any) string
  39. func IntsToString[T comdef.Integer](ints []T) string
  40. func ToInt64s(arr any) (ret []int64, err error)
  41. func MustToInt64s(arr any) []int64
  42. func SliceToInt64s(arr []any) []int64
  43. func AnyToSlice(sl any) (ls []any, err error)
  44. func AnyToStrings(arr any) []string
  45. func MustToStrings(arr any) []string
  46. func ToStrings(arr any) (ret []string, err error)
  47. func SliceToStrings(arr []any) []string
  48. func QuietStrings(arr []any) []string
  49. func ConvType[T any, R any](arr []T, newElemTyp R) ([]R, error)
  50. func AnyToString(arr any) string
  51. func SliceToString(arr ...any) string
  52. func ToString[T any](arr []T) string
  53. func CombineToMap[K comdef.SortedType, V any](keys []K, values []V) map[K]V
  54. func CombineToSMap(keys, values []string) map[string]string
  55. // source at arrutil/format.go
  56. func NewFormatter(arr any) *ArrFormatter
  57. func FormatIndent(arr any, indent string) string
  58. // source at arrutil/process.go
  59. func Reverse[T any](ls []T)
  60. func Remove[T comdef.Compared](ls []T, val T) []T
  61. func Filter[T any](ls []T, filter ...comdef.MatchFunc[T]) []T
  62. func Map[T any, V any](list []T, mapFn MapFn[T, V]) []V
  63. func Column[T any, V any](list []T, mapFn func(obj T) (val V, find bool)) []V
  64. func Unique[T ~string | comdef.XintOrFloat](list []T) []T
  65. func IndexOf[T ~string | comdef.XintOrFloat](val T, list []T) int
  66. // source at arrutil/strings.go
  67. func StringsToAnys(ss []string) []any
  68. func StringsToSlice(ss []string) []any
  69. func StringsAsInts(ss []string) []int
  70. func StringsToInts(ss []string) (ints []int, err error)
  71. func StringsTryInts(ss []string) (ints []int, err error)
  72. func StringsUnique(ss []string) []string
  73. func StringsContains(ss []string, s string) bool
  74. func StringsRemove(ss []string, s string) []string
  75. func StringsFilter(ss []string, filter ...comdef.StringMatchFunc) []string
  76. func StringsMap(ss []string, mapFn func(s string) string) []string
  77. func TrimStrings(ss []string, cutSet ...string) []string

ArrUtil Usage

check value:

  1. arrutil.IntsHas([]int{2, 4, 5}, 2) // True
  2. arrutil.Int64sHas([]int64{2, 4, 5}, 2) // True
  3. arrutil.StringsHas([]string{"a", "b"}, "a") // True
  4. // list and val interface{}
  5. arrutil.Contains(list, val)
  6. arrutil.Contains([]uint32{9, 2, 3}, 9) // True

convert:

  1. ints, err := arrutil.ToInt64s([]string{"1", "2"}) // ints: []int64{1, 2}
  2. ss, err := arrutil.ToStrings([]int{1, 2}) // ss: []string{"1", "2"}

Bytes Utils

Package github.com/gookit/goutil/byteutil

  1. // source at byteutil/buffer.go
  2. func NewBuffer() *Buffer
  3. // source at byteutil/byteutil.go
  4. func Md5(src any) []byte
  5. func ShortMd5(src any) []byte
  6. func Random(length int) ([]byte, error)
  7. func FirstLine(bs []byte) []byte
  8. func AppendAny(dst []byte, v any) []byte
  9. func Cut(bs []byte, sep byte) (before, after []byte, found bool)
  10. func SafeCut(bs []byte, sep byte) (before, after []byte)
  11. func SafeCuts(bs []byte, sep []byte) (before, after []byte)
  12. // source at byteutil/check.go
  13. func IsNumChar(c byte) bool
  14. // source at byteutil/conv.go
  15. func StrOrErr(bs []byte, err error) (string, error)
  16. func SafeString(bs []byte, err error) string
  17. func String(b []byte) string
  18. func ToString(b []byte) string
  19. func ToBytes(v any) ([]byte, error)
  20. func SafeBytes(v any) []byte
  21. func ToBytesWithFunc(v any, usrFn ToBytesFunc) ([]byte, error)
  22. // source at byteutil/encoder.go
  23. func NewStdEncoder(encFn BytesEncodeFunc, decFn BytesDecodeFunc) *StdEncoder
  24. // source at byteutil/pool.go
  25. func NewChanPool(chSize int, width int, capWidth int) *ChanPool

Cflag

Package github.com/gookit/goutil/cflag

  1. // source at cflag/app.go
  2. func NewApp(fns ...func(app *App)) *App
  3. func NewCmd(name, desc string) *Cmd
  4. // source at cflag/cflag.go
  5. func SetDebug(open bool)
  6. func New(fns ...func(c *CFlags)) *CFlags
  7. func NewEmpty(fns ...func(c *CFlags)) *CFlags
  8. func WithDesc(desc string) func(c *CFlags)
  9. func WithVersion(version string) func(c *CFlags)
  10. // source at cflag/ext.go
  11. func LimitInt(min, max int) comdef.IntCheckFunc
  12. func NewIntVar(checkFn comdef.IntCheckFunc) IntVar
  13. func NewStrVar(checkFn comdef.StrCheckFunc) StrVar
  14. func NewEnumString(enum ...string) EnumString
  15. func NewKVString() KVString
  16. func Value
  17. // source at cflag/optarg.go
  18. func NewArg(name, desc string, required bool) *FlagArg
  19. // source at cflag/util.go
  20. func IsGoodName(name string) bool
  21. func IsZeroValue(opt *flag.Flag, value string) (bool, bool)
  22. func AddPrefix(name string) string
  23. func AddPrefixes(name string, shorts []string) string
  24. func AddPrefixes2(name string, shorts []string, nameAtEnd bool) string
  25. func SplitShortcut(shortcut string) []string
  26. func FilterNames(names []string) []string
  27. func IsFlagHelpErr(err error) bool
  28. func WrapColorForCode(s string) string
  29. func ReplaceShorts(args []string, shortsMap map[string]string) []string

cflag Usage

cflag usage please see cflag/README.md

CLI/Console

Package github.com/gookit/goutil/cliutil

  1. // source at cliutil/cliutil.go
  2. func SplitMulti(ss []string, sep string) []string
  3. func LineBuild(binFile string, args []string) string
  4. func BuildLine(binFile string, args []string) string
  5. func String2OSArgs(line string) []string
  6. func StringToOSArgs(line string) []string
  7. func ParseLine(line string) []string
  8. func QuickExec(cmdLine string, workDir ...string) (string, error)
  9. func ExecLine(cmdLine string, workDir ...string) (string, error)
  10. func ExecCmd(binName string, args []string, workDir ...string) (string, error)
  11. func ExecCommand(binName string, args []string, workDir ...string) (string, error)
  12. func ShellExec(cmdLine string, shells ...string) (string, error)
  13. func CurrentShell(onlyName bool) (path string)
  14. func HasShellEnv(shell string) bool
  15. func BuildOptionHelpName(names []string) string
  16. func ShellQuote(s string) string
  17. func OutputLines(output string) []string
  18. // source at cliutil/info.go
  19. func Workdir() string
  20. func BinDir() string
  21. func BinFile() string
  22. func BinName() string
  23. func GetTermSize(refresh ...bool) (w int, h int)
  24. // source at cliutil/read.go
  25. func ReadInput(question string) (string, error)
  26. func ReadLine(question string) (string, error)
  27. func ReadFirst(question string) (string, error)
  28. func ReadFirstByte(question string) (byte, error)
  29. func ReadFirstRune(question string) (rune, error)
  30. func ReadAsBool(tip string, defVal bool) bool
  31. func Confirm(tip string, defVal ...bool) bool
  32. func InputIsYes(ans string) bool
  33. func ByteIsYes(ans byte) bool
  34. func ReadPassword(question ...string) string

CLI Util Usage

helper functions:

  1. cliutil.Workdir() // current workdir
  2. cliutil.BinDir() // the program exe file dir
  3. cliutil.ReadInput("Your name?")
  4. cliutil.ReadPassword("Input password:")
  5. ans, _ := cliutil.ReadFirstByte("continue?[y/n] ")

cmdline parse:

  1. package main
  2. import (
  3. "fmt"
  4. "github.com/gookit/goutil/cliutil"
  5. "github.com/gookit/goutil/dump"
  6. )
  7. func main() {
  8. args := cliutil.ParseLine(`./app top sub --msg "has multi words"`)
  9. dump.P(args)
  10. s := cliutil.BuildLine("./myapp", []string{
  11. "-a", "val0",
  12. "-m", "this is message",
  13. "arg0",
  14. })
  15. fmt.Println("Build line:", s)
  16. }

output:

  1. PRINT AT github.com/gookit/goutil/cliutil_test.TestParseLine(line_parser_test.go:30)
  2. []string [ #len=5
  3. string("./app"), #len=5
  4. string("top"), #len=3
  5. string("sub"), #len=3
  6. string("--msg"), #len=5
  7. string("has multi words"), #len=15
  8. ]
  9. Build line: ./myapp -a val0 -m "this is message" arg0

More, please see ./cliutil/README

Dumper

Package github.com/gookit/goutil/dump

  1. // source at dump/dump.go
  2. func Std() *Dumper
  3. func Reset()
  4. func Config(fns ...OptionFunc)
  5. func Print(vs ...any)
  6. func Println(vs ...any)
  7. func Fprint(w io.Writer, vs ...any)
  8. func Std2() *Dumper
  9. func Reset2()
  10. func Format(vs ...any) string
  11. func NoLoc(vs ...any)
  12. func Clear(vs ...any)
  13. // source at dump/dumper.go
  14. func NewDumper(out io.Writer, skip int) *Dumper
  15. func NewWithOptions(fns ...OptionFunc) *Dumper
  16. // source at dump/options.go
  17. func NewDefaultOptions(out io.Writer, skip int) *Options
  18. func SkipNilField() OptionFunc
  19. func SkipPrivate() OptionFunc
  20. func BytesAsString() OptionFunc
  21. func WithCallerSkip(skip int) OptionFunc
  22. func WithoutPosition() OptionFunc
  23. func WithoutOutput(out io.Writer) OptionFunc
  24. func WithoutColor() OptionFunc
  25. func WithoutType() OptionFunc

Examples

example code:

  1. package main
  2. import "github.com/gookit/goutil/dump"
  3. // rum demo:
  4. // go run ./dump/_examples/demo1.go
  5. func main() {
  6. otherFunc1()
  7. }
  8. func otherFunc1() {
  9. dump.P(
  10. 23,
  11. []string{"ab", "cd"},
  12. []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}, // len > 10
  13. map[string]interface{}{
  14. "key": "val", "sub": map[string]string{"k": "v"},
  15. },
  16. struct {
  17. ab string
  18. Cd int
  19. }{
  20. "ab", 23,
  21. },
  22. )
  23. }

Preview:

nested struct

source code at dump/dumper_test.TestStruct_WithNested

Encodes

Package github.com/gookit/goutil/encodes

  1. // source at encodes/encodes.go
  2. func B32Encode(str string) string
  3. func B32Decode(str string) string
  4. func B64Encode(str string) string
  5. func B64EncodeBytes(src []byte) []byte
  6. func B64Decode(str string) string
  7. func B64DecodeBytes(str []byte) []byte

ENV/Environment

Package github.com/gookit/goutil/envutil

  1. // source at envutil/envutil.go
  2. func VarReplace(s string) string
  3. func ParseOrErr(val string) (string, error)
  4. func ParseValue(val string) string
  5. func VarParse(val string) string
  6. func ParseEnvValue(val string) string
  7. func SetEnvMap(mp map[string]string)
  8. func SetEnvs(kvPairs ...string)
  9. func UnsetEnvs(keys ...string)
  10. // source at envutil/get.go
  11. func Getenv(name string, def ...string) string
  12. func GetInt(name string, def ...int) int
  13. func GetBool(name string, def ...bool) bool
  14. func GetMulti(names ...string) map[string]string
  15. func EnvPaths() []string
  16. func EnvMap() map[string]string
  17. func Environ() map[string]string
  18. func SearchEnvKeys(keywords string) map[string]string
  19. func SearchEnv(keywords string, matchValue bool) map[string]string
  20. // source at envutil/info.go
  21. func IsWin() bool
  22. func IsWindows() bool
  23. func IsMac() bool
  24. func IsLinux() bool
  25. func IsMSys() bool
  26. func IsWSL() bool
  27. func IsTerminal(fd uintptr) bool
  28. func StdIsTerminal() bool
  29. func IsConsole(out io.Writer) bool
  30. func HasShellEnv(shell string) bool
  31. func IsSupportColor() bool
  32. func IsSupport256Color() bool
  33. func IsSupportTrueColor() bool
  34. func IsGithubActions() bool

ENV Util Usage

helper functions:

  1. envutil.IsWin()
  2. envutil.IsMac()
  3. envutil.IsLinux()
  4. // get ENV value by key, can with default value
  5. envutil.Getenv("APP_ENV", "dev")
  6. envutil.GetInt("LOG_LEVEL", 1)
  7. envutil.GetBool("APP_DEBUG", true)
  8. // parse ENV var value from input string, support default value.
  9. envutil.ParseValue("${ENV_NAME | defValue}")

Errorx

Package github.com/gookit/goutil/errorx

Package errorx provide a enhanced error implements, allow with call stack and wrap another error.

  1. // source at errorx/assert.go
  2. func IsTrue(result bool, fmtAndArgs ...any) error
  3. func IsFalse(result bool, fmtAndArgs ...any) error
  4. func IsIn[T comdef.ScalarType](value T, list []T, fmtAndArgs ...any) error
  5. func NotIn[T comdef.ScalarType](value T, list []T, fmtAndArgs ...any) error
  6. // source at errorx/errors.go
  7. func NewR(code int, msg string) ErrorR
  8. func Fail(code int, msg string) ErrorR
  9. func Failf(code int, tpl string, v ...any) ErrorR
  10. func Suc(msg string) ErrorR
  11. // source at errorx/errorx.go
  12. func New(msg string) error
  13. func Newf(tpl string, vars ...any) error
  14. func Errorf(tpl string, vars ...any) error
  15. func With(err error, msg string) error
  16. func Withf(err error, tpl string, vars ...any) error
  17. func WithPrev(err error, msg string) error
  18. func WithPrevf(err error, tpl string, vars ...any) error
  19. func WithStack(err error) error
  20. func Traced(err error) error
  21. func Stacked(err error) error
  22. func WithOptions(msg string, fns ...func(opt *ErrStackOpt)) error
  23. func Wrap(err error, msg string) error
  24. func Wrapf(err error, tpl string, vars ...any) error
  25. // source at errorx/stack.go
  26. func FuncForPC(pc uintptr) *Func
  27. func ResetStdOpt()
  28. func Config(fns ...func(opt *ErrStackOpt))
  29. func SkipDepth(skipDepth int) func(opt *ErrStackOpt)
  30. func TraceDepth(traceDepth int) func(opt *ErrStackOpt)
  31. // source at errorx/util.go
  32. func Err(msg string) error
  33. func Raw(msg string) error
  34. func Ef(tpl string, vars ...any) error
  35. func Errf(tpl string, vars ...any) error
  36. func Rawf(tpl string, vars ...any) error
  37. func Cause(err error) error
  38. func Unwrap(err error) error
  39. func Previous(err error) error
  40. func IsErrorX(err error) (ok bool)
  41. func ToErrorX(err error) (ex *ErrorX, ok bool)
  42. func MustEX(err error) *ErrorX
  43. func Has(err, target error) bool
  44. func Is(err, target error) bool
  45. func To(err error, target any) bool
  46. func As(err error, target any) bool

Errorx Usage

Create error with call stack info

  • use the errorx.New instead errors.New
  1. func doSomething() error {
  2. if false {
  3. // return errors.New("a error happen")
  4. return errorx.New("a error happen")
  5. }
  6. }
  • use the errorx.Newf or errorx.Errorf instead fmt.Errorf
  1. func doSomething() error {
  2. if false {
  3. // return fmt.Errorf("a error %s", "happen")
  4. return errorx.Newf("a error %s", "happen")
  5. }
  6. }

Wrap the previous error

used like this before:

  1. if err := SomeFunc(); err != nil {
  2. return err
  3. }

can be replaced with:

  1. if err := SomeFunc(); err != nil {
  2. return errors.Stacked(err)
  3. }

Print the errorx.New() error

Examples for use errorx package, more please see ./errorx/README

  1. err := errorx.New("the error message")
  2. fmt.Println(err)
  3. // fmt.Printf("%v\n", err)
  4. // fmt.Printf("%#v\n", err)

from the test: errorx/errorx_test.TestNew()

Output:

  1. the error message
  2. STACK:
  3. github.com/gookit/goutil/errorx_test.returnXErr()
  4. /Users/inhere/Workspace/godev/gookit/goutil/errorx/errorx_test.go:21
  5. github.com/gookit/goutil/errorx_test.returnXErrL2()
  6. /Users/inhere/Workspace/godev/gookit/goutil/errorx/errorx_test.go:25
  7. github.com/gookit/goutil/errorx_test.TestNew()
  8. /Users/inhere/Workspace/godev/gookit/goutil/errorx/errorx_test.go:29
  9. testing.tRunner()
  10. /usr/local/Cellar/go/1.18/libexec/src/testing/testing.go:1439
  11. runtime.goexit()
  12. /usr/local/Cellar/go/1.18/libexec/src/runtime/asm_amd64.s:1571

Format Utils

Package github.com/gookit/goutil/fmtutil

  1. // source at fmtutil/fmtutil.go
  2. func StringOrJSON(v any) ([]byte, error)
  3. // source at fmtutil/format.go
  4. func DataSize(size uint64) string
  5. func SizeToString(size uint64) string
  6. func StringToByte(sizeStr string) uint64
  7. func ParseByte(sizeStr string) uint64
  8. func PrettyJSON(v any) (string, error)
  9. func ArgsWithSpaces(vs []any) (message string)
  10. // source at fmtutil/time.go
  11. func HowLongAgo(sec int64) string

File System

Package github.com/gookit/goutil/fsutil

  1. // source at fsutil/check.go
  2. func PathExists(path string) bool
  3. func IsDir(path string) bool
  4. func FileExists(path string) bool
  5. func IsFile(path string) bool
  6. func IsAbsPath(aPath string) bool
  7. func IsEmptyDir(dirPath string) bool
  8. func IsImageFile(path string) bool
  9. func IsZipFile(filepath string) bool
  10. func PathMatch(pattern, s string) bool
  11. // source at fsutil/define.go
  12. func NewEntry(fPath string, ent fs.DirEntry) Entry
  13. func NewFileInfo(fPath string, info fs.FileInfo) FileInfo
  14. // source at fsutil/find.go
  15. func FilePathInDirs(file string, dirs ...string) string
  16. func FirstExists(paths ...string) string
  17. func FirstExistsDir(paths ...string) string
  18. func FirstExistsFile(paths ...string) string
  19. func MatchPaths(paths []string, matcher PathMatchFunc) []string
  20. func MatchFirst(paths []string, matcher PathMatchFunc, defaultPath string) string
  21. func SearchNameUp(dirPath, name string) string
  22. func SearchNameUpx(dirPath, name string) (string, bool)
  23. func WalkDir(dir string, fn fs.WalkDirFunc) error
  24. func Glob(pattern string, fls ...NameMatchFunc) []string
  25. func GlobWithFunc(pattern string, fn func(filePath string) error) (err error)
  26. func OnlyFindDir(_ string, ent fs.DirEntry) bool
  27. func OnlyFindFile(_ string, ent fs.DirEntry) bool
  28. func ExcludeNames(names ...string) FilterFunc
  29. func IncludeSuffix(ss ...string) FilterFunc
  30. func ExcludeDotFile(_ string, ent fs.DirEntry) bool
  31. func ExcludeSuffix(ss ...string) FilterFunc
  32. func ApplyFilters(fPath string, ent fs.DirEntry, filters []FilterFunc) bool
  33. func FindInDir(dir string, handleFn HandleFunc, filters ...FilterFunc) (e error)
  34. // source at fsutil/fsutil.go
  35. func JoinPaths(elem ...string) string
  36. func JoinSubPaths(basePath string, elem ...string) string
  37. func SlashPath(path string) string
  38. func UnixPath(path string) string
  39. func ToAbsPath(p string) string
  40. // source at fsutil/info.go
  41. func DirPath(fpath string) string
  42. func Dir(fpath string) string
  43. func PathName(fpath string) string
  44. func Name(fpath string) string
  45. func FileExt(fpath string) string
  46. func Extname(fpath string) string
  47. func Suffix(fpath string) string
  48. func Expand(pathStr string) string
  49. func ExpandPath(pathStr string) string
  50. func ResolvePath(pathStr string) string
  51. func SplitPath(pathStr string) (dir, name string)
  52. // source at fsutil/info_nonwin.go
  53. func Realpath(pathStr string) string
  54. // source at fsutil/mime.go
  55. func DetectMime(path string) string
  56. func MimeType(path string) (mime string)
  57. func ReaderMimeType(r io.Reader) (mime string)
  58. // source at fsutil/operate.go
  59. func Mkdir(dirPath string, perm os.FileMode) error
  60. func MkDirs(perm os.FileMode, dirPaths ...string) error
  61. func MkSubDirs(perm os.FileMode, parentDir string, subDirs ...string) error
  62. func MkParentDir(fpath string) error
  63. func NewOpenOption(optFns ...OpenOptionFunc) *OpenOption
  64. func OpenOptOrNew(opt *OpenOption) *OpenOption
  65. func WithFlag(flag int) OpenOptionFunc
  66. func WithPerm(perm os.FileMode) OpenOptionFunc
  67. func OpenFile(filePath string, flag int, perm os.FileMode) (*os.File, error)
  68. func MustOpenFile(filePath string, flag int, perm os.FileMode) *os.File
  69. func QuickOpenFile(filepath string, fileFlag ...int) (*os.File, error)
  70. func OpenAppendFile(filepath string, filePerm ...os.FileMode) (*os.File, error)
  71. func OpenTruncFile(filepath string, filePerm ...os.FileMode) (*os.File, error)
  72. func OpenReadFile(filepath string) (*os.File, error)
  73. func CreateFile(fpath string, filePerm, dirPerm os.FileMode, fileFlag ...int) (*os.File, error)
  74. func MustCreateFile(filePath string, filePerm, dirPerm os.FileMode) *os.File
  75. func Remove(fPath string) error
  76. func MustRemove(fPath string)
  77. func QuietRemove(fPath string)
  78. func SafeRemoveAll(path string)
  79. func RmIfExist(fPath string) error
  80. func DeleteIfExist(fPath string) error
  81. func RmFileIfExist(fPath string) error
  82. func DeleteIfFileExist(fPath string) error
  83. func RemoveSub(dirPath string, fns ...FilterFunc) error
  84. func Unzip(archive, targetDir string) (err error)
  85. // source at fsutil/opread.go
  86. func NewIOReader(in any) (r io.Reader, err error)
  87. func DiscardReader(src io.Reader)
  88. func ReadFile(filePath string) []byte
  89. func MustReadFile(filePath string) []byte
  90. func ReadReader(r io.Reader) []byte
  91. func MustReadReader(r io.Reader) []byte
  92. func ReadString(in any) string
  93. func ReadStringOrErr(in any) (string, error)
  94. func ReadAll(in any) []byte
  95. func GetContents(in any) []byte
  96. func MustRead(in any) []byte
  97. func ReadOrErr(in any) ([]byte, error)
  98. func ReadExistFile(filePath string) []byte
  99. func TextScanner(in any) *scanner.Scanner
  100. func LineScanner(in any) *bufio.Scanner
  101. // source at fsutil/opwrite.go
  102. func OSTempFile(pattern string) (*os.File, error)
  103. func TempFile(dir, pattern string) (*os.File, error)
  104. func OSTempDir(pattern string) (string, error)
  105. func TempDir(dir, pattern string) (string, error)
  106. func MustSave(filePath string, data any, optFns ...OpenOptionFunc)
  107. func SaveFile(filePath string, data any, optFns ...OpenOptionFunc) error
  108. func PutContents(filePath string, data any, fileFlag ...int) (int, error)
  109. func WriteFile(filePath string, data any, perm os.FileMode, fileFlag ...int) error
  110. func WriteOSFile(f *os.File, data any) (n int, err error)
  111. func CopyFile(srcPath, dstPath string) error
  112. func MustCopyFile(srcPath, dstPath string)
  113. func UpdateContents(filePath string, handleFn func(bs []byte) []byte) error

FsUtil Usage

files finder:

  1. package main
  2. import (
  3. "fmt"
  4. "io/fs"
  5. "github.com/gookit/goutil/fsutil"
  6. )
  7. func main() {
  8. // find all files in dir
  9. fsutil.FindInDir("./", func(filePath string, de fs.DirEntry) error {
  10. fmt.Println(filePath)
  11. return nil
  12. })
  13. // find files with filters
  14. fsutil.FindInDir("./", func(filePath string, de fs.DirEntry) error {
  15. fmt.Println(filePath)
  16. return nil
  17. }, fsutil.ExcludeDotFile)
  18. }

Go Info

Package github.com/gookit/goutil/goinfo

  1. // source at goinfo/gofunc.go
  2. func FuncName(fn any) string
  3. func CutFuncName(fullFcName string) (pkgPath, shortFnName string)
  4. func PkgName(fullFcName string) string
  5. func GoodFuncName(name string) bool
  6. // source at goinfo/goinfo.go
  7. func GoVersion() string
  8. func ParseGoVersion(line string) (*GoInfo, error)
  9. func OsGoInfo() (*GoInfo, error)
  10. // source at goinfo/stack.go
  11. func GetCallStacks(all bool) []byte
  12. func GetCallerInfo(skip int) string
  13. func SimpleCallersInfo(skip, num int) []string
  14. func GetCallersInfo(skip, max int) []string

JSON Utils

Package github.com/gookit/goutil/jsonutil

  1. // source at jsonutil/encoding.go
  2. func MustString(v any) string
  3. func Encode(v any) ([]byte, error)
  4. func EncodePretty(v any) ([]byte, error)
  5. func EncodeString(v any) (string, error)
  6. func EncodeToWriter(v any, w io.Writer) error
  7. func EncodeUnescapeHTML(v any) ([]byte, error)
  8. func Decode(bts []byte, ptr any) error
  9. func DecodeString(str string, ptr any) error
  10. func DecodeReader(r io.Reader, ptr any) error
  11. // source at jsonutil/jsonutil.go
  12. func WriteFile(filePath string, data any) error
  13. func WritePretty(filePath string, data any) error
  14. func ReadFile(filePath string, v any) error
  15. func Pretty(v any) (string, error)
  16. func MustPretty(v any) string
  17. func Mapping(src, dst any) error
  18. func IsJSON(s string) bool
  19. func IsJSONFast(s string) bool
  20. func IsArray(s string) bool
  21. func IsObject(s string) bool
  22. func StripComments(src string) string

Map

Package github.com/gookit/goutil/maputil

  1. // source at maputil/check.go
  2. func HasKey(mp, key any) (ok bool)
  3. func HasOneKey(mp any, keys ...any) (ok bool, key any)
  4. func HasAllKeys(mp any, keys ...any) (ok bool, noKey any)
  5. // source at maputil/convert.go
  6. func KeyToLower(src map[string]string) map[string]string
  7. func ToStringMap(src map[string]any) map[string]string
  8. func CombineToSMap(keys, values []string) SMap
  9. func CombineToMap[K comdef.SortedType, V any](keys []K, values []V) map[K]V
  10. func ToAnyMap(mp any) map[string]any
  11. func TryAnyMap(mp any) (map[string]any, error)
  12. func HTTPQueryString(data map[string]any) string
  13. func StringsMapToAnyMap(ssMp map[string][]string) map[string]any
  14. func ToString(mp map[string]any) string
  15. func ToString2(mp any) string
  16. func FormatIndent(mp any, indent string) string
  17. func Flatten(mp map[string]any) map[string]any
  18. func FlatWithFunc(mp map[string]any, fn reflects.FlatFunc)
  19. // source at maputil/format.go
  20. func NewFormatter(mp any) *MapFormatter
  21. // source at maputil/get.go
  22. func DeepGet(mp map[string]any, path string) (val any)
  23. func QuietGet(mp map[string]any, path string) (val any)
  24. func GetFromAny(path string, data any) (val any, ok bool)
  25. func GetByPath(path string, mp map[string]any) (val any, ok bool)
  26. func GetByPathKeys(mp map[string]any, keys []string) (val any, ok bool)
  27. func Keys(mp any) (keys []string)
  28. func Values(mp any) (values []any)
  29. func EachAnyMap(mp any, fn func(key string, val any))
  30. // source at maputil/maputil.go
  31. func SimpleMerge(src, dst map[string]any) map[string]any
  32. func DeepMerge(src, dst map[string]any, deep int) map[string]any
  33. func MergeSMap(src, dst map[string]string, ignoreCase bool) map[string]string
  34. func MergeStringMap(src, dst map[string]string, ignoreCase bool) map[string]string
  35. func MergeMultiSMap(mps ...map[string]string) map[string]string
  36. func FilterSMap(sm map[string]string) map[string]string
  37. func MakeByPath(path string, val any) (mp map[string]any)
  38. func MakeByKeys(keys []string, val any) (mp map[string]any)
  39. // source at maputil/setval.go
  40. func SetByPath(mp *map[string]any, path string, val any) error
  41. func SetByKeys(mp *map[string]any, keys []string, val any) (err error)

Math/Number

Package github.com/gookit/goutil/mathutil

  1. // source at mathutil/check.go
  2. func IsNumeric(c byte) bool
  3. func Compare(first, second any, op string) bool
  4. func CompInt[T comdef.Xint](first, second T, op string) (ok bool)
  5. func CompInt64(first, second int64, op string) bool
  6. func CompFloat[T comdef.Float](first, second T, op string) (ok bool)
  7. func CompValue[T comdef.XintOrFloat](first, second T, op string) (ok bool)
  8. func InRange[T comdef.IntOrFloat](val, min, max T) bool
  9. func OutRange[T comdef.IntOrFloat](val, min, max T) bool
  10. func InUintRange[T comdef.Uint](val, min, max T) bool
  11. // source at mathutil/compare.go
  12. func Min[T comdef.XintOrFloat](x, y T) T
  13. func Max[T comdef.XintOrFloat](x, y T) T
  14. func SwapMin[T comdef.XintOrFloat](x, y T) (T, T)
  15. func SwapMax[T comdef.XintOrFloat](x, y T) (T, T)
  16. func MaxInt(x, y int) int
  17. func SwapMaxInt(x, y int) (int, int)
  18. func MaxI64(x, y int64) int64
  19. func SwapMaxI64(x, y int64) (int64, int64)
  20. func MaxFloat(x, y float64) float64
  21. // source at mathutil/convert.go
  22. func NewConvOption[T any](optFns ...ConvOptionFn[T]) *ConvOption[T]
  23. func WithNilAsFail[T any](opt *ConvOption[T])
  24. func WithHandlePtr[T any](opt *ConvOption[T])
  25. func WithUserConvFn[T any](fn ToTypeFunc[T]) ConvOptionFn[T]
  26. func Int(in any) (int, error)
  27. func SafeInt(in any) int
  28. func QuietInt(in any) int
  29. func IntOrPanic(in any) int
  30. func MustInt(in any) int
  31. func IntOrDefault(in any, defVal int) int
  32. func IntOr(in any, defVal int) int
  33. func IntOrErr(in any) (int, error)
  34. func ToInt(in any) (int, error)
  35. func ToIntWith(in any, optFns ...ConvOptionFn[int]) (iVal int, err error)
  36. func StrInt(s string) int
  37. func StrIntOr(s string, defVal int) int
  38. func Int64(in any) (int64, error)
  39. func SafeInt64(in any) int64
  40. func QuietInt64(in any) int64
  41. func MustInt64(in any) int64
  42. func Int64OrDefault(in any, defVal int64) int64
  43. func Int64Or(in any, defVal int64) int64
  44. func ToInt64(in any) (int64, error)
  45. func Int64OrErr(in any) (int64, error)
  46. func ToInt64With(in any, optFns ...ConvOptionFn[int64]) (i64 int64, err error)
  47. func Uint(in any) (uint, error)
  48. func SafeUint(in any) uint
  49. func QuietUint(in any) uint
  50. func MustUint(in any) uint
  51. func UintOrDefault(in any, defVal uint) uint
  52. func UintOr(in any, defVal uint) uint
  53. func UintOrErr(in any) (uint, error)
  54. func ToUint(in any) (u64 uint, err error)
  55. func ToUintWith(in any, optFns ...ConvOptionFn[uint]) (uVal uint, err error)
  56. func Uint64(in any) (uint64, error)
  57. func QuietUint64(in any) uint64
  58. func SafeUint64(in any) uint64
  59. func MustUint64(in any) uint64
  60. func Uint64OrDefault(in any, defVal uint64) uint64
  61. func Uint64Or(in any, defVal uint64) uint64
  62. func Uint64OrErr(in any) (uint64, error)
  63. func ToUint64(in any) (uint64, error)
  64. func ToUint64With(in any, optFns ...ConvOptionFn[uint64]) (u64 uint64, err error)
  65. func QuietFloat(in any) float64
  66. func SafeFloat(in any) float64
  67. func FloatOrPanic(in any) float64
  68. func MustFloat(in any) float64
  69. func FloatOrDefault(in any, defVal float64) float64
  70. func FloatOr(in any, defVal float64) float64
  71. func Float(in any) (float64, error)
  72. func FloatOrErr(in any) (float64, error)
  73. func ToFloat(in any) (float64, error)
  74. func ToFloatWith(in any, optFns ...ConvOptionFn[float64]) (f64 float64, err error)
  75. func MustString(val any) string
  76. func StringOrPanic(val any) string
  77. func StringOrDefault(val any, defVal string) string
  78. func StringOr(val any, defVal string) string
  79. func ToString(val any) (string, error)
  80. func StringOrErr(val any) (string, error)
  81. func QuietString(val any) string
  82. func String(val any) string
  83. func SafeString(val any) string
  84. func TryToString(val any, defaultAsErr bool) (string, error)
  85. func ToStringWith(in any, optFns ...comfunc.ConvOptionFn) (string, error)
  86. // source at mathutil/format.go
  87. func DataSize(size uint64) string
  88. func HowLongAgo(sec int64) string
  89. // source at mathutil/mathutil.go
  90. func OrElse[T comdef.XintOrFloat](val, defVal T) T
  91. func ZeroOr[T comdef.XintOrFloat](val, defVal T) T
  92. func LessOr[T comdef.XintOrFloat](val, max, devVal T) T
  93. func LteOr[T comdef.XintOrFloat](val, max, devVal T) T
  94. func GreaterOr[T comdef.XintOrFloat](val, min, defVal T) T
  95. func GteOr[T comdef.XintOrFloat](val, min, defVal T) T
  96. func Mul[T1, T2 comdef.XintOrFloat](a T1, b T2) float64
  97. func MulF2i(a, b float64) int
  98. func Div[T1, T2 comdef.XintOrFloat](a T1, b T2) float64
  99. func DivInt[T comdef.Integer](a, b T) int
  100. func DivF2i(a, b float64) int
  101. func Percent(val, total int) float64
  102. // source at mathutil/random.go
  103. func RandomInt(min, max int) int
  104. func RandInt(min, max int) int
  105. func RandIntWithSeed(min, max int, seed int64) int
  106. func RandomIntWithSeed(min, max int, seed int64) int
  107. // source at mathutil/value.go
  108. func New[T comdef.IntOrFloat](v T) *Num[T]

Reflects

Package github.com/gookit/goutil/reflects

  1. // source at reflects/check.go
  2. func HasChild(v reflect.Value) bool
  3. func IsArrayOrSlice(k reflect.Kind) bool
  4. func IsSimpleKind(k reflect.Kind) bool
  5. func IsAnyInt(k reflect.Kind) bool
  6. func IsIntLike(k reflect.Kind) bool
  7. func IsIntx(k reflect.Kind) bool
  8. func IsUintX(k reflect.Kind) bool
  9. func IsNil(v reflect.Value) bool
  10. func CanBeNil(typ reflect.Type) bool
  11. func IsFunc(val any) bool
  12. func IsEqual(src, dst any) bool
  13. func IsEmpty(v reflect.Value) bool
  14. func IsEmptyReal(v reflect.Value) bool
  15. // source at reflects/conv.go
  16. func BaseTypeVal(v reflect.Value) (value any, err error)
  17. func ToBaseVal(v reflect.Value) (value any, err error)
  18. func ConvToType(val any, typ reflect.Type) (rv reflect.Value, err error)
  19. func ValueByType(val any, typ reflect.Type) (rv reflect.Value, err error)
  20. func ValueByKind(val any, kind reflect.Kind) (rv reflect.Value, err error)
  21. func ConvToKind(val any, kind reflect.Kind) (rv reflect.Value, err error)
  22. func ConvSlice(oldSlRv reflect.Value, newElemTyp reflect.Type) (rv reflect.Value, err error)
  23. func String(rv reflect.Value) string
  24. func ToString(rv reflect.Value) (str string, err error)
  25. func ValToString(rv reflect.Value, defaultAsErr bool) (str string, err error)
  26. // source at reflects/func.go
  27. func NewFunc(fn any) *FuncX
  28. func Call2(fn reflect.Value, args []reflect.Value) (reflect.Value, error)
  29. func Call(fn reflect.Value, args []reflect.Value, opt *CallOpt) ([]reflect.Value, error)
  30. func SafeCall2(fun reflect.Value, args []reflect.Value) (val reflect.Value, err error)
  31. func SafeCall(fun reflect.Value, args []reflect.Value) (ret []reflect.Value, err error)
  32. // source at reflects/map.go
  33. func EachMap(mp reflect.Value, fn func(key, val reflect.Value))
  34. func EachStrAnyMap(mp reflect.Value, fn func(key string, val any))
  35. func FlatMap(rv reflect.Value, fn FlatFunc)
  36. // source at reflects/slice.go
  37. func MakeSliceByElem(elTyp reflect.Type, len, cap int) reflect.Value
  38. func FlatSlice(sl reflect.Value, depth int) reflect.Value
  39. // source at reflects/type.go
  40. func ToBaseKind(kind reflect.Kind) BKind
  41. func ToBKind(kind reflect.Kind) BKind
  42. func TypeOf(v any) Type
  43. // source at reflects/util.go
  44. func Elem(v reflect.Value) reflect.Value
  45. func Indirect(v reflect.Value) reflect.Value
  46. func UnwrapAny(v reflect.Value) reflect.Value
  47. func TypeReal(t reflect.Type) reflect.Type
  48. func TypeElem(t reflect.Type) reflect.Type
  49. func Len(v reflect.Value) int
  50. func SliceSubKind(typ reflect.Type) reflect.Kind
  51. func SliceElemKind(typ reflect.Type) reflect.Kind
  52. func UnexportedValue(rv reflect.Value) any
  53. func SetUnexportedValue(rv reflect.Value, value any)
  54. func SetValue(rv reflect.Value, val any) error
  55. func SetRValue(rv, val reflect.Value)
  56. // source at reflects/value.go
  57. func Wrap(rv reflect.Value) Value
  58. func ValueOf(v any) Value

Stdio

Package github.com/gookit/goutil/stdio

  1. // source at stdio/ioutil.go
  2. func QuietFprint(w io.Writer, a ...any)
  3. func QuietFprintf(w io.Writer, tpl string, vs ...any)
  4. func QuietFprintln(w io.Writer, a ...any)
  5. func QuietWriteString(w io.Writer, ss ...string)
  6. // source at stdio/stdio.go
  7. func DiscardReader(src io.Reader)
  8. func ReadString(r io.Reader) string
  9. func MustReadReader(r io.Reader) []byte
  10. func NewIOReader(in any) io.Reader
  11. func NewScanner(in any) *bufio.Scanner
  12. func WriteByte(b byte)
  13. func WriteBytes(bs []byte)
  14. func WritelnBytes(bs []byte)
  15. func WriteString(s string)
  16. func Writeln(s string)
  17. // source at stdio/writer.go
  18. func WrapW(w io.Writer) *WriteWrapper
  19. func NewWriteWrapper(w io.Writer) *WriteWrapper

Structs

Package github.com/gookit/goutil/structs

  1. // source at structs/alias.go
  2. func NewAliases(checker func(alias string)) *Aliases
  3. // source at structs/convert.go
  4. func ToMap(st any, optFns ...MapOptFunc) map[string]any
  5. func MustToMap(st any, optFns ...MapOptFunc) map[string]any
  6. func TryToMap(st any, optFns ...MapOptFunc) (map[string]any, error)
  7. func ToSMap(st any, optFns ...MapOptFunc) map[string]string
  8. func TryToSMap(st any, optFns ...MapOptFunc) (map[string]string, error)
  9. func MustToSMap(st any, optFns ...MapOptFunc) map[string]string
  10. func ToString(st any, optFns ...MapOptFunc) string
  11. func WithMapTagName(tagName string) MapOptFunc
  12. func MergeAnonymous(opt *MapOptions)
  13. func ExportPrivate(opt *MapOptions)
  14. func StructToMap(st any, optFns ...MapOptFunc) (map[string]any, error)
  15. // source at structs/copy.go
  16. func MapStruct(srcSt, dstSt any)
  17. // source at structs/data.go
  18. func NewLiteData(data map[string]any) *Data
  19. func NewData() *Data
  20. func NewOrderedData(cap int) *OrderedData
  21. // source at structs/init.go
  22. func Init(ptr any, optFns ...InitOptFunc) error
  23. func InitDefaults(ptr any, optFns ...InitOptFunc) error
  24. // source at structs/structs.go
  25. func IsExported(name string) bool
  26. func IsUnexported(name string) bool
  27. // source at structs/tags.go
  28. func ParseTags(st any, tagNames []string) (map[string]maputil.SMap, error)
  29. func ParseReflectTags(rt reflect.Type, tagNames []string) (map[string]maputil.SMap, error)
  30. func NewTagParser(tagNames ...string) *TagParser
  31. func ParseTagValueDefault(field, tagVal string) (mp maputil.SMap, err error)
  32. func ParseTagValueQuick(tagVal string, defines []string) maputil.SMap
  33. func ParseTagValueDefine(sep string, defines []string) TagValFunc
  34. func ParseTagValueNamed(field, tagVal string, keys ...string) (mp maputil.SMap, err error)
  35. // source at structs/value.go
  36. func NewValue(val any) *Value
  37. // source at structs/wrapper.go
  38. func Wrap(src any) *Wrapper
  39. func NewWrapper(src any) *Wrapper
  40. func WrapValue(rv reflect.Value) *Wrapper
  41. // source at structs/writer.go
  42. func NewWriter(ptr any) *Wrapper
  43. func WithParseDefault(opt *SetOptions)
  44. func SetValues(ptr any, data map[string]any, optFns ...SetOptFunc) error

Strings

Package github.com/gookit/goutil/strutil

  1. // source at strutil/bytes.go
  2. func NewBuffer() *Buffer
  3. func NewByteChanPool(maxSize, width, capWidth int) *ByteChanPool
  4. // source at strutil/check.go
  5. func IsNumChar(c byte) bool
  6. func IsNumeric(s string) bool
  7. func IsAlphabet(char uint8) bool
  8. func IsAlphaNum(c uint8) bool
  9. func StrPos(s, sub string) int
  10. func BytePos(s string, bt byte) int
  11. func IEqual(s1, s2 string) bool
  12. func NoCaseEq(s, t string) bool
  13. func IContains(s, sub string) bool
  14. func ContainsByte(s string, c byte) bool
  15. func ContainsOne(s string, subs []string) bool
  16. func HasOneSub(s string, subs []string) bool
  17. func ContainsAll(s string, subs []string) bool
  18. func HasAllSubs(s string, subs []string) bool
  19. func IsStartsOf(s string, prefixes []string) bool
  20. func HasOnePrefix(s string, prefixes []string) bool
  21. func HasPrefix(s string, prefix string) bool
  22. func IsStartOf(s, prefix string) bool
  23. func HasSuffix(s string, suffix string) bool
  24. func IsEndOf(s, suffix string) bool
  25. func HasOneSuffix(s string, suffixes []string) bool
  26. func IsValidUtf8(s string) bool
  27. func IsSpace(c byte) bool
  28. func IsEmpty(s string) bool
  29. func IsBlank(s string) bool
  30. func IsNotBlank(s string) bool
  31. func IsBlankBytes(bs []byte) bool
  32. func IsSymbol(r rune) bool
  33. func HasEmpty(ss ...string) bool
  34. func IsAllEmpty(ss ...string) bool
  35. func IsVersion(s string) bool
  36. func Compare(s1, s2, op string) bool
  37. func VersionCompare(v1, v2, op string) bool
  38. func SimpleMatch(s string, keywords []string) bool
  39. func QuickMatch(pattern, s string) bool
  40. func PathMatch(pattern, s string) bool
  41. func GlobMatch(pattern, s string) bool
  42. func LikeMatch(pattern, s string) bool
  43. func MatchNodePath(pattern, s string, sep string) bool
  44. // source at strutil/convbase.go
  45. func Base10Conv(src string, to int) string
  46. func BaseConv(src string, from, to int) string
  47. func BaseConvByTpl(src string, fromBase, toBase string) string
  48. // source at strutil/convert.go
  49. func Quote(s string) string
  50. func Unquote(s string) string
  51. func Join(sep string, ss ...string) string
  52. func JoinList(sep string, ss []string) string
  53. func JoinAny(sep string, parts ...any) string
  54. func Implode(sep string, ss ...string) string
  55. func String(val any) (string, error)
  56. func ToString(val any) (string, error)
  57. func StringOrErr(val any) (string, error)
  58. func QuietString(val any) string
  59. func SafeString(in any) string
  60. func StringOrPanic(val any) string
  61. func MustString(val any) string
  62. func StringOrDefault(val any, defVal string) string
  63. func StringOr(val any, defVal string) string
  64. func AnyToString(val any, defaultAsErr bool) (s string, err error)
  65. func ToStringWith(in any, optFns ...comfunc.ConvOptionFn) (string, error)
  66. func ToBool(s string) (bool, error)
  67. func QuietBool(s string) bool
  68. func SafeBool(s string) bool
  69. func MustBool(s string) bool
  70. func Bool(s string) (bool, error)
  71. func Int(s string) (int, error)
  72. func ToInt(s string) (int, error)
  73. func IntOrDefault(s string, defVal int) int
  74. func IntOr(s string, defVal int) int
  75. func SafeInt(s string) int
  76. func QuietInt(s string) int
  77. func MustInt(s string) int
  78. func IntOrPanic(s string) int
  79. func Int64(s string) int64
  80. func QuietInt64(s string) int64
  81. func SafeInt64(s string) int64
  82. func ToInt64(s string) (int64, error)
  83. func Int64OrDefault(s string, defVal int64) int64
  84. func Int64Or(s string, defVal int64) int64
  85. func Int64OrErr(s string) (int64, error)
  86. func MustInt64(s string) int64
  87. func Int64OrPanic(s string) int64
  88. func Uint(s string) uint64
  89. func SafeUint(s string) uint64
  90. func ToUint(s string) (uint64, error)
  91. func UintOrErr(s string) (uint64, error)
  92. func MustUint(s string) uint64
  93. func UintOrPanic(s string) uint64
  94. func UintOrDefault(s string, defVal uint64) uint64
  95. func UintOr(s string, defVal uint64) uint64
  96. func Byte2str(b []byte) string
  97. func Byte2string(b []byte) string
  98. func ToBytes(s string) (b []byte)
  99. func Ints(s string, sep ...string) []int
  100. func ToInts(s string, sep ...string) ([]int, error)
  101. func ToIntSlice(s string, sep ...string) (ints []int, err error)
  102. func ToArray(s string, sep ...string) []string
  103. func Strings(s string, sep ...string) []string
  104. func ToStrings(s string, sep ...string) []string
  105. func ToSlice(s string, sep ...string) []string
  106. func ToOSArgs(s string) []string
  107. func ToDuration(s string) (time.Duration, error)
  108. // source at strutil/encode.go
  109. func EscapeJS(s string) string
  110. func EscapeHTML(s string) string
  111. func AddSlashes(s string) string
  112. func StripSlashes(s string) string
  113. func URLEncode(s string) string
  114. func URLDecode(s string) string
  115. func B32Encode(str string) string
  116. func B32Decode(str string) string
  117. func B64Encode(str string) string
  118. func B64EncodeBytes(src []byte) []byte
  119. func B64Decode(str string) string
  120. func B64DecodeBytes(str []byte) []byte
  121. // source at strutil/ext.go
  122. func NewComparator(src, dst string) *SimilarComparator
  123. func Similarity(s, t string, rate float32) (float32, bool)
  124. // source at strutil/filter.go
  125. func Trim(s string, cutSet ...string) string
  126. func Ltrim(s string, cutSet ...string) string
  127. func LTrim(s string, cutSet ...string) string
  128. func TrimLeft(s string, cutSet ...string) string
  129. func Rtrim(s string, cutSet ...string) string
  130. func RTrim(s string, cutSet ...string) string
  131. func TrimRight(s string, cutSet ...string) string
  132. func FilterEmail(s string) string
  133. func Filter(ss []string, fls ...comdef.StringMatchFunc) []string
  134. // source at strutil/format.go
  135. func Title(s string) string
  136. func Lower(s string) string
  137. func Lowercase(s string) string
  138. func Upper(s string) string
  139. func Uppercase(s string) string
  140. func UpperWord(s string) string
  141. func LowerFirst(s string) string
  142. func UpperFirst(s string) string
  143. func SnakeCase(s string, sep ...string) string
  144. func Camel(s string, sep ...string) string
  145. func CamelCase(s string, sep ...string) string
  146. func Indent(s, prefix string) string
  147. func IndentBytes(b, prefix []byte) []byte
  148. // source at strutil/gensn.go
  149. func MicroTimeID() string
  150. func MicroTimeHexID() string
  151. func MTimeHexID() string
  152. func MTimeBaseID(toBase int) string
  153. func DatetimeNo(prefix string) string
  154. func DateSN(prefix string) string
  155. func DateSNV2(prefix string, extBase ...int) string
  156. // source at strutil/hash.go
  157. func Md5(src any) string
  158. func MD5(src any) string
  159. func GenMd5(src any) string
  160. func Md5Bytes(src any) []byte
  161. func ShortMd5(src any) string
  162. func HashPasswd(pwd, key string) string
  163. func VerifyPasswd(pwdMAC, pwd, key string) bool
  164. // source at strutil/padding.go
  165. func Padding(s, pad string, length int, pos PosFlag) string
  166. func PadLeft(s, pad string, length int) string
  167. func PadRight(s, pad string, length int) string
  168. func Resize(s string, length int, align PosFlag) string
  169. func PadChars[T byte | rune](cs []T, pad T, length int, pos PosFlag) []T
  170. func PadBytes(bs []byte, pad byte, length int, pos PosFlag) []byte
  171. func PadBytesLeft(bs []byte, pad byte, length int) []byte
  172. func PadBytesRight(bs []byte, pad byte, length int) []byte
  173. func PadRunes(rs []rune, pad rune, length int, pos PosFlag) []rune
  174. func PadRunesLeft(rs []rune, pad rune, length int) []rune
  175. func PadRunesRight(rs []rune, pad rune, length int) []rune
  176. func Repeat(s string, times int) string
  177. func RepeatRune(char rune, times int) []rune
  178. func RepeatBytes(char byte, times int) []byte
  179. func RepeatChars[T byte | rune](char T, times int) []T
  180. // source at strutil/parse.go
  181. func MustToTime(s string, layouts ...string) time.Time
  182. func ToTime(s string, layouts ...string) (t time.Time, err error)
  183. func ParseSizeRange(expr string, opt *ParseSizeOpt) (min, max uint64, err error)
  184. func SafeByteSize(sizeStr string) uint64
  185. func ToByteSize(sizeStr string) (uint64, error)
  186. // source at strutil/random.go
  187. func RandomChars(ln int) string
  188. func RandomCharsV2(ln int) string
  189. func RandomCharsV3(ln int) string
  190. func RandWithTpl(n int, letters string) string
  191. func RandomString(length int) (string, error)
  192. func RandomBytes(length int) ([]byte, error)
  193. // source at strutil/runes.go
  194. func RuneIsWord(c rune) bool
  195. func RuneIsLower(c rune) bool
  196. func RuneIsUpper(c rune) bool
  197. func RunePos(s string, ru rune) int
  198. func IsSpaceRune(r rune) bool
  199. func Utf8Len(s string) int
  200. func Utf8len(s string) int
  201. func RuneCount(s string) int
  202. func RuneWidth(r rune) int
  203. func TextWidth(s string) int
  204. func Utf8Width(s string) int
  205. func RunesWidth(rs []rune) (w int)
  206. func Truncate(s string, w int, tail string) string
  207. func TextTruncate(s string, w int, tail string) string
  208. func Utf8Truncate(s string, w int, tail string) string
  209. func TextSplit(s string, w int) []string
  210. func Utf8Split(s string, w int) []string
  211. func TextWrap(s string, w int) string
  212. func WidthWrap(s string, w int) string
  213. func WordWrap(s string, w int) string
  214. // source at strutil/split.go
  215. func BeforeFirst(s, sep string) string
  216. func AfterFirst(s, sep string) string
  217. func BeforeLast(s, sep string) string
  218. func AfterLast(s, sep string) string
  219. func Cut(s, sep string) (before string, after string, found bool)
  220. func QuietCut(s, sep string) (before string, after string)
  221. func MustCut(s, sep string) (before string, after string)
  222. func TrimCut(s, sep string) (string, string)
  223. func SplitKV(s, sep string) (string, string)
  224. func SplitValid(s, sep string) (ss []string)
  225. func Split(s, sep string) (ss []string)
  226. func SplitNValid(s, sep string, n int) (ss []string)
  227. func SplitN(s, sep string, n int) (ss []string)
  228. func SplitTrimmed(s, sep string) (ss []string)
  229. func SplitNTrimmed(s, sep string, n int) (ss []string)
  230. func Substr(s string, pos, length int) string
  231. func SplitInlineComment(val string, strict ...bool) (string, string)
  232. func FirstLine(output string) string
  233. // source at strutil/strutil.go
  234. func OrCond(cond bool, s1, s2 string) string
  235. func BlankOr(val, defVal string) string
  236. func ZeroOr[T ~string](val, defVal T) T
  237. func ErrorOr(s string, err error, defVal string) string
  238. func OrElse(s, orVal string) string
  239. func OrElseNilSafe(s *string, orVal string) string
  240. func OrHandle(s string, fn comdef.StringHandleFunc) string
  241. func Valid(ss ...string) string
  242. func Replaces(str string, pairs map[string]string) string
  243. func NewReplacer(pairs map[string]string) *strings.Replacer
  244. func WrapTag(s, tag string) string
  245. func SubstrCount(s, substr string, params ...uint64) (int, error)

Syncs

Package github.com/gookit/goutil/syncs

  1. // source at syncs/chan.go
  2. func WaitCloseSignals(onClose func(sig os.Signal))
  3. func Go(f func() error) error
  4. // source at syncs/group.go
  5. func NewCtxErrGroup(ctx context.Context, limit ...int) (*ErrGroup, context.Context)
  6. func NewErrGroup(limit ...int) *ErrGroup
  7. // source at syncs/signal.go
  8. func SignalHandler(ctx context.Context, signals ...os.Signal) (execute func() error, interrupt func(error))

System Utils

Package github.com/gookit/goutil/sysutil

  1. // source at sysutil/exec.go
  2. func NewCmd(bin string, args ...string) *cmdr.Cmd
  3. func FlushExec(bin string, args ...string) error
  4. func QuickExec(cmdLine string, workDir ...string) (string, error)
  5. func ExecLine(cmdLine string, workDir ...string) (string, error)
  6. func ExecCmd(binName string, args []string, workDir ...string) (string, error)
  7. func ShellExec(cmdLine string, shells ...string) (string, error)
  8. // source at sysutil/stack.go
  9. func CallersInfos(skip, num int, filters ...func(file string, fc *runtime.Func) bool) []*CallerInfo
  10. // source at sysutil/sysenv.go
  11. func IsMSys() bool
  12. func IsConsole(out io.Writer) bool
  13. func IsTerminal(fd uintptr) bool
  14. func StdIsTerminal() bool
  15. func Hostname() string
  16. func CurrentShell(onlyName bool) (path string)
  17. func HasShellEnv(shell string) bool
  18. func IsShellSpecialVar(c uint8) bool
  19. func FindExecutable(binName string) (string, error)
  20. func Executable(binName string) (string, error)
  21. func HasExecutable(binName string) bool
  22. func Getenv(name string, def ...string) string
  23. func Environ() map[string]string
  24. func EnvMapWith(newEnv map[string]string) map[string]string
  25. func EnvPaths() []string
  26. func SearchPath(keywords string, limit int) []string
  27. // source at sysutil/sysgo.go
  28. func GoVersion() string
  29. func ParseGoVersion(line string) (*GoInfo, error)
  30. func OsGoInfo() (*GoInfo, error)
  31. // source at sysutil/sysutil.go
  32. func Workdir() string
  33. func BinDir() string
  34. func BinName() string
  35. func BinFile() string
  36. func Open(fileOrURL string) error
  37. func OpenBrowser(fileOrURL string) error
  38. func OpenFile(path string) error
  39. // source at sysutil/sysutil_nonwin.go
  40. func Kill(pid int, signal syscall.Signal) error
  41. func ProcessExists(pid int) bool
  42. // source at sysutil/sysutil_unix.go
  43. func IsWin() bool
  44. func IsWindows() bool
  45. func IsMac() bool
  46. func IsDarwin() bool
  47. func IsLinux() bool
  48. func OpenURL(URL string) error
  49. // source at sysutil/user.go
  50. func MustFindUser(uname string) *user.User
  51. func LoginUser() *user.User
  52. func CurrentUser() *user.User
  53. func UHomeDir() string
  54. func UserHomeDir() string
  55. func HomeDir() string
  56. func UserDir(subPath string) string
  57. func UserCacheDir(subPath string) string
  58. func UserConfigDir(subPath string) string
  59. func ExpandPath(path string) string
  60. func ExpandHome(path string) string
  61. // source at sysutil/user_nonwin.go
  62. func ChangeUserByName(newUname string) error
  63. func ChangeUserUidGid(newUID int, newGid int) error
  64. func ChangeUserUIDGid(newUID int, newGid int) (err error)

Testing Utils

Package github.com/gookit/goutil/testutil

  1. // source at testutil/buffer.go
  2. func NewBuffer() *byteutil.Buffer
  3. // source at testutil/envmock.go
  4. func MockEnvValue(key, val string, fn func(nv string))
  5. func MockEnvValues(kvMap map[string]string, fn func())
  6. func MockOsEnvByText(envText string, fn func())
  7. func MockOsEnv(mp map[string]string, fn func())
  8. func ClearOSEnv()
  9. func RevertOSEnv()
  10. func MockCleanOsEnv(mp map[string]string, fn func())
  11. // source at testutil/httpmock.go
  12. func NewHttpRequest(method, path string, data *MD) *http.Request
  13. func NewHTTPRequest(method, path string, data *MD) *http.Request
  14. func MockRequest(h http.Handler, method, path string, data *MD) *httptest.ResponseRecorder
  15. func TestMain(m *testing.M)
  16. func NewEchoServer() *httptest.Server
  17. func BuildEchoReply(r *http.Request) *EchoReply
  18. func ParseRespToReply(w *http.Response) *EchoReply
  19. func ParseBodyToReply(bd io.ReadCloser) *EchoReply
  20. // source at testutil/testutil.go
  21. func DiscardStdout() error
  22. func ReadOutput() (s string)
  23. func RewriteStdout()
  24. func RestoreStdout(printData ...bool) (s string)
  25. func RewriteStderr()
  26. func RestoreStderr(printData ...bool) (s string)
  27. func SetTimeLocal(tl *time.Location)
  28. func SetTimeLocalUTC()
  29. func RestoreTimeLocal()
  30. // source at testutil/writer.go
  31. func NewTestWriter() *TestWriter
  32. func NewDirEnt(fpath string, isDir ...bool) *fakeobj.DirEntry

Timex

Package github.com/gookit/goutil/timex

Provides an enhanced time.Time implementation, and add more commonly used functional methods.

  1. // source at timex/check.go
  2. func IsDuration(s string) bool
  3. func InRange(dst, start, end time.Time) bool
  4. // source at timex/conv.go
  5. func Elapsed(start, end time.Time) string
  6. func ElapsedNow(start time.Time) string
  7. func FromNow(t time.Time) string
  8. func FromNowWith(u time.Time, tms []TimeMessage) string
  9. func HowLongAgo(diffSec int64) string
  10. func HowLongAgo2(diffSec int64, tms []TimeMessage) string
  11. func ToTime(s string, layouts ...string) (time.Time, error)
  12. func ToDur(s string) (time.Duration, error)
  13. func ToDuration(s string) (time.Duration, error)
  14. func TryToTime(s string, bt time.Time) (time.Time, error)
  15. func ParseRange(expr string, opt *ParseRangeOpt) (start, end time.Time, err error)
  16. // source at timex/gotime.go
  17. func SetLocalByName(tzName string) error
  18. func NowAddDay(day int) time.Time
  19. func NowAddHour(hour int) time.Time
  20. func NowAddMinutes(minutes int) time.Time
  21. func NowAddSec(seconds int) time.Time
  22. func NowAddSeconds(seconds int) time.Time
  23. func NowHourStart() time.Time
  24. func NowHourEnd() time.Time
  25. func AddDay(t time.Time, day int) time.Time
  26. func AddHour(t time.Time, hour int) time.Time
  27. func AddMinutes(t time.Time, minutes int) time.Time
  28. func AddSeconds(t time.Time, seconds int) time.Time
  29. func AddSec(t time.Time, seconds int) time.Time
  30. func HourStart(t time.Time) time.Time
  31. func HourEnd(t time.Time) time.Time
  32. func DayStart(t time.Time) time.Time
  33. func DayEnd(t time.Time) time.Time
  34. func TodayStart() time.Time
  35. func TodayEnd() time.Time
  36. // source at timex/template.go
  37. func ToLayout(template string) string
  38. // source at timex/timex.go
  39. func Now() *Time
  40. func New(t time.Time) *Time
  41. func Wrap(t time.Time) *Time
  42. func FromTime(t time.Time) *Time
  43. func Local() *Time
  44. func FromUnix(sec int64) *Time
  45. func FromDate(s string, template ...string) (*Time, error)
  46. func FromString(s string, layouts ...string) (*Time, error)
  47. func LocalByName(tzName string) *Time
  48. // source at timex/util.go
  49. func NowUnix() int64
  50. func NowDate(template ...string) string
  51. func Format(t time.Time) string
  52. func FormatBy(t time.Time, layout string) string
  53. func Date(t time.Time, template ...string) string
  54. func Datetime(t time.Time, template ...string) string
  55. func DateFormat(t time.Time, template string) string
  56. func FormatByTpl(t time.Time, template string) string
  57. func FormatUnix(sec int64, layout ...string) string
  58. func FormatUnixBy(sec int64, layout string) string
  59. func FormatUnixByTpl(sec int64, template ...string) string

Timex Usage

Create timex instance

  1. now := timex.Now()
  2. // from time.Time
  3. tx := timex.New(time.Now())
  4. tx := timex.FromTime(time.Now())
  5. // from time unix
  6. tx := timex.FromUnix(1647411580)

Create from datetime string:

  1. // auto match layout by datetime
  2. tx, err := timex.FromString("2022-04-20 19:40:34")
  3. // custom set the datetime layout
  4. tx, err := timex.FromString("2022-04-20 19:40:34", "2006-01-02 15:04:05")
  5. // use date template as layout
  6. tx, err := timex.FromDate("2022-04-20 19:40:34", "Y-m-d H:I:S")

Use timex instance

  1. tx := timex.Now()

change time:

  1. tx.Yesterday()
  2. tx.Tomorrow()
  3. tx.DayStart() // get time at Y-m-d 00:00:00
  4. tx.DayEnd() // get time at Y-m-d 23:59:59
  5. tx.HourStart() // get time at Y-m-d H:00:00
  6. tx.HourEnd() // get time at Y-m-d H:59:59
  7. tx.AddDay(2)
  8. tx.AddHour(1)
  9. tx.AddMinutes(15)
  10. tx.AddSeconds(120)

compare time:

  1. // before compare
  2. tx.IsBefore(u time.Time)
  3. tx.IsBeforeUnix(1647411580)
  4. // after compare
  5. tx.IsAfter(u time.Time)
  6. tx.IsAfterUnix(1647411580)

Helper functions

  1. ts := timex.NowUnix() // current unix timestamp
  2. t := NowAddDay(1) // from now add 1 day
  3. t := NowAddHour(1) // from now add 1 hour
  4. t := NowAddMinutes(3) // from now add 3 minutes
  5. t := NowAddSeconds(180) // from now add 180 seconds

Convert time to date by template

Template Chars:

  1. Y,y - year
  2. Y - year 2006
  3. y - year 06
  4. m - month 01-12
  5. d - day 01-31
  6. H,h - hour
  7. H - hour 00-23
  8. h - hour 01-12
  9. I,i - minute
  10. I - minute 00-59
  11. i - minute 0-59
  12. S,s - second
  13. S - second 00-59
  14. s - second 0-59

More, please see char map

Examples, use timex:

  1. tx := timex.Now()
  2. date := tx.DateFormat("Y-m-d H:I:S") // Output: 2022-04-20 19:09:03
  3. date = tx.DateFormat("y-m-d h:i:s") // Output: 22-04-20 07:9:3

Format time.Time:

  1. tx := time.Now()
  2. date := timex.DateFormat(tx, "Y-m-d H:I:S") // Output: 2022-04-20 19:40:34

More usage:

  1. ts := timex.NowUnix() // current unix timestamp
  2. date := FormatUnix(ts, "2006-01-02 15:04:05") // Get: 2022-04-20 19:40:34
  3. date := FormatUnixByTpl(ts, "Y-m-d H:I:S") // Get: 2022-04-20 19:40:34

Code Check & Testing

  1. gofmt -w -l ./
  2. golint ./...
  3. # testing
  4. go test -v ./...
  5. go test -v -run ^TestErr$
  6. go test -v -run ^TestErr$ ./testutil/assert/...

Testing in docker:

  1. cd goutil
  2. docker run -ti -v $(pwd):/go/work golang:1.18
  3. root@xx:/go/work# go test ./...

Gookit packages

  • gookit/ini Go config management, use INI files
  • gookit/rux Simple and fast request router for golang HTTP
  • gookit/gcli Build CLI application, tool library, running CLI commands
  • gookit/slog Lightweight, easy to extend, configurable logging library written in Go
  • gookit/color A command-line color library with true color support, universal API methods and Windows support
  • gookit/event Lightweight event manager and dispatcher implements by Go
  • gookit/cache Generic cache use and cache manager for golang. support File, Memory, Redis, Memcached.
  • gookit/config Go config management. support JSON, YAML, TOML, INI, HCL, ENV and Flags
  • gookit/filter Provide filtering, sanitizing, and conversion of golang data
  • gookit/validate Use for data validation and filtering. support Map, Struct, Form data
  • gookit/goutil Some utils for the Go: string, array/slice, map, format, cli, env, filesystem, test and more
  • More, please see https://github.com/gookit

License

MIT