diff --git a/README.md b/README.md index 1c5a63d6a..ec01faa9e 100644 --- a/README.md +++ b/README.md @@ -88,48 +88,48 @@ u64Val = goutil.Uint("2") // 2 ```go // source at arrutil/arrutil.go -func Reverse(ss []string) -func StringsRemove(ss []string, s string) []string -func StringsFilter(ss []string, filter ...func(s string) bool) []string -func StringsMap(ss []string, mapFn func(s string) string) []string -func TrimStrings(ss []string, cutSet ...string) []string +func Reverse(ss []string) +func StringsRemove(ss []string, s string) []string +func StringsFilter(ss []string, filter ...func(s string) bool) []string +func StringsMap(ss []string, mapFn func(s string) string) []string +func TrimStrings(ss []string, cutSet ...string) []string // source at arrutil/check.go -func IntsHas(ints []int, val int) bool -func Int64sHas(ints []int64, val int64) bool -func InStrings(elem string, ss []string) bool { return StringsHas(ss, elem) } -func StringsHas(ss []string, val string) bool -func HasValue(arr, val any) bool -func Contains(arr, val any) bool -func NotContains(arr, val any) bool +func IntsHas(ints []int, val int) bool +func Int64sHas(ints []int64, val int64) bool +func InStrings(elem string, ss []string) bool +func StringsHas(ss []string, val string) bool +func HasValue(arr, val any) bool +func Contains(arr, val any) bool +func NotContains(arr, val any) bool // source at arrutil/collection.go -func TwowaySearch(data any, item any, fn Comparer) (int, error) -func MakeEmptySlice(itemType reflect.Type) any -func CloneSlice(data any) any -func Excepts(first, second any, fn Comparer) any -func Intersects(first any, second any, fn Comparer) any -func Union(first, second any, fn Comparer) any -func Find(source any, fn Predicate) (any, error) -func FindOrDefault(source any, fn Predicate, defaultValue any) any -func TakeWhile(data any, fn Predicate) any -func ExceptWhile(data any, fn Predicate) any +func TwowaySearch(data any, item any, fn Comparer) (int, error) +func MakeEmptySlice(itemType reflect.Type) any +func CloneSlice(data any) any +func Excepts(first, second any, fn Comparer) any +func Intersects(first any, second any, fn Comparer) any +func Union(first, second any, fn Comparer) any +func Find(source any, fn Predicate) (any, error) +func FindOrDefault(source any, fn Predicate, defaultValue any) any +func TakeWhile(data any, fn Predicate) any +func ExceptWhile(data any, fn Predicate) any // source at arrutil/convert.go -func JoinStrings(sep string, ss ...string) string -func StringsJoin(sep string, ss ...string) string -func StringsToInts(ss []string) (ints []int, err error) -func MustToStrings(arr any) []string -func StringsToSlice(ss []string) []any -func ToInt64s(arr any) (ret []int64, err error) -func MustToInt64s(arr any) []int64 -func SliceToInt64s(arr []any) []int64 -func ToStrings(arr any) (ret []string, err error) -func SliceToStrings(arr []any) []string -func AnyToString(arr any) string -func SliceToString(arr ...any) string { return ToString(arr) } -func ToString(arr []any) string -func JoinSlice(sep string, arr ...any) string +func JoinStrings(sep string, ss ...string) string +func StringsJoin(sep string, ss ...string) string +func StringsToInts(ss []string) (ints []int, err error) +func MustToStrings(arr any) []string +func StringsToSlice(ss []string) []any +func ToInt64s(arr any) (ret []int64, err error) +func MustToInt64s(arr any) []int64 +func SliceToInt64s(arr []any) []int64 +func ToStrings(arr any) (ret []string, err error) +func SliceToStrings(arr []any) []string +func AnyToString(arr any) string +func SliceToString(arr ...any) string +func ToString(arr []any) string +func JoinSlice(sep string, arr ...any) string // source at arrutil/format.go -func NewFormatter(arr any) *ArrFormatter -func FormatIndent(arr any, indent string) string +func NewFormatter(arr any) *ArrFormatter +func FormatIndent(arr any, indent string) string ``` #### ArrUtil Usage @@ -159,13 +159,13 @@ ss, err := arrutil.ToStrings([]int{1, 2}) // ss: []string{"1", "2"} ```go // source at byteutil/buffer.go -func NewBuffer() *Buffer +func NewBuffer() *Buffer // source at byteutil/bytex.go -func Md5(src any) []byte +func Md5(src any) []byte // source at byteutil/encoder.go -func NewStdEncoder(encFn func(src []byte) []byte, decFn func(src []byte) ([]byte, error)) *StdEncoder +func NewStdEncoder(encFn func(src []byte) []byte, decFn func(src []byte) ([]byte, error)) *StdEncoder // source at byteutil/pool.go -func NewChanPool(maxSize int, width int, capWidth int) *ChanPool +func NewChanPool(maxSize int, width int, capWidth int) *ChanPool ``` ### Cflag @@ -174,26 +174,26 @@ func NewChanPool(maxSize int, width int, capWidth int) *ChanPool ```go // source at cflag/app.go -func NewApp(fns ...func(app *App)) *App -func NewCmd(name, desc string) *Cmd +func NewApp(fns ...func(app *App)) *App +func NewCmd(name, desc string) *Cmd // source at cflag/cflag.go -func SetDebug(open bool) -func New(fns ...func(c *CFlags)) *CFlags -func NewEmpty(fns ...func(c *CFlags)) *CFlags -func WithDesc(desc string) func(c *CFlags) -func WithVersion(version string) func(c *CFlags) +func SetDebug(open bool) +func New(fns ...func(c *CFlags)) *CFlags +func NewEmpty(fns ...func(c *CFlags)) *CFlags +func WithDesc(desc string) func(c *CFlags) +func WithVersion(version string) func(c *CFlags) // source at cflag/optarg.go -func NewArg(name, desc string, required bool) *FlagArg +func NewArg(name, desc string, required bool) *FlagArg // source at cflag/util.go -func IsZeroValue(opt *flag.Flag, value string) (bool, bool) -func AddPrefix(name string) string -func AddPrefixes(name string, shorts []string) string -func AddPrefixes2(name string, shorts []string, nameAtEnd bool) string -func SplitShortcut(shortcut string) []string -func FilterNames(names []string) []string -func IsFlagHelpErr(err error) bool -func WrapColorForCode(s string) string -func ReplaceShorts(args []string, shortsMap map[string]string) []string +func IsZeroValue(opt *flag.Flag, value string) (bool, bool) +func AddPrefix(name string) string +func AddPrefixes(name string, shorts []string) string +func AddPrefixes2(name string, shorts []string, nameAtEnd bool) string +func SplitShortcut(shortcut string) []string +func FilterNames(names []string) []string +func IsFlagHelpErr(err error) bool +func WrapColorForCode(s string) string +func ReplaceShorts(args []string, shortsMap map[string]string) []string ``` #### `cflag` Usage @@ -206,71 +206,71 @@ func ReplaceShorts(args []string, shortsMap map[string]string) []string ```go // source at cliutil/cliutil.go -func LineBuild(binFile string, args []string) string -func BuildLine(binFile string, args []string) string -func String2OSArgs(line string) []string -func StringToOSArgs(line string) []string -func ParseLine(line string) []string -func QuickExec(cmdLine string, workDir ...string) (string, error) -func ExecLine(cmdLine string, workDir ...string) (string, error) -func ExecCmd(binName string, args []string, workDir ...string) (string, error) -func ExecCommand(binName string, args []string, workDir ...string) (string, error) -func ShellExec(cmdLine string, shells ...string) (string, error) -func CurrentShell(onlyName bool) (path string) -func HasShellEnv(shell string) bool -func BuildOptionHelpName(names []string) string -func ShellQuote(s string) string -func OutputLines(output string) []string -func FirstLine(output string) string +func LineBuild(binFile string, args []string) string +func BuildLine(binFile string, args []string) string +func String2OSArgs(line string) []string +func StringToOSArgs(line string) []string +func ParseLine(line string) []string +func QuickExec(cmdLine string, workDir ...string) (string, error) +func ExecLine(cmdLine string, workDir ...string) (string, error) +func ExecCmd(binName string, args []string, workDir ...string) (string, error) +func ExecCommand(binName string, args []string, workDir ...string) (string, error) +func ShellExec(cmdLine string, shells ...string) (string, error) +func CurrentShell(onlyName bool) (path string) +func HasShellEnv(shell string) bool +func BuildOptionHelpName(names []string) string +func ShellQuote(s string) string +func OutputLines(output string) []string +func FirstLine(output string) string // source at cliutil/color_print.go -func Redp(a ...any) { color.Red.Print(a...) } -func Redf(format string, a ...any) { color.Red.Printf(format, a...) } -func Redln(a ...any) { color.Red.Println(a...) } -func Bluep(a ...any) { color.Blue.Print(a...) } -func Bluef(format string, a ...any) { color.Blue.Printf(format, a...) } -func Blueln(a ...any) { color.Blue.Println(a...) } -func Cyanp(a ...any) { color.Cyan.Print(a...) } -func Cyanf(format string, a ...any) { color.Cyan.Printf(format, a...) } -func Cyanln(a ...any) { color.Cyan.Println(a...) } -func Grayp(a ...any) { color.Gray.Print(a...) } -func Grayf(format string, a ...any) { color.Gray.Printf(format, a...) } -func Grayln(a ...any) { color.Gray.Println(a...) } -func Greenp(a ...any) { color.Green.Print(a...) } -func Greenf(format string, a ...any) { color.Green.Printf(format, a...) } -func Greenln(a ...any) { color.Green.Println(a...) } -func Yellowp(a ...any) { color.Yellow.Print(a...) } -func Yellowf(format string, a ...any) { color.Yellow.Printf(format, a...) } -func Yellowln(a ...any) { color.Yellow.Println(a...) } -func Magentap(a ...any) { color.Magenta.Print(a...) } -func Magentaf(format string, a ...any) { color.Magenta.Printf(format, a...) } -func Magentaln(a ...any) { color.Magenta.Println(a...) } -func Infop(a ...any) { color.Info.Print(a...) } -func Infof(format string, a ...any) { color.Info.Printf(format, a...) } -func Infoln(a ...any) { color.Info.Println(a...) } -func Successp(a ...any) { color.Success.Print(a...) } -func Successf(format string, a ...any) { color.Success.Printf(format, a...) } -func Successln(a ...any) { color.Success.Println(a...) } -func Errorp(a ...any) { color.Error.Print(a...) } -func Errorf(format string, a ...any) { color.Error.Printf(format, a...) } -func Errorln(a ...any) { color.Error.Println(a...) } -func Warnp(a ...any) { color.Warn.Print(a...) } -func Warnf(format string, a ...any) { color.Warn.Printf(format, a...) } -func Warnln(a ...any) { color.Warn.Println(a...) } +func Redp(a ...any) +func Redf(format string, a ...any) +func Redln(a ...any) +func Bluep(a ...any) +func Bluef(format string, a ...any) +func Blueln(a ...any) +func Cyanp(a ...any) +func Cyanf(format string, a ...any) +func Cyanln(a ...any) +func Grayp(a ...any) +func Grayf(format string, a ...any) +func Grayln(a ...any) +func Greenp(a ...any) +func Greenf(format string, a ...any) +func Greenln(a ...any) +func Yellowp(a ...any) +func Yellowf(format string, a ...any) +func Yellowln(a ...any) +func Magentap(a ...any) +func Magentaf(format string, a ...any) +func Magentaln(a ...any) +func Infop(a ...any) +func Infof(format string, a ...any) +func Infoln(a ...any) +func Successp(a ...any) +func Successf(format string, a ...any) +func Successln(a ...any) +func Errorp(a ...any) +func Errorf(format string, a ...any) +func Errorln(a ...any) +func Warnp(a ...any) +func Warnf(format string, a ...any) +func Warnln(a ...any) // source at cliutil/info.go -func Workdir() string -func BinDir() string -func BinFile() string -func BinName() string -func GetTermSize(refresh ...bool) (w int, h int) +func Workdir() string +func BinDir() string +func BinFile() string +func BinName() string +func GetTermSize(refresh ...bool) (w int, h int) // source at cliutil/read.go -func ReadInput(question string) (string, error) -func ReadLine(question string) (string, error) -func ReadFirst(question string) (string, error) -func ReadFirstByte(question string) (byte, error) -func ReadFirstRune(question string) (rune, error) -func ReadPassword(question ...string) string -func InputIsYes(ans string) bool -func ByteIsYes(ans byte) bool +func ReadInput(question string) (string, error) +func ReadLine(question string) (string, error) +func ReadFirst(question string) (string, error) +func ReadFirstByte(question string) (byte, error) +func ReadFirstRune(question string) (rune, error) +func ReadPassword(question ...string) string +func InputIsYes(ans string) bool +func ByteIsYes(ans byte) bool ``` #### CLI Util Usage @@ -334,19 +334,30 @@ Build line: ./myapp -a val0 -m "this is message" arg0 ```go // source at dump/dump.go -func Std() *Dumper -func Reset() -func Config(fn func(opts *Options)) -func Print(vs ...any) -func Println(vs ...any) -func Fprint(w io.Writer, vs ...any) -func Format(vs ...any) string -func NoLoc(vs ...any) -func Clear(vs ...any) +func Std() *Dumper +func Reset() +func Config(fns ...OptionFunc) +func Print(vs ...any) +func Println(vs ...any) +func Fprint(w io.Writer, vs ...any) +func Std2() *Dumper +func Reset2() +func Format(vs ...any) string +func NoLoc(vs ...any) +func Clear(vs ...any) // source at dump/dumper.go -func NewDumper(out io.Writer, skip int) *Dumper -func NewWithOptions(fn func(opts *Options)) *Dumper -func NewDefaultOptions(out io.Writer, skip int) *Options +func NewDumper(out io.Writer, skip int) *Dumper +func NewWithOptions(fns ...OptionFunc) *Dumper +// source at dump/options.go +func NewDefaultOptions(out io.Writer, skip int) *Options +func SkipNilField() OptionFunc +func SkipPrivate() OptionFunc +func BytesAsString() OptionFunc +func WithCallerSkip(skip int) OptionFunc +func WithoutPosition() OptionFunc +func WithoutOutput(out io.Writer) OptionFunc +func WithoutColor() OptionFunc +func WithoutType() OptionFunc ``` #### Examples @@ -398,31 +409,31 @@ Preview: ```go // source at envutil/envutil.go -func VarReplace(s string) string { return os.ExpandEnv(s) } -func VarParse(val string) string -func ParseEnvValue(val string) string -func ParseValue(val string) (newVal string) -func SetEnvs(mp map[string]string) +func VarReplace(s string) string +func VarParse(val string) string +func ParseEnvValue(val string) string +func ParseValue(val string) (newVal string) +func SetEnvs(mp map[string]string) // source at envutil/get.go -func Getenv(name string, def ...string) string -func GetInt(name string, def ...int) int -func GetBool(name string, def ...bool) bool -func Environ() map[string]string +func Getenv(name string, def ...string) string +func GetInt(name string, def ...int) int +func GetBool(name string, def ...bool) bool +func Environ() map[string]string // source at envutil/info.go -func IsWin() bool -func IsWindows() bool -func IsMac() bool -func IsLinux() bool -func IsMSys() bool -func IsWSL() bool -func IsTerminal(fd uintptr) bool -func StdIsTerminal() bool -func IsConsole(out io.Writer) bool -func HasShellEnv(shell string) bool -func IsSupportColor() bool -func IsSupport256Color() bool -func IsSupportTrueColor() bool -func IsGithubActions() bool +func IsWin() bool +func IsWindows() bool +func IsMac() bool +func IsLinux() bool +func IsMSys() bool +func IsWSL() bool +func IsTerminal(fd uintptr) bool +func StdIsTerminal() bool +func IsConsole(out io.Writer) bool +func HasShellEnv(shell string) bool +func IsSupportColor() bool +func IsSupport256Color() bool +func IsSupportTrueColor() bool +func IsGithubActions() bool ``` #### ENV Util Usage @@ -452,40 +463,40 @@ Package errorx provide a enhanced error implements, allow with call stack and wr ```go // source at errorx/errors.go -func NewR(code int, msg string) ErrorR -func Fail(code int, msg string) ErrorR -func Suc(msg string) ErrorR +func NewR(code int, msg string) ErrorR +func Fail(code int, msg string) ErrorR +func Suc(msg string) ErrorR // source at errorx/errorx.go -func New(msg string) error -func Newf(tpl string, vars ...any) error -func Errorf(tpl string, vars ...any) error -func With(err error, msg string) error -func Withf(err error, tpl string, vars ...any) error -func WithPrev(err error, msg string) error -func WithPrevf(err error, tpl string, vars ...any) error -func WithStack(err error) error -func Traced(err error) error -func Stacked(err error) error -func WithOptions(msg string, fns ...func(opt *ErrStackOpt)) error -func Wrap(err error, msg string) error -func Wrapf(err error, tpl string, vars ...any) error +func New(msg string) error +func Newf(tpl string, vars ...any) error +func Errorf(tpl string, vars ...any) error +func With(err error, msg string) error +func Withf(err error, tpl string, vars ...any) error +func WithPrev(err error, msg string) error +func WithPrevf(err error, tpl string, vars ...any) error +func WithStack(err error) error +func Traced(err error) error +func Stacked(err error) error +func WithOptions(msg string, fns ...func(opt *ErrStackOpt)) error +func Wrap(err error, msg string) error +func Wrapf(err error, tpl string, vars ...any) error // source at errorx/stack.go -func FuncForPC(pc uintptr) *Func -func ResetStdOpt() -func Config(fns ...func(opt *ErrStackOpt)) -func SkipDepth(skipDepth int) func(opt *ErrStackOpt) -func TraceDepth(traceDepth int) func(opt *ErrStackOpt) +func FuncForPC(pc uintptr) *Func +func ResetStdOpt() +func Config(fns ...func(opt *ErrStackOpt)) +func SkipDepth(skipDepth int) func(opt *ErrStackOpt) +func TraceDepth(traceDepth int) func(opt *ErrStackOpt) // source at errorx/util.go -func Raw(msg string) error -func Rawf(tpl string, vars ...any) error -func Cause(err error) error -func Unwrap(err error) error -func Previous(err error) error { return Unwrap(err) } -func ToErrorX(err error) (ex *ErrorX, ok bool) -func Has(err, target error) bool -func Is(err, target error) bool -func To(err error, target any) bool -func As(err error, target any) bool +func Raw(msg string) error +func Rawf(tpl string, vars ...any) error +func Cause(err error) error +func Unwrap(err error) error +func Previous(err error) error +func ToErrorX(err error) (ex *ErrorX, ok bool) +func Has(err, target error) bool +func Is(err, target error) bool +func To(err error, target any) bool +func As(err error, target any) bool ``` #### Errorx Usage @@ -570,15 +581,15 @@ runtime.goexit() ```go // source at fmtutil/format.go -func DataSize(size uint64) string -func SizeToString(size uint64) string { return DataSize(size) } -func StringToByte(sizeStr string) uint64 { return ParseByte(sizeStr) } -func ParseByte(sizeStr string) uint64 -func PrettyJSON(v any) (string, error) -func StringsToInts(ss []string) (ints []int, err error) -func ArgsWithSpaces(args []any) (message string) +func DataSize(size uint64) string +func SizeToString(size uint64) string +func StringToByte(sizeStr string) uint64 +func ParseByte(sizeStr string) uint64 +func PrettyJSON(v any) (string, error) +func StringsToInts(ss []string) (ints []int, err error) +func ArgsWithSpaces(args []any) (message string) // source at fmtutil/time.go -func HowLongAgo(sec int64) string +func HowLongAgo(sec int64) string ``` ### File System @@ -587,57 +598,57 @@ func HowLongAgo(sec int64) string ```go // source at fsutil/check.go -func PathExists(path string) bool -func IsDir(path string) bool -func FileExists(path string) bool -func IsFile(path string) bool -func IsAbsPath(aPath string) bool -func IsImageFile(path string) bool -func IsZipFile(filepath string) bool +func PathExists(path string) bool +func IsDir(path string) bool +func FileExists(path string) bool +func IsFile(path string) bool +func IsAbsPath(aPath string) bool +func IsImageFile(path string) bool +func IsZipFile(filepath string) bool // source at fsutil/fsutil.go -func OSTempFile(pattern string) (*os.File, error) -func TempFile(dir, pattern string) (*os.File, error) -func OSTempDir(pattern string) (string, error) -func TempDir(dir, pattern string) (string, error) -func MimeType(path string) (mime string) -func ReaderMimeType(r io.Reader) (mime string) +func OSTempFile(pattern string) (*os.File, error) +func TempFile(dir, pattern string) (*os.File, error) +func OSTempDir(pattern string) (string, error) +func TempDir(dir, pattern string) (string, error) +func MimeType(path string) (mime string) +func ReaderMimeType(r io.Reader) (mime string) // source at fsutil/info.go -func Dir(fpath string) string -func PathName(fpath string) string -func Name(fpath string) string -func FileExt(fpath string) string -func Suffix(fpath string) string -func Expand(pathStr string) string -func ExpandPath(pathStr string) string -func Realpath(pathStr string) string -func SplitPath(pathStr string) (dir, name string) -func GlobWithFunc(pattern string, fn func(filePath string) error) (err error) -func FindInDir(dir string, handleFn HandleFunc, filters ...FilterFunc) (e error) +func Dir(fpath string) string +func PathName(fpath string) string +func Name(fpath string) string +func FileExt(fpath string) string +func Suffix(fpath string) string +func Expand(pathStr string) string +func ExpandPath(pathStr string) string +func Realpath(pathStr string) string +func SplitPath(pathStr string) (dir, name string) +func GlobWithFunc(pattern string, fn func(filePath string) error) (err error) +func FindInDir(dir string, handleFn HandleFunc, filters ...FilterFunc) (e error) // source at fsutil/operate.go -func Mkdir(dirPath string, perm os.FileMode) error -func MkParentDir(fpath string) error -func DiscardReader(src io.Reader) -func MustReadFile(filePath string) []byte -func MustReadReader(r io.Reader) []byte -func GetContents(in any) []byte -func ReadExistFile(filePath string) []byte -func OpenFile(filepath string, flag int, perm os.FileMode) (*os.File, error) -func QuickOpenFile(filepath string, fileFlag ...int) (*os.File, error) -func OpenReadFile(filepath string) (*os.File, error) -func CreateFile(fpath string, filePerm, dirPerm os.FileMode, fileFlag ...int) (*os.File, error) -func MustCreateFile(filePath string, filePerm, dirPerm os.FileMode) *os.File -func PutContents(filePath string, data any, fileFlag ...int) (int, error) -func WriteFile(filePath string, data any, perm os.FileMode, fileFlag ...int) error -func CopyFile(srcPath, dstPath string) error -func MustCopyFile(srcPath, dstPath string) -func Remove(fPath string) error -func MustRemove(fPath string) -func QuietRemove(fPath string) { _ = os.Remove(fPath) } -func RmIfExist(fPath string) error { return DeleteIfExist(fPath) } -func DeleteIfExist(fPath string) error -func RmFileIfExist(fPath string) error { return DeleteIfFileExist(fPath) } -func DeleteIfFileExist(fPath string) error -func Unzip(archive, targetDir string) (err error) +func Mkdir(dirPath string, perm os.FileMode) error +func MkParentDir(fpath string) error +func DiscardReader(src io.Reader) +func MustReadFile(filePath string) []byte +func MustReadReader(r io.Reader) []byte +func GetContents(in any) []byte +func ReadExistFile(filePath string) []byte +func OpenFile(filepath string, flag int, perm os.FileMode) (*os.File, error) +func QuickOpenFile(filepath string, fileFlag ...int) (*os.File, error) +func OpenReadFile(filepath string) (*os.File, error) +func CreateFile(fpath string, filePerm, dirPerm os.FileMode, fileFlag ...int) (*os.File, error) +func MustCreateFile(filePath string, filePerm, dirPerm os.FileMode) *os.File +func PutContents(filePath string, data any, fileFlag ...int) (int, error) +func WriteFile(filePath string, data any, perm os.FileMode, fileFlag ...int) error +func CopyFile(srcPath, dstPath string) error +func MustCopyFile(srcPath, dstPath string) +func Remove(fPath string) error +func MustRemove(fPath string) +func QuietRemove(fPath string) +func RmIfExist(fPath string) error +func DeleteIfExist(fPath string) error +func RmFileIfExist(fPath string) error +func DeleteIfFileExist(fPath string) error +func Unzip(archive, targetDir string) (err error) ``` #### FsUtil Usage @@ -683,18 +694,18 @@ func main() { ```go // source at jsonutil/jsonutil.go -func WriteFile(filePath string, data any) error -func ReadFile(filePath string, v any) error -func Pretty(v any) (string, error) -func Encode(v any) ([]byte, error) -func EncodePretty(v any) ([]byte, error) -func EncodeToWriter(v any, w io.Writer) error -func EncodeUnescapeHTML(v any) ([]byte, error) -func Decode(bts []byte, ptr any) error -func DecodeString(str string, ptr any) error -func DecodeReader(r io.Reader, ptr any) error -func Mapping(src, dst any) error -func StripComments(src string) string +func WriteFile(filePath string, data any) error +func ReadFile(filePath string, v any) error +func Pretty(v any) (string, error) +func Encode(v any) ([]byte, error) +func EncodePretty(v any) ([]byte, error) +func EncodeToWriter(v any, w io.Writer) error +func EncodeUnescapeHTML(v any) ([]byte, error) +func Decode(bts []byte, ptr any) error +func DecodeString(str string, ptr any) error +func DecodeReader(r io.Reader, ptr any) error +func Mapping(src, dst any) error +func StripComments(src string) string ``` ### Map @@ -703,33 +714,33 @@ func StripComments(src string) string ```go // source at maputil/check.go -func HasKey(mp, key any) (ok bool) -func HasAllKeys(mp any, keys ...any) (ok bool, noKey any) +func HasKey(mp, key any) (ok bool) +func HasAllKeys(mp any, keys ...any) (ok bool, noKey any) // source at maputil/convert.go -func KeyToLower(src map[string]string) map[string]string -func ToStringMap(src map[string]any) map[string]string -func HttpQueryString(data map[string]any) string -func ToString(mp map[string]any) string -func ToString2(mp any) string -func FormatIndent(mp any, indent string) string -func Flatten(mp map[string]any) map[string]any -func FlatWithFunc(mp map[string]any, fn reflects.FlatFunc) +func KeyToLower(src map[string]string) map[string]string +func ToStringMap(src map[string]any) map[string]string +func HTTPQueryString(data map[string]any) string +func ToString(mp map[string]any) string +func ToString2(mp any) string +func FormatIndent(mp any, indent string) string +func Flatten(mp map[string]any) map[string]any +func FlatWithFunc(mp map[string]any, fn reflects.FlatFunc) // source at maputil/format.go -func NewFormatter(mp any) *MapFormatter +func NewFormatter(mp any) *MapFormatter // source at maputil/get.go -func DeepGet(mp map[string]any, path string) (val any) -func QuietGet(mp map[string]any, path string) (val any) -func GetByPath(path string, mp map[string]any) (val any, ok bool) -func Keys(mp any) (keys []string) -func Values(mp any) (values []any) +func DeepGet(mp map[string]any, path string) (val any) +func QuietGet(mp map[string]any, path string) (val any) +func GetByPath(path string, mp map[string]any) (val any, ok bool) +func Keys(mp any) (keys []string) +func Values(mp any) (values []any) // source at maputil/maputil.go -func MergeSMap(src, dst map[string]string, ignoreCase bool) map[string]string -func MergeStringMap(src, dst map[string]string, ignoreCase bool) map[string]string -func MakeByPath(path string, val any) (mp map[string]any) -func MakeByKeys(keys []string, val any) (mp map[string]any) +func MergeSMap(src, dst map[string]string, ignoreCase bool) map[string]string +func MergeStringMap(src, dst map[string]string, ignoreCase bool) map[string]string +func MakeByPath(path string, val any) (mp map[string]any) +func MakeByKeys(keys []string, val any) (mp map[string]any) // source at maputil/setval.go -func SetByPath(mp *map[string]any, path string, val any) error -func SetByKeys(mp *map[string]any, keys []string, val any) (err error) +func SetByPath(mp *map[string]any, path string, val any) error +func SetByKeys(mp *map[string]any, keys []string, val any) (err error) ``` ### Math/Number @@ -738,57 +749,57 @@ func SetByKeys(mp *map[string]any, keys []string, val any) (err error) ```go // source at mathutil/check.go -func Compare(srcVal, dstVal any, op string) (ok bool) -func CompInt64(srcI64, dstI64 int64, op string) (ok bool) -func CompFloat(srcF64, dstF64 float64, op string) (ok bool) +func Compare(srcVal, dstVal any, op string) (ok bool) +func CompInt64(srcI64, dstI64 int64, op string) (ok bool) +func CompFloat(srcF64, dstF64 float64, op string) (ok bool) // source at mathutil/convert.go -func Int(in any) (int, error) -func QuietInt(in any) int -func MustInt(in any) int -func IntOrPanic(in any) int -func IntOrErr(in any) (iVal int, err error) -func ToInt(in any) (iVal int, err error) -func StrInt(s string) int -func Uint(in any) (uint64, error) -func QuietUint(in any) uint64 -func MustUint(in any) uint64 -func UintOrErr(in any) (uint64, error) -func ToUint(in any) (u64 uint64, err error) -func Int64(in any) (int64, error) -func QuietInt64(in any) int64 -func MustInt64(in any) int64 -func Int64OrErr(in any) (int64, error) -func ToInt64(in any) (i64 int64, err error) -func QuietFloat(in any) float64 -func FloatOrPanic(in any) float64 -func MustFloat(in any) float64 -func Float(in any) (float64, error) -func FloatOrErr(in any) (float64, error) -func ToFloat(in any) (f64 float64, err error) -func StringOrPanic(val any) string -func MustString(val any) string -func ToString(val any) (string, error) -func StringOrErr(val any) (string, error) -func QuietString(val any) string -func String(val any) string -func TryToString(val any, defaultAsErr bool) (str string, err error) +func Int(in any) (int, error) +func QuietInt(in any) int +func MustInt(in any) int +func IntOrPanic(in any) int +func IntOrErr(in any) (iVal int, err error) +func ToInt(in any) (iVal int, err error) +func StrInt(s string) int +func Uint(in any) (uint64, error) +func QuietUint(in any) uint64 +func MustUint(in any) uint64 +func UintOrErr(in any) (uint64, error) +func ToUint(in any) (u64 uint64, err error) +func Int64(in any) (int64, error) +func QuietInt64(in any) int64 +func MustInt64(in any) int64 +func Int64OrErr(in any) (int64, error) +func ToInt64(in any) (i64 int64, err error) +func QuietFloat(in any) float64 +func FloatOrPanic(in any) float64 +func MustFloat(in any) float64 +func Float(in any) (float64, error) +func FloatOrErr(in any) (float64, error) +func ToFloat(in any) (f64 float64, err error) +func StringOrPanic(val any) string +func MustString(val any) string +func ToString(val any) (string, error) +func StringOrErr(val any) (string, error) +func QuietString(val any) string +func String(val any) string +func TryToString(val any, defaultAsErr bool) (str string, err error) // source at mathutil/mathutil.go -func MaxFloat(x, y float64) float64 -func MaxInt(x, y int) int -func SwapMaxInt(x, y int) (int, int) -func MaxI64(x, y int64) int64 -func SwapMaxI64(x, y int64) (int64, int64) +func MaxFloat(x, y float64) float64 +func MaxInt(x, y int) int +func SwapMaxInt(x, y int) (int, int) +func MaxI64(x, y int64) int64 +func SwapMaxI64(x, y int64) (int64, int64) // source at mathutil/number.go -func IsNumeric(c byte) bool -func Percent(val, total int) float64 -func ElapsedTime(startTime time.Time) string -func DataSize(size uint64) string -func HowLongAgo(sec int64) string +func IsNumeric(c byte) bool +func Percent(val, total int) float64 +func ElapsedTime(startTime time.Time) string +func DataSize(size uint64) string +func HowLongAgo(sec int64) string // source at mathutil/random.go -func RandomInt(min, max int) int -func RandInt(min, max int) int { return RandomInt(min, max) } -func RandIntWithSeed(min, max int, seed int64) int -func RandomIntWithSeed(min, max int, seed int64) int +func RandomInt(min, max int) int +func RandInt(min, max int) int +func RandIntWithSeed(min, max int, seed int64) int +func RandomIntWithSeed(min, max int, seed int64) int ``` ### Reflects @@ -797,33 +808,33 @@ func RandomIntWithSeed(min, max int, seed int64) int ```go // source at reflects/check.go -func HasChild(v reflect.Value) bool -func IsNil(v reflect.Value) bool -func IsFunc(val any) bool -func IsEqual(src, dst any) bool -func IsEmpty(v reflect.Value) bool -func IsEmptyValue(v reflect.Value) bool +func HasChild(v reflect.Value) bool +func IsNil(v reflect.Value) bool +func IsFunc(val any) bool +func IsEqual(src, dst any) bool +func IsEmpty(v reflect.Value) bool +func IsEmptyValue(v reflect.Value) bool // source at reflects/conv.go -func BaseTypeVal(v reflect.Value) (value any, err error) -func ValueByType(val any, typ reflect.Type) (rv reflect.Value, err error) -func ValueByKind(val any, kind reflect.Kind) (rv reflect.Value, err error) -func String(rv reflect.Value) string -func ToString(rv reflect.Value) (str string, err error) -func ValToString(rv reflect.Value, defaultAsErr bool) (str string, err error) +func BaseTypeVal(v reflect.Value) (value any, err error) +func ValueByType(val any, typ reflect.Type) (rv reflect.Value, err error) +func ValueByKind(val any, kind reflect.Kind) (rv reflect.Value, err error) +func String(rv reflect.Value) string +func ToString(rv reflect.Value) (str string, err error) +func ValToString(rv reflect.Value, defaultAsErr bool) (str string, err error) // source at reflects/type.go -func ToBaseKind(kind reflect.Kind) BKind -func ToBKind(kind reflect.Kind) BKind -func TypeOf(v any) Type +func ToBaseKind(kind reflect.Kind) BKind +func ToBKind(kind reflect.Kind) BKind +func TypeOf(v any) Type // source at reflects/util.go -func Elem(v reflect.Value) reflect.Value -func Indirect(v reflect.Value) reflect.Value -func Len(v reflect.Value) int -func SliceSubKind(typ reflect.Type) reflect.Kind -func SetValue(rv reflect.Value, val any) error -func FlatMap(rv reflect.Value, fn FlatFunc) +func Elem(v reflect.Value) reflect.Value +func Indirect(v reflect.Value) reflect.Value +func Len(v reflect.Value) int +func SliceSubKind(typ reflect.Type) reflect.Kind +func SetValue(rv reflect.Value, val any) error +func FlatMap(rv reflect.Value, fn FlatFunc) // source at reflects/value.go -func Wrap(rv reflect.Value) Value -func ValueOf(v any) Value +func Wrap(rv reflect.Value) Value +func ValueOf(v any) Value ``` ### Stdio @@ -832,14 +843,14 @@ func ValueOf(v any) Value ```go // source at stdio/ioutil.go -func QuietFprint(w io.Writer, ss ...string) -func QuietFprintf(w io.Writer, tpl string, vs ...any) -func QuietFprintln(w io.Writer, ss ...string) -func QuietWriteString(w io.Writer, ss ...string) -func DiscardReader(src io.Reader) -func MustReadReader(r io.Reader) []byte +func QuietFprint(w io.Writer, ss ...string) +func QuietFprintf(w io.Writer, tpl string, vs ...any) +func QuietFprintln(w io.Writer, ss ...string) +func QuietWriteString(w io.Writer, ss ...string) +func DiscardReader(src io.Reader) +func MustReadReader(r io.Reader) []byte // source at stdio/writer.go -func NewWriteWrapper(w io.Writer) *WriteWrapper +func NewWriteWrapper(w io.Writer) *WriteWrapper ``` ### Standard @@ -848,40 +859,40 @@ func NewWriteWrapper(w io.Writer) *WriteWrapper ```go // source at stdutil/chan.go -func WaitCloseSignals(closer io.Closer) error -func Go(f func() error) error -func SignalHandler(ctx context.Context, signals ...os.Signal) (execute func() error, interrupt func(error)) +func WaitCloseSignals(closer io.Closer) error +func Go(f func() error) error +func SignalHandler(ctx context.Context, signals ...os.Signal) (execute func() error, interrupt func(error)) // source at stdutil/check.go -func IsNil(v any) bool -func IsEmpty(v any) bool -func IsFunc(val any) bool -func IsEqual(src, dst any) bool -func Contains(data, elem any) bool -func IsContains(data, elem any) bool -func CheckContains(data, elem any) (valid, found bool) -func ValueIsEmpty(v reflect.Value) bool -func ValueLen(v reflect.Value) int +func IsNil(v any) bool +func IsEmpty(v any) bool +func IsFunc(val any) bool +func IsEqual(src, dst any) bool +func Contains(data, elem any) bool +func IsContains(data, elem any) bool +func CheckContains(data, elem any) (valid, found bool) +func ValueIsEmpty(v reflect.Value) bool +func ValueLen(v reflect.Value) int // source at stdutil/conv.go -func ToString(v any) string -func MustString(v any) string -func TryString(v any) (string, error) -func BaseTypeVal(val any) (value any, err error) -func BaseTypeVal2(v reflect.Value) (value any, err error) +func ToString(v any) string +func MustString(v any) string +func TryString(v any) (string, error) +func BaseTypeVal(val any) (value any, err error) +func BaseTypeVal2(v reflect.Value) (value any, err error) // source at stdutil/gofunc.go -func FuncName(fn any) string -func CutFuncName(fullFcName string) (pkgPath, shortFnName string) -func PkgName(fullFcName string) string +func FuncName(fn any) string +func CutFuncName(fullFcName string) (pkgPath, shortFnName string) +func PkgName(fullFcName string) string // source at stdutil/stack.go -func GetCallStacks(all bool) []byte -func GetCallerInfo(skip int) string -func SimpleCallersInfo(skip, num int) []string -func GetCallersInfo(skip, max int) []string +func GetCallStacks(all bool) []byte +func GetCallerInfo(skip int) string +func SimpleCallersInfo(skip, num int) []string +func GetCallersInfo(skip, max int) []string // source at stdutil/stdutil.go -func DiscardE(_ error) {} -func PanicIfErr(err error) -func PanicIf(err error) -func Panicf(format string, v ...any) -func GoVersion() string +func DiscardE(_ error) +func PanicIfErr(err error) +func PanicIf(err error) +func Panicf(format string, v ...any) +func GoVersion() string ``` ### Structs @@ -890,28 +901,30 @@ func GoVersion() string ```go // source at structs/alias.go -func NewAliases(checker func(alias string)) *Aliases +func NewAliases(checker func(alias string)) *Aliases // source at structs/convert.go -func ToMap(st any, optFns ...MapOptFunc) map[string]any -func MustToMap(st any, optFns ...MapOptFunc) map[string]any -func TryToMap(st any, optFns ...MapOptFunc) (map[string]any, error) -func StructToMap(st any, optFns ...MapOptFunc) (map[string]any, error) +func ToMap(st any, optFns ...MapOptFunc) map[string]any +func MustToMap(st any, optFns ...MapOptFunc) map[string]any +func TryToMap(st any, optFns ...MapOptFunc) (map[string]any, error) +func StructToMap(st any, optFns ...MapOptFunc) (map[string]any, error) // source at structs/data.go -func NewData() *Data +func NewData() *Data // source at structs/setval.go -func InitDefaults(ptr any, optFns ...InitOptFunc) error -func SetValues(ptr any, data map[string]any, optFns ...SetOptFunc) error +func InitDefaults(ptr any, optFns ...InitOptFunc) error +func SetValues(ptr any, data map[string]any, optFns ...SetOptFunc) error // source at structs/structs.go -func MapStruct(srcSt, dstSt any) +func MapStruct(srcSt, dstSt any) +func IsExported(fieldName string) bool +func IsUnexported(fieldName string) bool // source at structs/tags.go -func ParseTags(st any, tagNames []string) (map[string]maputil.SMap, error) -func ParseReflectTags(rt reflect.Type, tagNames []string) (map[string]maputil.SMap, error) -func NewTagParser(tagNames ...string) *TagParser -func ParseTagValueDefault(field, tagVal string) (mp maputil.SMap, err error) -func ParseTagValueDefine(sep string, defines []string) TagValFunc -func ParseTagValueNamed(field, tagVal string, keys ...string) (mp maputil.SMap, err error) +func ParseTags(st any, tagNames []string) (map[string]maputil.SMap, error) +func ParseReflectTags(rt reflect.Type, tagNames []string) (map[string]maputil.SMap, error) +func NewTagParser(tagNames ...string) *TagParser +func ParseTagValueDefault(field, tagVal string) (mp maputil.SMap, err error) +func ParseTagValueDefine(sep string, defines []string) TagValFunc +func ParseTagValueNamed(field, tagVal string, keys ...string) (mp maputil.SMap, err error) // source at structs/value.go -func NewValue(val any) *Value +func NewValue(val any) *Value ``` ### Strings @@ -920,184 +933,184 @@ func NewValue(val any) *Value ```go // source at strutil/bytes.go -func NewBuffer() *Buffer -func NewByteChanPool(maxSize, width, capWidth int) *ByteChanPool +func NewBuffer() *Buffer +func NewByteChanPool(maxSize, width, capWidth int) *ByteChanPool // source at strutil/check.go -func NoCaseEq(s, t string) bool -func IsNumChar(c byte) bool -func IsNumeric(s string) bool -func IsAlphabet(char uint8) bool -func IsAlphaNum(c uint8) bool -func StrPos(s, sub string) int -func BytePos(s string, bt byte) int -func HasOneSub(s string, subs []string) bool -func HasAllSubs(s string, subs []string) bool -func IsStartsOf(s string, prefixes []string) bool -func HasOnePrefix(s string, prefixes []string) bool -func HasPrefix(s string, prefix string) bool { return strings.HasPrefix(s, prefix) } -func IsStartOf(s, prefix string) bool { return strings.HasPrefix(s, prefix) } -func HasSuffix(s string, suffix string) bool { return strings.HasSuffix(s, suffix) } -func IsEndOf(s, suffix string) bool { return strings.HasSuffix(s, suffix) } -func IsValidUtf8(s string) bool { return utf8.ValidString(s) } -func IsSpace(c byte) bool -func IsEmpty(s string) bool { return len(s) == 0 } -func IsBlank(s string) bool -func IsNotBlank(s string) bool -func IsBlankBytes(bs []byte) bool -func IsSymbol(r rune) bool -func IsVersion(s string) bool -func Compare(s1, s2, op string) bool -func VersionCompare(v1, v2, op string) bool +func NoCaseEq(s, t string) bool +func IsNumChar(c byte) bool +func IsNumeric(s string) bool +func IsAlphabet(char uint8) bool +func IsAlphaNum(c uint8) bool +func StrPos(s, sub string) int +func BytePos(s string, bt byte) int +func HasOneSub(s string, subs []string) bool +func HasAllSubs(s string, subs []string) bool +func IsStartsOf(s string, prefixes []string) bool +func HasOnePrefix(s string, prefixes []string) bool +func HasPrefix(s string, prefix string) bool +func IsStartOf(s, prefix string) bool +func HasSuffix(s string, suffix string) bool +func IsEndOf(s, suffix string) bool +func IsValidUtf8(s string) bool +func IsSpace(c byte) bool +func IsEmpty(s string) bool +func IsBlank(s string) bool +func IsNotBlank(s string) bool +func IsBlankBytes(bs []byte) bool +func IsSymbol(r rune) bool +func IsVersion(s string) bool +func Compare(s1, s2, op string) bool +func VersionCompare(v1, v2, op string) bool // source at strutil/convert.go -func Quote(s string) string { return strconv.Quote(s) } -func Unquote(s string) string -func Join(sep string, ss ...string) string { return strings.Join(ss, sep) } -func JoinList(sep string, ss []string) string { return strings.Join(ss, sep) } -func Implode(sep string, ss ...string) string { return strings.Join(ss, sep) } -func String(val any) (string, error) -func QuietString(in any) string -func MustString(in any) string -func StringOrErr(val any) (string, error) -func ToString(val any) (string, error) -func AnyToString(val any, defaultAsErr bool) (str string, err error) -func Byte2str(b []byte) string -func Byte2string(b []byte) string -func ToBytes(s string) (b []byte) -func ToBool(s string) (bool, error) -func QuietBool(s string) bool -func MustBool(s string) bool -func Bool(s string) (bool, error) -func Int(s string) (int, error) -func ToInt(s string) (int, error) -func QuietInt(s string) int -func MustInt(s string) int -func IntOrPanic(s string) int -func Int64(s string) int64 -func QuietInt64(s string) int64 -func ToInt64(s string) (int64, error) -func Int64OrErr(s string) (int64, error) -func MustInt64(s string) int64 -func Int64OrPanic(s string) int64 -func Ints(s string, sep ...string) []int -func ToInts(s string, sep ...string) ([]int, error) { return ToIntSlice(s, sep...) } -func ToIntSlice(s string, sep ...string) (ints []int, err error) -func ToArray(s string, sep ...string) []string { return ToSlice(s, sep...) } -func Strings(s string, sep ...string) []string { return ToSlice(s, sep...) } -func ToStrings(s string, sep ...string) []string { return ToSlice(s, sep...) } -func ToSlice(s string, sep ...string) []string -func ToOSArgs(s string) []string -func MustToTime(s string, layouts ...string) time.Time -func ToTime(s string, layouts ...string) (t time.Time, err error) -func ToDuration(s string) (time.Duration, error) +func Quote(s string) string +func Unquote(s string) string +func Join(sep string, ss ...string) string +func JoinList(sep string, ss []string) string +func Implode(sep string, ss ...string) string +func String(val any) (string, error) +func QuietString(in any) string +func MustString(in any) string +func StringOrErr(val any) (string, error) +func ToString(val any) (string, error) +func AnyToString(val any, defaultAsErr bool) (str string, err error) +func Byte2str(b []byte) string +func Byte2string(b []byte) string +func ToBytes(s string) (b []byte) +func ToBool(s string) (bool, error) +func QuietBool(s string) bool +func MustBool(s string) bool +func Bool(s string) (bool, error) +func Int(s string) (int, error) +func ToInt(s string) (int, error) +func QuietInt(s string) int +func MustInt(s string) int +func IntOrPanic(s string) int +func Int64(s string) int64 +func QuietInt64(s string) int64 +func ToInt64(s string) (int64, error) +func Int64OrErr(s string) (int64, error) +func MustInt64(s string) int64 +func Int64OrPanic(s string) int64 +func Ints(s string, sep ...string) []int +func ToInts(s string, sep ...string) ([]int, error) +func ToIntSlice(s string, sep ...string) (ints []int, err error) +func ToArray(s string, sep ...string) []string +func Strings(s string, sep ...string) []string +func ToStrings(s string, sep ...string) []string +func ToSlice(s string, sep ...string) []string +func ToOSArgs(s string) []string +func MustToTime(s string, layouts ...string) time.Time +func ToTime(s string, layouts ...string) (t time.Time, err error) +func ToDuration(s string) (time.Duration, error) // source at strutil/crypto.go -func Md5(src any) string -func MD5(src any) string { return Md5(src) } -func GenMd5(src any) string { return Md5(src) } -func Md5Bytes(src any) []byte -func HashPasswd(pwd, key string) string -func VerifyPasswd(pwdMAC, pwd, key string) bool +func Md5(src any) string +func MD5(src any) string +func GenMd5(src any) string +func Md5Bytes(src any) []byte +func HashPasswd(pwd, key string) string +func VerifyPasswd(pwdMAC, pwd, key string) bool // source at strutil/encode.go -func EscapeJS(s string) string -func EscapeHTML(s string) string -func AddSlashes(s string) string -func StripSlashes(s string) string -func URLEncode(s string) string -func URLDecode(s string) string -func B32Encode(str string) string -func B32Decode(str string) string -func B64Encode(str string) string -func B64EncodeBytes(src []byte) []byte -func B64Decode(str string) string -func B64DecodeBytes(str string) []byte -func Encoding(base int, typ BaseType) BaseEncoder +func EscapeJS(s string) string +func EscapeHTML(s string) string +func AddSlashes(s string) string +func StripSlashes(s string) string +func URLEncode(s string) string +func URLDecode(s string) string +func B32Encode(str string) string +func B32Decode(str string) string +func B64Encode(str string) string +func B64EncodeBytes(src []byte) []byte +func B64Decode(str string) string +func B64DecodeBytes(str string) []byte +func Encoding(base int, typ BaseType) BaseEncoder // source at strutil/filter.go -func Trim(s string, cutSet ...string) string -func Ltrim(s string, cutSet ...string) string { return TrimLeft(s, cutSet...) } -func LTrim(s string, cutSet ...string) string { return TrimLeft(s, cutSet...) } -func TrimLeft(s string, cutSet ...string) string -func Rtrim(s string, cutSet ...string) string { return TrimRight(s, cutSet...) } -func RTrim(s string, cutSet ...string) string { return TrimRight(s, cutSet...) } -func TrimRight(s string, cutSet ...string) string -func FilterEmail(s string) string +func Trim(s string, cutSet ...string) string +func Ltrim(s string, cutSet ...string) string +func LTrim(s string, cutSet ...string) string +func TrimLeft(s string, cutSet ...string) string +func Rtrim(s string, cutSet ...string) string +func RTrim(s string, cutSet ...string) string +func TrimRight(s string, cutSet ...string) string +func FilterEmail(s string) string // source at strutil/format.go -func Title(s string) string { return strings.ToTitle(s) } -func Lower(s string) string { return strings.ToLower(s) } -func Lowercase(s string) string { return strings.ToLower(s) } -func Upper(s string) string { return strings.ToUpper(s) } -func Uppercase(s string) string { return strings.ToUpper(s) } -func UpperWord(s string) string -func LowerFirst(s string) string -func UpperFirst(s string) string -func SnakeCase(s string, sep ...string) string -func Camel(s string, sep ...string) string { return CamelCase(s, sep...) } -func CamelCase(s string, sep ...string) string -func Indent(s, prefix string) string -func IndentBytes(b, prefix []byte) []byte +func Title(s string) string +func Lower(s string) string +func Lowercase(s string) string +func Upper(s string) string +func Uppercase(s string) string +func UpperWord(s string) string +func LowerFirst(s string) string +func UpperFirst(s string) string +func SnakeCase(s string, sep ...string) string +func Camel(s string, sep ...string) string +func CamelCase(s string, sep ...string) string +func Indent(s, prefix string) string +func IndentBytes(b, prefix []byte) []byte // source at strutil/id.go -func MicroTimeID() string -func MicroTimeHexID() string +func MicroTimeID() string +func MicroTimeHexID() string // source at strutil/padding.go -func Padding(s, pad string, length int, pos PosFlag) string -func PadLeft(s, pad string, length int) string -func PadRight(s, pad string, length int) string -func Resize(s string, length int, align PosFlag) string -func PadBytes(bs []byte, pad byte, length int, pos PosFlag) []byte -func PadBytesLeft(bs []byte, pad byte, length int) []byte -func PadBytesRight(bs []byte, pad byte, length int) []byte -func PadRunes(rs []rune, pad rune, length int, pos PosFlag) []rune -func PadRunesLeft(rs []rune, pad rune, length int) []rune -func PadRunesRight(rs []rune, pad rune, length int) []rune -func Repeat(s string, times int) string -func RepeatRune(char rune, times int) []rune -func RepeatBytes(char byte, times int) []byte +func Padding(s, pad string, length int, pos PosFlag) string +func PadLeft(s, pad string, length int) string +func PadRight(s, pad string, length int) string +func Resize(s string, length int, align PosFlag) string +func PadBytes(bs []byte, pad byte, length int, pos PosFlag) []byte +func PadBytesLeft(bs []byte, pad byte, length int) []byte +func PadBytesRight(bs []byte, pad byte, length int) []byte +func PadRunes(rs []rune, pad rune, length int, pos PosFlag) []rune +func PadRunesLeft(rs []rune, pad rune, length int) []rune +func PadRunesRight(rs []rune, pad rune, length int) []rune +func Repeat(s string, times int) string +func RepeatRune(char rune, times int) []rune +func RepeatBytes(char byte, times int) []byte // source at strutil/random.go -func RandomChars(ln int) string -func RandomCharsV2(ln int) string -func RandomCharsV3(ln int) string -func RandomBytes(length int) ([]byte, error) -func RandomString(length int) (string, error) +func RandomChars(ln int) string +func RandomCharsV2(ln int) string +func RandomCharsV3(ln int) string +func RandomBytes(length int) ([]byte, error) +func RandomString(length int) (string, error) // source at strutil/runes.go -func RuneIsWord(c rune) bool -func RuneIsLower(c rune) bool -func RuneIsUpper(c rune) bool -func RunePos(s string, ru rune) int { return strings.IndexRune(s, ru) } -func IsSpaceRune(r rune) bool -func Utf8Len(s string) int { return utf8.RuneCountInString(s) } -func Utf8len(s string) int { return utf8.RuneCountInString(s) } -func RuneCount(s string) int { return len([]rune(s)) } -func RuneWidth(r rune) int -func TextWidth(s string) int { return Utf8Width(s) } -func Utf8Width(s string) int { return RunesWidth([]rune(s)) } -func RunesWidth(rs []rune) (w int) -func TextTruncate(s string, w int, tail string) string { return Utf8Truncate(s, w, tail) } -func Utf8Truncate(s string, w int, tail string) string -func TextSplit(s string, w int) []string { return Utf8Split(s, w) } -func Utf8Split(s string, w int) []string -func TextWrap(s string, w int) string { return WidthWrap(s, w) } -func WidthWrap(s string, w int) string -func WordWrap(s string, w int) string +func RuneIsWord(c rune) bool +func RuneIsLower(c rune) bool +func RuneIsUpper(c rune) bool +func RunePos(s string, ru rune) int +func IsSpaceRune(r rune) bool +func Utf8Len(s string) int +func Utf8len(s string) int +func RuneCount(s string) int +func RuneWidth(r rune) int +func TextWidth(s string) int +func Utf8Width(s string) int +func RunesWidth(rs []rune) (w int) +func TextTruncate(s string, w int, tail string) string +func Utf8Truncate(s string, w int, tail string) string +func TextSplit(s string, w int) []string +func Utf8Split(s string, w int) []string +func TextWrap(s string, w int) string +func WidthWrap(s string, w int) string +func WordWrap(s string, w int) string // source at strutil/similar_find.go -func NewComparator(src, dst string) *SimilarComparator -func Similarity(s, t string, rate float32) (float32, bool) +func NewComparator(src, dst string) *SimilarComparator +func Similarity(s, t string, rate float32) (float32, bool) // source at strutil/split.go -func Cut(s, sep string) (before string, after string, found bool) -func MustCut(s, sep string) (before string, after string) -func TrimCut(s, sep string) (string, string) -func SplitValid(s, sep string) (ss []string) { return Split(s, sep) } -func Split(s, sep string) (ss []string) -func SplitNValid(s, sep string, n int) (ss []string) { return SplitN(s, sep, n) } -func SplitN(s, sep string, n int) (ss []string) -func SplitTrimmed(s, sep string) (ss []string) -func SplitNTrimmed(s, sep string, n int) (ss []string) -func Substr(s string, pos, length int) string -func SplitInlineComment(val string) (string, string) +func Cut(s, sep string) (before string, after string, found bool) +func MustCut(s, sep string) (before string, after string) +func TrimCut(s, sep string) (string, string) +func SplitValid(s, sep string) (ss []string) +func Split(s, sep string) (ss []string) +func SplitNValid(s, sep string, n int) (ss []string) +func SplitN(s, sep string, n int) (ss []string) +func SplitTrimmed(s, sep string) (ss []string) +func SplitNTrimmed(s, sep string, n int) (ss []string) +func Substr(s string, pos, length int) string +func SplitInlineComment(val string) (string, string) // source at strutil/strutil.go -func Replaces(str string, pairs map[string]string) string -func PrettyJSON(v any) (string, error) -func RenderTemplate(input string, data any, fns template.FuncMap, isFile ...bool) string -func RenderText(input string, data any, fns template.FuncMap, isFile ...bool) string -func WrapTag(s, tag string) string -func SubstrCount(s string, needle string, params ...uint64) (int, error) +func Replaces(str string, pairs map[string]string) string +func PrettyJSON(v any) (string, error) +func RenderTemplate(input string, data any, fns template.FuncMap, isFile ...bool) string +func RenderText(input string, data any, fns template.FuncMap, isFile ...bool) string +func WrapTag(s, tag string) string +func SubstrCount(s string, substr string, params ...uint64) (int, error) ``` ### System Utils @@ -1106,59 +1119,59 @@ func SubstrCount(s string, needle string, params ...uint64) (int, error) ```go // source at sysutil/exec.go -func NewCmd(bin string, args ...string) *cmdr.Cmd -func FlushExec(bin string, args ...string) error -func QuickExec(cmdLine string, workDir ...string) (string, error) -func ExecLine(cmdLine string, workDir ...string) (string, error) -func ExecCmd(binName string, args []string, workDir ...string) (string, error) -func ShellExec(cmdLine string, shells ...string) (string, error) +func NewCmd(bin string, args ...string) *cmdr.Cmd +func FlushExec(bin string, args ...string) error +func QuickExec(cmdLine string, workDir ...string) (string, error) +func ExecLine(cmdLine string, workDir ...string) (string, error) +func ExecCmd(binName string, args []string, workDir ...string) (string, error) +func ShellExec(cmdLine string, shells ...string) (string, error) // source at sysutil/stack.go -func CallersInfos(skip, num int, filters ...func(file string, fc *runtime.Func) bool) []*CallerInfo +func CallersInfos(skip, num int, filters ...func(file string, fc *runtime.Func) bool) []*CallerInfo // source at sysutil/sysenv.go -func IsMSys() bool -func IsConsole(out io.Writer) bool -func IsTerminal(fd uintptr) bool -func StdIsTerminal() bool -func Hostname() string -func CurrentShell(onlyName bool) (path string) -func HasShellEnv(shell string) bool -func IsShellSpecialVar(c uint8) bool -func EnvPaths() []string -func FindExecutable(binName string) (string, error) -func Executable(binName string) (string, error) -func HasExecutable(binName string) bool -func SearchPath(keywords string) []string +func IsMSys() bool +func IsConsole(out io.Writer) bool +func IsTerminal(fd uintptr) bool +func StdIsTerminal() bool +func Hostname() string +func CurrentShell(onlyName bool) (path string) +func HasShellEnv(shell string) bool +func IsShellSpecialVar(c uint8) bool +func EnvPaths() []string +func FindExecutable(binName string) (string, error) +func Executable(binName string) (string, error) +func HasExecutable(binName string) bool +func SearchPath(keywords string) []string // source at sysutil/sysgo.go -func GoVersion() string -func ParseGoVersion(line string) (*GoInfo, error) -func OsGoInfo() (*GoInfo, error) +func GoVersion() string +func ParseGoVersion(line string) (*GoInfo, error) +func OsGoInfo() (*GoInfo, error) // source at sysutil/sysutil.go -func Workdir() string -func BinDir() string -func BinFile() string +func Workdir() string +func BinDir() string +func BinFile() string // source at sysutil/sysutil_nonwin.go -func IsWin() bool -func IsWindows() bool -func IsMac() bool -func IsDarwin() bool -func IsLinux() bool -func Kill(pid int, signal syscall.Signal) error -func ProcessExists(pid int) bool -func OpenBrowser(URL string) error +func IsWin() bool +func IsWindows() bool +func IsMac() bool +func IsDarwin() bool +func IsLinux() bool +func Kill(pid int, signal syscall.Signal) error +func ProcessExists(pid int) bool +func OpenBrowser(URL string) error // source at sysutil/user.go -func MustFindUser(uname string) *user.User -func LoginUser() *user.User -func CurrentUser() *user.User -func UHomeDir() string -func UserHomeDir() string -func HomeDir() string -func UserDir(subPath string) string -func UserCacheDir(subPath string) string -func UserConfigDir(subPath string) string -func ExpandPath(path string) string +func MustFindUser(uname string) *user.User +func LoginUser() *user.User +func CurrentUser() *user.User +func UHomeDir() string +func UserHomeDir() string +func HomeDir() string +func UserDir(subPath string) string +func UserCacheDir(subPath string) string +func UserConfigDir(subPath string) string +func ExpandPath(path string) string // source at sysutil/user_nonwin.go -func ChangeUserByName(newUname string) (err error) -func ChangeUserUidGid(newUid int, newGid int) (err error) +func ChangeUserByName(newUname string) (err error) +func ChangeUserUidGid(newUid int, newGid int) (err error) ``` ### Testing Utils @@ -1167,27 +1180,27 @@ func ChangeUserUidGid(newUid int, newGid int) (err error) ```go // source at testutil/buffer.go -func NewBuffer() *Buffer +func NewBuffer() *Buffer // source at testutil/envmock.go -func MockEnvValue(key, val string, fn func(nv string)) -func MockEnvValues(kvMap map[string]string, fn func()) -func MockOsEnvByText(envText string, fn func()) -func MockOsEnv(mp map[string]string, fn func()) -func ClearOSEnv() { os.Clearenv() } -func RevertOSEnv() -func MockCleanOsEnv(mp map[string]string, fn func()) +func MockEnvValue(key, val string, fn func(nv string)) +func MockEnvValues(kvMap map[string]string, fn func()) +func MockOsEnvByText(envText string, fn func()) +func MockOsEnv(mp map[string]string, fn func()) +func ClearOSEnv() +func RevertOSEnv() +func MockCleanOsEnv(mp map[string]string, fn func()) // source at testutil/httpmock.go -func NewHttpRequest(method, path string, data *MD) *http.Request -func MockRequest(h http.Handler, method, path string, data *MD) *httptest.ResponseRecorder +func NewHttpRequest(method, path string, data *MD) *http.Request +func MockRequest(h http.Handler, method, path string, data *MD) *httptest.ResponseRecorder // source at testutil/testutil.go -func DiscardStdout() error -func ReadOutput() (s string) -func RewriteStdout() -func RestoreStdout(printData ...bool) (s string) -func RewriteStderr() -func RestoreStderr(printData ...bool) (s string) +func DiscardStdout() error +func ReadOutput() (s string) +func RewriteStdout() +func RestoreStdout(printData ...bool) (s string) +func RewriteStderr() +func RestoreStderr(printData ...bool) (s string) // source at testutil/writer.go -func NewTestWriter() *TestWriter +func NewTestWriter() *TestWriter ``` ### Timex @@ -1197,46 +1210,46 @@ func NewTestWriter() *TestWriter Provides an enhanced time.Time implementation, and add more commonly used functional methods. ```go // source at timex/template.go -func ToLayout(template string) string +func ToLayout(template string) string // source at timex/timex.go -func Now() *Time -func New(t time.Time) *Time -func Wrap(t time.Time) *Time -func FromTime(t time.Time) *Time -func Local() *Time -func FromUnix(sec int64) *Time -func FromDate(s string, template ...string) (*Time, error) -func FromString(s string, layouts ...string) (*Time, error) -func LocalByName(tzName string) *Time +func Now() *Time +func New(t time.Time) *Time +func Wrap(t time.Time) *Time +func FromTime(t time.Time) *Time +func Local() *Time +func FromUnix(sec int64) *Time +func FromDate(s string, template ...string) (*Time, error) +func FromString(s string, layouts ...string) (*Time, error) +func LocalByName(tzName string) *Time // source at timex/util.go -func NowUnix() int64 -func SetLocalByName(tzName string) error -func Format(t time.Time) string -func FormatBy(t time.Time, layout string) string -func Date(t time.Time, template string) string -func DateFormat(t time.Time, template string) string -func FormatByTpl(t time.Time, template string) string -func FormatUnix(sec int64) string -func FormatUnixBy(sec int64, layout string) string -func FormatUnixByTpl(sec int64, template string) string -func NowAddDay(day int) time.Time -func NowAddHour(hour int) time.Time -func NowAddMinutes(minutes int) time.Time -func NowAddSeconds(seconds int) time.Time -func NowHourStart() time.Time -func NowHourEnd() time.Time -func AddDay(t time.Time, day int) time.Time -func AddHour(t time.Time, hour int) time.Time -func AddMinutes(t time.Time, minutes int) time.Time -func AddSeconds(t time.Time, seconds int) time.Time -func HourStart(t time.Time) time.Time -func HourEnd(t time.Time) time.Time -func DayStart(t time.Time) time.Time -func DayEnd(t time.Time) time.Time -func TodayStart() time.Time -func TodayEnd() time.Time -func HowLongAgo(sec int64) string -func ToDuration(s string) (time.Duration, error) +func NowUnix() int64 +func SetLocalByName(tzName string) error +func Format(t time.Time) string +func FormatBy(t time.Time, layout string) string +func Date(t time.Time, template string) string +func DateFormat(t time.Time, template string) string +func FormatByTpl(t time.Time, template string) string +func FormatUnix(sec int64) string +func FormatUnixBy(sec int64, layout string) string +func FormatUnixByTpl(sec int64, template string) string +func NowAddDay(day int) time.Time +func NowAddHour(hour int) time.Time +func NowAddMinutes(minutes int) time.Time +func NowAddSeconds(seconds int) time.Time +func NowHourStart() time.Time +func NowHourEnd() time.Time +func AddDay(t time.Time, day int) time.Time +func AddHour(t time.Time, hour int) time.Time +func AddMinutes(t time.Time, minutes int) time.Time +func AddSeconds(t time.Time, seconds int) time.Time +func HourStart(t time.Time) time.Time +func HourEnd(t time.Time) time.Time +func DayStart(t time.Time) time.Time +func DayEnd(t time.Time) time.Time +func TodayStart() time.Time +func TodayEnd() time.Time +func HowLongAgo(sec int64) string +func ToDuration(s string) (time.Duration, error) ``` #### Timex Usage @@ -1357,6 +1370,126 @@ date := FormatUnixByTpl(ts, "Y-m-d H:I:S") // Get: 2022-04-20 19:40:34 ``` +## Code Check & Testing + +```bash +gofmt -w -l ./ +golint ./... + +# testing +go test -v ./... +go test -v -run ^TestErr$ +go test -v -run ^TestErr$ ./testutil/assert/... +``` + +Testing in docker: + +```shell +cd goutil +docker run -ti -v $(pwd):/go/work golang:1.18 +root@xx:/go/work# go test ./... +``` + +## Related + +- https://github.com/duke-git/lancet +- https://github.com/samber/lo +- https://github.com/zyedidia/generic +- https://github.com/thoas/go-funk + +## Gookit packages + +- [gookit/ini](https://github.com/gookit/ini) Go config management, use INI files +- [gookit/rux](https://github.com/gookit/rux) Simple and fast request router for golang HTTP +- [gookit/gcli](https://github.com/gookit/gcli) Build CLI application, tool library, running CLI commands +- [gookit/slog](https://github.com/gookit/slog) Lightweight, easy to extend, configurable logging library written in Go +- [gookit/color](https://github.com/gookit/color) A command-line color library with true color support, universal API methods and Windows support +- [gookit/event](https://github.com/gookit/event) Lightweight event manager and dispatcher implements by Go +- [gookit/cache](https://github.com/gookit/cache) Generic cache use and cache manager for golang. support File, Memory, Redis, Memcached. +- [gookit/config](https://github.com/gookit/config) Go config management. support JSON, YAML, TOML, INI, HCL, ENV and Flags +- [gookit/filter](https://github.com/gookit/filter) Provide filtering, sanitizing, and conversion of golang data +- [gookit/validate](https://github.com/gookit/validate) Use for data validation and filtering. support Map, Struct, Form data +- [gookit/goutil](https://github.com/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](LICENSE) +on of golang data +- [gookit/validate](https://github.com/gookit/validate) Use for data validation and filtering. support Map, Struct, Form data +- [gookit/goutil](https://github.com/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](LICENSE) +ore compare +tx.IsBefore(u time.Time) +tx.IsBeforeUnix(1647411580) +// after compare +tx.IsAfter(u time.Time) +tx.IsAfterUnix(1647411580) +``` + +**Helper functions** + +```go +ts := timex.NowUnix() // current unix timestamp + +t := NowAddDay(1) // from now add 1 day +t := NowAddHour(1) // from now add 1 hour +t := NowAddMinutes(3) // from now add 3 minutes +t := NowAddSeconds(180) // from now add 180 seconds +``` + +**Convert time to date by template** + +Template Chars: + +```text + Y,y - year + Y - year 2006 + y - year 06 + m - month 01-12 + d - day 01-31 + H,h - hour + H - hour 00-23 + h - hour 01-12 + I,i - minute + I - minute 00-59 + i - minute 0-59 + S,s - second + S - second 00-59 + s - second 0-59 +``` + +> More, please see [char map](./timex/template.go) + +Examples, use timex: + +```go +tx := timex.Now() +date := tx.DateFormat("Y-m-d H:I:S") // Output: 2022-04-20 19:09:03 +date = tx.DateFormat("y-m-d h:i:s") // Output: 22-04-20 07:9:3 +``` + +Format time.Time: + +```go +tx := time.Now() +date := timex.DateFormat(tx, "Y-m-d H:I:S") // Output: 2022-04-20 19:40:34 +``` + +More usage: + +```go +ts := timex.NowUnix() // current unix timestamp + +date := FormatUnix(ts, "2006-01-02 15:04:05") // Get: 2022-04-20 19:40:34 +date := FormatUnixByTpl(ts, "Y-m-d H:I:S") // Get: 2022-04-20 19:40:34 +``` + + ## Code Check & Testing ```bash diff --git a/README.zh-CN.md b/README.zh-CN.md index f4e7a724f..1f4bbac0e 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -87,48 +87,48 @@ u64Val = goutil.Uint("2") // 2 ```go // source at arrutil/arrutil.go -func Reverse(ss []string) -func StringsRemove(ss []string, s string) []string -func StringsFilter(ss []string, filter ...func(s string) bool) []string -func StringsMap(ss []string, mapFn func(s string) string) []string -func TrimStrings(ss []string, cutSet ...string) []string +func Reverse(ss []string) +func StringsRemove(ss []string, s string) []string +func StringsFilter(ss []string, filter ...func(s string) bool) []string +func StringsMap(ss []string, mapFn func(s string) string) []string +func TrimStrings(ss []string, cutSet ...string) []string // source at arrutil/check.go -func IntsHas(ints []int, val int) bool -func Int64sHas(ints []int64, val int64) bool -func InStrings(elem string, ss []string) bool { return StringsHas(ss, elem) } -func StringsHas(ss []string, val string) bool -func HasValue(arr, val any) bool -func Contains(arr, val any) bool -func NotContains(arr, val any) bool +func IntsHas(ints []int, val int) bool +func Int64sHas(ints []int64, val int64) bool +func InStrings(elem string, ss []string) bool +func StringsHas(ss []string, val string) bool +func HasValue(arr, val any) bool +func Contains(arr, val any) bool +func NotContains(arr, val any) bool // source at arrutil/collection.go -func TwowaySearch(data any, item any, fn Comparer) (int, error) -func MakeEmptySlice(itemType reflect.Type) any -func CloneSlice(data any) any -func Excepts(first, second any, fn Comparer) any -func Intersects(first any, second any, fn Comparer) any -func Union(first, second any, fn Comparer) any -func Find(source any, fn Predicate) (any, error) -func FindOrDefault(source any, fn Predicate, defaultValue any) any -func TakeWhile(data any, fn Predicate) any -func ExceptWhile(data any, fn Predicate) any +func TwowaySearch(data any, item any, fn Comparer) (int, error) +func MakeEmptySlice(itemType reflect.Type) any +func CloneSlice(data any) any +func Excepts(first, second any, fn Comparer) any +func Intersects(first any, second any, fn Comparer) any +func Union(first, second any, fn Comparer) any +func Find(source any, fn Predicate) (any, error) +func FindOrDefault(source any, fn Predicate, defaultValue any) any +func TakeWhile(data any, fn Predicate) any +func ExceptWhile(data any, fn Predicate) any // source at arrutil/convert.go -func JoinStrings(sep string, ss ...string) string -func StringsJoin(sep string, ss ...string) string -func StringsToInts(ss []string) (ints []int, err error) -func MustToStrings(arr any) []string -func StringsToSlice(ss []string) []any -func ToInt64s(arr any) (ret []int64, err error) -func MustToInt64s(arr any) []int64 -func SliceToInt64s(arr []any) []int64 -func ToStrings(arr any) (ret []string, err error) -func SliceToStrings(arr []any) []string -func AnyToString(arr any) string -func SliceToString(arr ...any) string { return ToString(arr) } -func ToString(arr []any) string -func JoinSlice(sep string, arr ...any) string +func JoinStrings(sep string, ss ...string) string +func StringsJoin(sep string, ss ...string) string +func StringsToInts(ss []string) (ints []int, err error) +func MustToStrings(arr any) []string +func StringsToSlice(ss []string) []any +func ToInt64s(arr any) (ret []int64, err error) +func MustToInt64s(arr any) []int64 +func SliceToInt64s(arr []any) []int64 +func ToStrings(arr any) (ret []string, err error) +func SliceToStrings(arr []any) []string +func AnyToString(arr any) string +func SliceToString(arr ...any) string +func ToString(arr []any) string +func JoinSlice(sep string, arr ...any) string // source at arrutil/format.go -func NewFormatter(arr any) *ArrFormatter -func FormatIndent(arr any, indent string) string +func NewFormatter(arr any) *ArrFormatter +func FormatIndent(arr any, indent string) string ``` #### ArrUtil Usage @@ -158,13 +158,13 @@ ss, err := arrutil.ToStrings([]int{1, 2}) // ss: []string{"1", "2"} ```go // source at byteutil/buffer.go -func NewBuffer() *Buffer +func NewBuffer() *Buffer // source at byteutil/bytex.go -func Md5(src any) []byte +func Md5(src any) []byte // source at byteutil/encoder.go -func NewStdEncoder(encFn func(src []byte) []byte, decFn func(src []byte) ([]byte, error)) *StdEncoder +func NewStdEncoder(encFn func(src []byte) []byte, decFn func(src []byte) ([]byte, error)) *StdEncoder // source at byteutil/pool.go -func NewChanPool(maxSize int, width int, capWidth int) *ChanPool +func NewChanPool(maxSize int, width int, capWidth int) *ChanPool ``` ### Cflag @@ -173,26 +173,26 @@ func NewChanPool(maxSize int, width int, capWidth int) *ChanPool ```go // source at cflag/app.go -func NewApp(fns ...func(app *App)) *App -func NewCmd(name, desc string) *Cmd +func NewApp(fns ...func(app *App)) *App +func NewCmd(name, desc string) *Cmd // source at cflag/cflag.go -func SetDebug(open bool) -func New(fns ...func(c *CFlags)) *CFlags -func NewEmpty(fns ...func(c *CFlags)) *CFlags -func WithDesc(desc string) func(c *CFlags) -func WithVersion(version string) func(c *CFlags) +func SetDebug(open bool) +func New(fns ...func(c *CFlags)) *CFlags +func NewEmpty(fns ...func(c *CFlags)) *CFlags +func WithDesc(desc string) func(c *CFlags) +func WithVersion(version string) func(c *CFlags) // source at cflag/optarg.go -func NewArg(name, desc string, required bool) *FlagArg +func NewArg(name, desc string, required bool) *FlagArg // source at cflag/util.go -func IsZeroValue(opt *flag.Flag, value string) (bool, bool) -func AddPrefix(name string) string -func AddPrefixes(name string, shorts []string) string -func AddPrefixes2(name string, shorts []string, nameAtEnd bool) string -func SplitShortcut(shortcut string) []string -func FilterNames(names []string) []string -func IsFlagHelpErr(err error) bool -func WrapColorForCode(s string) string -func ReplaceShorts(args []string, shortsMap map[string]string) []string +func IsZeroValue(opt *flag.Flag, value string) (bool, bool) +func AddPrefix(name string) string +func AddPrefixes(name string, shorts []string) string +func AddPrefixes2(name string, shorts []string, nameAtEnd bool) string +func SplitShortcut(shortcut string) []string +func FilterNames(names []string) []string +func IsFlagHelpErr(err error) bool +func WrapColorForCode(s string) string +func ReplaceShorts(args []string, shortsMap map[string]string) []string ``` #### `cflag` Usage @@ -205,71 +205,71 @@ func ReplaceShorts(args []string, shortsMap map[string]string) []string ```go // source at cliutil/cliutil.go -func LineBuild(binFile string, args []string) string -func BuildLine(binFile string, args []string) string -func String2OSArgs(line string) []string -func StringToOSArgs(line string) []string -func ParseLine(line string) []string -func QuickExec(cmdLine string, workDir ...string) (string, error) -func ExecLine(cmdLine string, workDir ...string) (string, error) -func ExecCmd(binName string, args []string, workDir ...string) (string, error) -func ExecCommand(binName string, args []string, workDir ...string) (string, error) -func ShellExec(cmdLine string, shells ...string) (string, error) -func CurrentShell(onlyName bool) (path string) -func HasShellEnv(shell string) bool -func BuildOptionHelpName(names []string) string -func ShellQuote(s string) string -func OutputLines(output string) []string -func FirstLine(output string) string +func LineBuild(binFile string, args []string) string +func BuildLine(binFile string, args []string) string +func String2OSArgs(line string) []string +func StringToOSArgs(line string) []string +func ParseLine(line string) []string +func QuickExec(cmdLine string, workDir ...string) (string, error) +func ExecLine(cmdLine string, workDir ...string) (string, error) +func ExecCmd(binName string, args []string, workDir ...string) (string, error) +func ExecCommand(binName string, args []string, workDir ...string) (string, error) +func ShellExec(cmdLine string, shells ...string) (string, error) +func CurrentShell(onlyName bool) (path string) +func HasShellEnv(shell string) bool +func BuildOptionHelpName(names []string) string +func ShellQuote(s string) string +func OutputLines(output string) []string +func FirstLine(output string) string // source at cliutil/color_print.go -func Redp(a ...any) { color.Red.Print(a...) } -func Redf(format string, a ...any) { color.Red.Printf(format, a...) } -func Redln(a ...any) { color.Red.Println(a...) } -func Bluep(a ...any) { color.Blue.Print(a...) } -func Bluef(format string, a ...any) { color.Blue.Printf(format, a...) } -func Blueln(a ...any) { color.Blue.Println(a...) } -func Cyanp(a ...any) { color.Cyan.Print(a...) } -func Cyanf(format string, a ...any) { color.Cyan.Printf(format, a...) } -func Cyanln(a ...any) { color.Cyan.Println(a...) } -func Grayp(a ...any) { color.Gray.Print(a...) } -func Grayf(format string, a ...any) { color.Gray.Printf(format, a...) } -func Grayln(a ...any) { color.Gray.Println(a...) } -func Greenp(a ...any) { color.Green.Print(a...) } -func Greenf(format string, a ...any) { color.Green.Printf(format, a...) } -func Greenln(a ...any) { color.Green.Println(a...) } -func Yellowp(a ...any) { color.Yellow.Print(a...) } -func Yellowf(format string, a ...any) { color.Yellow.Printf(format, a...) } -func Yellowln(a ...any) { color.Yellow.Println(a...) } -func Magentap(a ...any) { color.Magenta.Print(a...) } -func Magentaf(format string, a ...any) { color.Magenta.Printf(format, a...) } -func Magentaln(a ...any) { color.Magenta.Println(a...) } -func Infop(a ...any) { color.Info.Print(a...) } -func Infof(format string, a ...any) { color.Info.Printf(format, a...) } -func Infoln(a ...any) { color.Info.Println(a...) } -func Successp(a ...any) { color.Success.Print(a...) } -func Successf(format string, a ...any) { color.Success.Printf(format, a...) } -func Successln(a ...any) { color.Success.Println(a...) } -func Errorp(a ...any) { color.Error.Print(a...) } -func Errorf(format string, a ...any) { color.Error.Printf(format, a...) } -func Errorln(a ...any) { color.Error.Println(a...) } -func Warnp(a ...any) { color.Warn.Print(a...) } -func Warnf(format string, a ...any) { color.Warn.Printf(format, a...) } -func Warnln(a ...any) { color.Warn.Println(a...) } +func Redp(a ...any) +func Redf(format string, a ...any) +func Redln(a ...any) +func Bluep(a ...any) +func Bluef(format string, a ...any) +func Blueln(a ...any) +func Cyanp(a ...any) +func Cyanf(format string, a ...any) +func Cyanln(a ...any) +func Grayp(a ...any) +func Grayf(format string, a ...any) +func Grayln(a ...any) +func Greenp(a ...any) +func Greenf(format string, a ...any) +func Greenln(a ...any) +func Yellowp(a ...any) +func Yellowf(format string, a ...any) +func Yellowln(a ...any) +func Magentap(a ...any) +func Magentaf(format string, a ...any) +func Magentaln(a ...any) +func Infop(a ...any) +func Infof(format string, a ...any) +func Infoln(a ...any) +func Successp(a ...any) +func Successf(format string, a ...any) +func Successln(a ...any) +func Errorp(a ...any) +func Errorf(format string, a ...any) +func Errorln(a ...any) +func Warnp(a ...any) +func Warnf(format string, a ...any) +func Warnln(a ...any) // source at cliutil/info.go -func Workdir() string -func BinDir() string -func BinFile() string -func BinName() string -func GetTermSize(refresh ...bool) (w int, h int) +func Workdir() string +func BinDir() string +func BinFile() string +func BinName() string +func GetTermSize(refresh ...bool) (w int, h int) // source at cliutil/read.go -func ReadInput(question string) (string, error) -func ReadLine(question string) (string, error) -func ReadFirst(question string) (string, error) -func ReadFirstByte(question string) (byte, error) -func ReadFirstRune(question string) (rune, error) -func ReadPassword(question ...string) string -func InputIsYes(ans string) bool -func ByteIsYes(ans byte) bool +func ReadInput(question string) (string, error) +func ReadLine(question string) (string, error) +func ReadFirst(question string) (string, error) +func ReadFirstByte(question string) (byte, error) +func ReadFirstRune(question string) (rune, error) +func ReadPassword(question ...string) string +func InputIsYes(ans string) bool +func ByteIsYes(ans byte) bool ``` #### CLI Util Usage @@ -333,19 +333,30 @@ Build line: ./myapp -a val0 -m "this is message" arg0 ```go // source at dump/dump.go -func Std() *Dumper -func Reset() -func Config(fn func(opts *Options)) -func Print(vs ...any) -func Println(vs ...any) -func Fprint(w io.Writer, vs ...any) -func Format(vs ...any) string -func NoLoc(vs ...any) -func Clear(vs ...any) +func Std() *Dumper +func Reset() +func Config(fns ...OptionFunc) +func Print(vs ...any) +func Println(vs ...any) +func Fprint(w io.Writer, vs ...any) +func Std2() *Dumper +func Reset2() +func Format(vs ...any) string +func NoLoc(vs ...any) +func Clear(vs ...any) // source at dump/dumper.go -func NewDumper(out io.Writer, skip int) *Dumper -func NewWithOptions(fn func(opts *Options)) *Dumper -func NewDefaultOptions(out io.Writer, skip int) *Options +func NewDumper(out io.Writer, skip int) *Dumper +func NewWithOptions(fns ...OptionFunc) *Dumper +// source at dump/options.go +func NewDefaultOptions(out io.Writer, skip int) *Options +func SkipNilField() OptionFunc +func SkipPrivate() OptionFunc +func BytesAsString() OptionFunc +func WithCallerSkip(skip int) OptionFunc +func WithoutPosition() OptionFunc +func WithoutOutput(out io.Writer) OptionFunc +func WithoutColor() OptionFunc +func WithoutType() OptionFunc ``` #### Examples @@ -397,31 +408,31 @@ Preview: ```go // source at envutil/envutil.go -func VarReplace(s string) string { return os.ExpandEnv(s) } -func VarParse(val string) string -func ParseEnvValue(val string) string -func ParseValue(val string) (newVal string) -func SetEnvs(mp map[string]string) +func VarReplace(s string) string +func VarParse(val string) string +func ParseEnvValue(val string) string +func ParseValue(val string) (newVal string) +func SetEnvs(mp map[string]string) // source at envutil/get.go -func Getenv(name string, def ...string) string -func GetInt(name string, def ...int) int -func GetBool(name string, def ...bool) bool -func Environ() map[string]string +func Getenv(name string, def ...string) string +func GetInt(name string, def ...int) int +func GetBool(name string, def ...bool) bool +func Environ() map[string]string // source at envutil/info.go -func IsWin() bool -func IsWindows() bool -func IsMac() bool -func IsLinux() bool -func IsMSys() bool -func IsWSL() bool -func IsTerminal(fd uintptr) bool -func StdIsTerminal() bool -func IsConsole(out io.Writer) bool -func HasShellEnv(shell string) bool -func IsSupportColor() bool -func IsSupport256Color() bool -func IsSupportTrueColor() bool -func IsGithubActions() bool +func IsWin() bool +func IsWindows() bool +func IsMac() bool +func IsLinux() bool +func IsMSys() bool +func IsWSL() bool +func IsTerminal(fd uintptr) bool +func StdIsTerminal() bool +func IsConsole(out io.Writer) bool +func HasShellEnv(shell string) bool +func IsSupportColor() bool +func IsSupport256Color() bool +func IsSupportTrueColor() bool +func IsGithubActions() bool ``` #### ENV Util Usage @@ -453,40 +464,40 @@ envutil.ParseValue("${ENV_NAME | defValue}") ```go // source at errorx/errors.go -func NewR(code int, msg string) ErrorR -func Fail(code int, msg string) ErrorR -func Suc(msg string) ErrorR +func NewR(code int, msg string) ErrorR +func Fail(code int, msg string) ErrorR +func Suc(msg string) ErrorR // source at errorx/errorx.go -func New(msg string) error -func Newf(tpl string, vars ...any) error -func Errorf(tpl string, vars ...any) error -func With(err error, msg string) error -func Withf(err error, tpl string, vars ...any) error -func WithPrev(err error, msg string) error -func WithPrevf(err error, tpl string, vars ...any) error -func WithStack(err error) error -func Traced(err error) error -func Stacked(err error) error -func WithOptions(msg string, fns ...func(opt *ErrStackOpt)) error -func Wrap(err error, msg string) error -func Wrapf(err error, tpl string, vars ...any) error +func New(msg string) error +func Newf(tpl string, vars ...any) error +func Errorf(tpl string, vars ...any) error +func With(err error, msg string) error +func Withf(err error, tpl string, vars ...any) error +func WithPrev(err error, msg string) error +func WithPrevf(err error, tpl string, vars ...any) error +func WithStack(err error) error +func Traced(err error) error +func Stacked(err error) error +func WithOptions(msg string, fns ...func(opt *ErrStackOpt)) error +func Wrap(err error, msg string) error +func Wrapf(err error, tpl string, vars ...any) error // source at errorx/stack.go -func FuncForPC(pc uintptr) *Func -func ResetStdOpt() -func Config(fns ...func(opt *ErrStackOpt)) -func SkipDepth(skipDepth int) func(opt *ErrStackOpt) -func TraceDepth(traceDepth int) func(opt *ErrStackOpt) +func FuncForPC(pc uintptr) *Func +func ResetStdOpt() +func Config(fns ...func(opt *ErrStackOpt)) +func SkipDepth(skipDepth int) func(opt *ErrStackOpt) +func TraceDepth(traceDepth int) func(opt *ErrStackOpt) // source at errorx/util.go -func Raw(msg string) error -func Rawf(tpl string, vars ...any) error -func Cause(err error) error -func Unwrap(err error) error -func Previous(err error) error { return Unwrap(err) } -func ToErrorX(err error) (ex *ErrorX, ok bool) -func Has(err, target error) bool -func Is(err, target error) bool -func To(err error, target any) bool -func As(err error, target any) bool +func Raw(msg string) error +func Rawf(tpl string, vars ...any) error +func Cause(err error) error +func Unwrap(err error) error +func Previous(err error) error +func ToErrorX(err error) (ex *ErrorX, ok bool) +func Has(err, target error) bool +func Is(err, target error) bool +func To(err error, target any) bool +func As(err error, target any) bool ``` #### Errorx 使用示例 @@ -571,15 +582,15 @@ runtime.goexit() ```go // source at fmtutil/format.go -func DataSize(size uint64) string -func SizeToString(size uint64) string { return DataSize(size) } -func StringToByte(sizeStr string) uint64 { return ParseByte(sizeStr) } -func ParseByte(sizeStr string) uint64 -func PrettyJSON(v any) (string, error) -func StringsToInts(ss []string) (ints []int, err error) -func ArgsWithSpaces(args []any) (message string) +func DataSize(size uint64) string +func SizeToString(size uint64) string +func StringToByte(sizeStr string) uint64 +func ParseByte(sizeStr string) uint64 +func PrettyJSON(v any) (string, error) +func StringsToInts(ss []string) (ints []int, err error) +func ArgsWithSpaces(args []any) (message string) // source at fmtutil/time.go -func HowLongAgo(sec int64) string +func HowLongAgo(sec int64) string ``` ### File System @@ -588,57 +599,57 @@ func HowLongAgo(sec int64) string ```go // source at fsutil/check.go -func PathExists(path string) bool -func IsDir(path string) bool -func FileExists(path string) bool -func IsFile(path string) bool -func IsAbsPath(aPath string) bool -func IsImageFile(path string) bool -func IsZipFile(filepath string) bool +func PathExists(path string) bool +func IsDir(path string) bool +func FileExists(path string) bool +func IsFile(path string) bool +func IsAbsPath(aPath string) bool +func IsImageFile(path string) bool +func IsZipFile(filepath string) bool // source at fsutil/fsutil.go -func OSTempFile(pattern string) (*os.File, error) -func TempFile(dir, pattern string) (*os.File, error) -func OSTempDir(pattern string) (string, error) -func TempDir(dir, pattern string) (string, error) -func MimeType(path string) (mime string) -func ReaderMimeType(r io.Reader) (mime string) +func OSTempFile(pattern string) (*os.File, error) +func TempFile(dir, pattern string) (*os.File, error) +func OSTempDir(pattern string) (string, error) +func TempDir(dir, pattern string) (string, error) +func MimeType(path string) (mime string) +func ReaderMimeType(r io.Reader) (mime string) // source at fsutil/info.go -func Dir(fpath string) string -func PathName(fpath string) string -func Name(fpath string) string -func FileExt(fpath string) string -func Suffix(fpath string) string -func Expand(pathStr string) string -func ExpandPath(pathStr string) string -func Realpath(pathStr string) string -func SplitPath(pathStr string) (dir, name string) -func GlobWithFunc(pattern string, fn func(filePath string) error) (err error) -func FindInDir(dir string, handleFn HandleFunc, filters ...FilterFunc) (e error) +func Dir(fpath string) string +func PathName(fpath string) string +func Name(fpath string) string +func FileExt(fpath string) string +func Suffix(fpath string) string +func Expand(pathStr string) string +func ExpandPath(pathStr string) string +func Realpath(pathStr string) string +func SplitPath(pathStr string) (dir, name string) +func GlobWithFunc(pattern string, fn func(filePath string) error) (err error) +func FindInDir(dir string, handleFn HandleFunc, filters ...FilterFunc) (e error) // source at fsutil/operate.go -func Mkdir(dirPath string, perm os.FileMode) error -func MkParentDir(fpath string) error -func DiscardReader(src io.Reader) -func MustReadFile(filePath string) []byte -func MustReadReader(r io.Reader) []byte -func GetContents(in any) []byte -func ReadExistFile(filePath string) []byte -func OpenFile(filepath string, flag int, perm os.FileMode) (*os.File, error) -func QuickOpenFile(filepath string, fileFlag ...int) (*os.File, error) -func OpenReadFile(filepath string) (*os.File, error) -func CreateFile(fpath string, filePerm, dirPerm os.FileMode, fileFlag ...int) (*os.File, error) -func MustCreateFile(filePath string, filePerm, dirPerm os.FileMode) *os.File -func PutContents(filePath string, data any, fileFlag ...int) (int, error) -func WriteFile(filePath string, data any, perm os.FileMode, fileFlag ...int) error -func CopyFile(srcPath, dstPath string) error -func MustCopyFile(srcPath, dstPath string) -func Remove(fPath string) error -func MustRemove(fPath string) -func QuietRemove(fPath string) { _ = os.Remove(fPath) } -func RmIfExist(fPath string) error { return DeleteIfExist(fPath) } -func DeleteIfExist(fPath string) error -func RmFileIfExist(fPath string) error { return DeleteIfFileExist(fPath) } -func DeleteIfFileExist(fPath string) error -func Unzip(archive, targetDir string) (err error) +func Mkdir(dirPath string, perm os.FileMode) error +func MkParentDir(fpath string) error +func DiscardReader(src io.Reader) +func MustReadFile(filePath string) []byte +func MustReadReader(r io.Reader) []byte +func GetContents(in any) []byte +func ReadExistFile(filePath string) []byte +func OpenFile(filepath string, flag int, perm os.FileMode) (*os.File, error) +func QuickOpenFile(filepath string, fileFlag ...int) (*os.File, error) +func OpenReadFile(filepath string) (*os.File, error) +func CreateFile(fpath string, filePerm, dirPerm os.FileMode, fileFlag ...int) (*os.File, error) +func MustCreateFile(filePath string, filePerm, dirPerm os.FileMode) *os.File +func PutContents(filePath string, data any, fileFlag ...int) (int, error) +func WriteFile(filePath string, data any, perm os.FileMode, fileFlag ...int) error +func CopyFile(srcPath, dstPath string) error +func MustCopyFile(srcPath, dstPath string) +func Remove(fPath string) error +func MustRemove(fPath string) +func QuietRemove(fPath string) +func RmIfExist(fPath string) error +func DeleteIfExist(fPath string) error +func RmFileIfExist(fPath string) error +func DeleteIfFileExist(fPath string) error +func Unzip(archive, targetDir string) (err error) ``` #### FsUtil Usage @@ -684,18 +695,18 @@ func main() { ```go // source at jsonutil/jsonutil.go -func WriteFile(filePath string, data any) error -func ReadFile(filePath string, v any) error -func Pretty(v any) (string, error) -func Encode(v any) ([]byte, error) -func EncodePretty(v any) ([]byte, error) -func EncodeToWriter(v any, w io.Writer) error -func EncodeUnescapeHTML(v any) ([]byte, error) -func Decode(bts []byte, ptr any) error -func DecodeString(str string, ptr any) error -func DecodeReader(r io.Reader, ptr any) error -func Mapping(src, dst any) error -func StripComments(src string) string +func WriteFile(filePath string, data any) error +func ReadFile(filePath string, v any) error +func Pretty(v any) (string, error) +func Encode(v any) ([]byte, error) +func EncodePretty(v any) ([]byte, error) +func EncodeToWriter(v any, w io.Writer) error +func EncodeUnescapeHTML(v any) ([]byte, error) +func Decode(bts []byte, ptr any) error +func DecodeString(str string, ptr any) error +func DecodeReader(r io.Reader, ptr any) error +func Mapping(src, dst any) error +func StripComments(src string) string ``` ### Map @@ -704,33 +715,33 @@ func StripComments(src string) string ```go // source at maputil/check.go -func HasKey(mp, key any) (ok bool) -func HasAllKeys(mp any, keys ...any) (ok bool, noKey any) +func HasKey(mp, key any) (ok bool) +func HasAllKeys(mp any, keys ...any) (ok bool, noKey any) // source at maputil/convert.go -func KeyToLower(src map[string]string) map[string]string -func ToStringMap(src map[string]any) map[string]string -func HttpQueryString(data map[string]any) string -func ToString(mp map[string]any) string -func ToString2(mp any) string -func FormatIndent(mp any, indent string) string -func Flatten(mp map[string]any) map[string]any -func FlatWithFunc(mp map[string]any, fn reflects.FlatFunc) +func KeyToLower(src map[string]string) map[string]string +func ToStringMap(src map[string]any) map[string]string +func HTTPQueryString(data map[string]any) string +func ToString(mp map[string]any) string +func ToString2(mp any) string +func FormatIndent(mp any, indent string) string +func Flatten(mp map[string]any) map[string]any +func FlatWithFunc(mp map[string]any, fn reflects.FlatFunc) // source at maputil/format.go -func NewFormatter(mp any) *MapFormatter +func NewFormatter(mp any) *MapFormatter // source at maputil/get.go -func DeepGet(mp map[string]any, path string) (val any) -func QuietGet(mp map[string]any, path string) (val any) -func GetByPath(path string, mp map[string]any) (val any, ok bool) -func Keys(mp any) (keys []string) -func Values(mp any) (values []any) +func DeepGet(mp map[string]any, path string) (val any) +func QuietGet(mp map[string]any, path string) (val any) +func GetByPath(path string, mp map[string]any) (val any, ok bool) +func Keys(mp any) (keys []string) +func Values(mp any) (values []any) // source at maputil/maputil.go -func MergeSMap(src, dst map[string]string, ignoreCase bool) map[string]string -func MergeStringMap(src, dst map[string]string, ignoreCase bool) map[string]string -func MakeByPath(path string, val any) (mp map[string]any) -func MakeByKeys(keys []string, val any) (mp map[string]any) +func MergeSMap(src, dst map[string]string, ignoreCase bool) map[string]string +func MergeStringMap(src, dst map[string]string, ignoreCase bool) map[string]string +func MakeByPath(path string, val any) (mp map[string]any) +func MakeByKeys(keys []string, val any) (mp map[string]any) // source at maputil/setval.go -func SetByPath(mp *map[string]any, path string, val any) error -func SetByKeys(mp *map[string]any, keys []string, val any) (err error) +func SetByPath(mp *map[string]any, path string, val any) error +func SetByKeys(mp *map[string]any, keys []string, val any) (err error) ``` ### Math/Number @@ -739,57 +750,57 @@ func SetByKeys(mp *map[string]any, keys []string, val any) (err error) ```go // source at mathutil/check.go -func Compare(srcVal, dstVal any, op string) (ok bool) -func CompInt64(srcI64, dstI64 int64, op string) (ok bool) -func CompFloat(srcF64, dstF64 float64, op string) (ok bool) +func Compare(srcVal, dstVal any, op string) (ok bool) +func CompInt64(srcI64, dstI64 int64, op string) (ok bool) +func CompFloat(srcF64, dstF64 float64, op string) (ok bool) // source at mathutil/convert.go -func Int(in any) (int, error) -func QuietInt(in any) int -func MustInt(in any) int -func IntOrPanic(in any) int -func IntOrErr(in any) (iVal int, err error) -func ToInt(in any) (iVal int, err error) -func StrInt(s string) int -func Uint(in any) (uint64, error) -func QuietUint(in any) uint64 -func MustUint(in any) uint64 -func UintOrErr(in any) (uint64, error) -func ToUint(in any) (u64 uint64, err error) -func Int64(in any) (int64, error) -func QuietInt64(in any) int64 -func MustInt64(in any) int64 -func Int64OrErr(in any) (int64, error) -func ToInt64(in any) (i64 int64, err error) -func QuietFloat(in any) float64 -func FloatOrPanic(in any) float64 -func MustFloat(in any) float64 -func Float(in any) (float64, error) -func FloatOrErr(in any) (float64, error) -func ToFloat(in any) (f64 float64, err error) -func StringOrPanic(val any) string -func MustString(val any) string -func ToString(val any) (string, error) -func StringOrErr(val any) (string, error) -func QuietString(val any) string -func String(val any) string -func TryToString(val any, defaultAsErr bool) (str string, err error) +func Int(in any) (int, error) +func QuietInt(in any) int +func MustInt(in any) int +func IntOrPanic(in any) int +func IntOrErr(in any) (iVal int, err error) +func ToInt(in any) (iVal int, err error) +func StrInt(s string) int +func Uint(in any) (uint64, error) +func QuietUint(in any) uint64 +func MustUint(in any) uint64 +func UintOrErr(in any) (uint64, error) +func ToUint(in any) (u64 uint64, err error) +func Int64(in any) (int64, error) +func QuietInt64(in any) int64 +func MustInt64(in any) int64 +func Int64OrErr(in any) (int64, error) +func ToInt64(in any) (i64 int64, err error) +func QuietFloat(in any) float64 +func FloatOrPanic(in any) float64 +func MustFloat(in any) float64 +func Float(in any) (float64, error) +func FloatOrErr(in any) (float64, error) +func ToFloat(in any) (f64 float64, err error) +func StringOrPanic(val any) string +func MustString(val any) string +func ToString(val any) (string, error) +func StringOrErr(val any) (string, error) +func QuietString(val any) string +func String(val any) string +func TryToString(val any, defaultAsErr bool) (str string, err error) // source at mathutil/mathutil.go -func MaxFloat(x, y float64) float64 -func MaxInt(x, y int) int -func SwapMaxInt(x, y int) (int, int) -func MaxI64(x, y int64) int64 -func SwapMaxI64(x, y int64) (int64, int64) +func MaxFloat(x, y float64) float64 +func MaxInt(x, y int) int +func SwapMaxInt(x, y int) (int, int) +func MaxI64(x, y int64) int64 +func SwapMaxI64(x, y int64) (int64, int64) // source at mathutil/number.go -func IsNumeric(c byte) bool -func Percent(val, total int) float64 -func ElapsedTime(startTime time.Time) string -func DataSize(size uint64) string -func HowLongAgo(sec int64) string +func IsNumeric(c byte) bool +func Percent(val, total int) float64 +func ElapsedTime(startTime time.Time) string +func DataSize(size uint64) string +func HowLongAgo(sec int64) string // source at mathutil/random.go -func RandomInt(min, max int) int -func RandInt(min, max int) int { return RandomInt(min, max) } -func RandIntWithSeed(min, max int, seed int64) int -func RandomIntWithSeed(min, max int, seed int64) int +func RandomInt(min, max int) int +func RandInt(min, max int) int +func RandIntWithSeed(min, max int, seed int64) int +func RandomIntWithSeed(min, max int, seed int64) int ``` ### Reflects @@ -798,33 +809,33 @@ func RandomIntWithSeed(min, max int, seed int64) int ```go // source at reflects/check.go -func HasChild(v reflect.Value) bool -func IsNil(v reflect.Value) bool -func IsFunc(val any) bool -func IsEqual(src, dst any) bool -func IsEmpty(v reflect.Value) bool -func IsEmptyValue(v reflect.Value) bool +func HasChild(v reflect.Value) bool +func IsNil(v reflect.Value) bool +func IsFunc(val any) bool +func IsEqual(src, dst any) bool +func IsEmpty(v reflect.Value) bool +func IsEmptyValue(v reflect.Value) bool // source at reflects/conv.go -func BaseTypeVal(v reflect.Value) (value any, err error) -func ValueByType(val any, typ reflect.Type) (rv reflect.Value, err error) -func ValueByKind(val any, kind reflect.Kind) (rv reflect.Value, err error) -func String(rv reflect.Value) string -func ToString(rv reflect.Value) (str string, err error) -func ValToString(rv reflect.Value, defaultAsErr bool) (str string, err error) +func BaseTypeVal(v reflect.Value) (value any, err error) +func ValueByType(val any, typ reflect.Type) (rv reflect.Value, err error) +func ValueByKind(val any, kind reflect.Kind) (rv reflect.Value, err error) +func String(rv reflect.Value) string +func ToString(rv reflect.Value) (str string, err error) +func ValToString(rv reflect.Value, defaultAsErr bool) (str string, err error) // source at reflects/type.go -func ToBaseKind(kind reflect.Kind) BKind -func ToBKind(kind reflect.Kind) BKind -func TypeOf(v any) Type +func ToBaseKind(kind reflect.Kind) BKind +func ToBKind(kind reflect.Kind) BKind +func TypeOf(v any) Type // source at reflects/util.go -func Elem(v reflect.Value) reflect.Value -func Indirect(v reflect.Value) reflect.Value -func Len(v reflect.Value) int -func SliceSubKind(typ reflect.Type) reflect.Kind -func SetValue(rv reflect.Value, val any) error -func FlatMap(rv reflect.Value, fn FlatFunc) +func Elem(v reflect.Value) reflect.Value +func Indirect(v reflect.Value) reflect.Value +func Len(v reflect.Value) int +func SliceSubKind(typ reflect.Type) reflect.Kind +func SetValue(rv reflect.Value, val any) error +func FlatMap(rv reflect.Value, fn FlatFunc) // source at reflects/value.go -func Wrap(rv reflect.Value) Value -func ValueOf(v any) Value +func Wrap(rv reflect.Value) Value +func ValueOf(v any) Value ``` ### Stdio @@ -833,14 +844,14 @@ func ValueOf(v any) Value ```go // source at stdio/ioutil.go -func QuietFprint(w io.Writer, ss ...string) -func QuietFprintf(w io.Writer, tpl string, vs ...any) -func QuietFprintln(w io.Writer, ss ...string) -func QuietWriteString(w io.Writer, ss ...string) -func DiscardReader(src io.Reader) -func MustReadReader(r io.Reader) []byte +func QuietFprint(w io.Writer, ss ...string) +func QuietFprintf(w io.Writer, tpl string, vs ...any) +func QuietFprintln(w io.Writer, ss ...string) +func QuietWriteString(w io.Writer, ss ...string) +func DiscardReader(src io.Reader) +func MustReadReader(r io.Reader) []byte // source at stdio/writer.go -func NewWriteWrapper(w io.Writer) *WriteWrapper +func NewWriteWrapper(w io.Writer) *WriteWrapper ``` ### Standard @@ -849,40 +860,40 @@ func NewWriteWrapper(w io.Writer) *WriteWrapper ```go // source at stdutil/chan.go -func WaitCloseSignals(closer io.Closer) error -func Go(f func() error) error -func SignalHandler(ctx context.Context, signals ...os.Signal) (execute func() error, interrupt func(error)) +func WaitCloseSignals(closer io.Closer) error +func Go(f func() error) error +func SignalHandler(ctx context.Context, signals ...os.Signal) (execute func() error, interrupt func(error)) // source at stdutil/check.go -func IsNil(v any) bool -func IsEmpty(v any) bool -func IsFunc(val any) bool -func IsEqual(src, dst any) bool -func Contains(data, elem any) bool -func IsContains(data, elem any) bool -func CheckContains(data, elem any) (valid, found bool) -func ValueIsEmpty(v reflect.Value) bool -func ValueLen(v reflect.Value) int +func IsNil(v any) bool +func IsEmpty(v any) bool +func IsFunc(val any) bool +func IsEqual(src, dst any) bool +func Contains(data, elem any) bool +func IsContains(data, elem any) bool +func CheckContains(data, elem any) (valid, found bool) +func ValueIsEmpty(v reflect.Value) bool +func ValueLen(v reflect.Value) int // source at stdutil/conv.go -func ToString(v any) string -func MustString(v any) string -func TryString(v any) (string, error) -func BaseTypeVal(val any) (value any, err error) -func BaseTypeVal2(v reflect.Value) (value any, err error) +func ToString(v any) string +func MustString(v any) string +func TryString(v any) (string, error) +func BaseTypeVal(val any) (value any, err error) +func BaseTypeVal2(v reflect.Value) (value any, err error) // source at stdutil/gofunc.go -func FuncName(fn any) string -func CutFuncName(fullFcName string) (pkgPath, shortFnName string) -func PkgName(fullFcName string) string +func FuncName(fn any) string +func CutFuncName(fullFcName string) (pkgPath, shortFnName string) +func PkgName(fullFcName string) string // source at stdutil/stack.go -func GetCallStacks(all bool) []byte -func GetCallerInfo(skip int) string -func SimpleCallersInfo(skip, num int) []string -func GetCallersInfo(skip, max int) []string +func GetCallStacks(all bool) []byte +func GetCallerInfo(skip int) string +func SimpleCallersInfo(skip, num int) []string +func GetCallersInfo(skip, max int) []string // source at stdutil/stdutil.go -func DiscardE(_ error) {} -func PanicIfErr(err error) -func PanicIf(err error) -func Panicf(format string, v ...any) -func GoVersion() string +func DiscardE(_ error) +func PanicIfErr(err error) +func PanicIf(err error) +func Panicf(format string, v ...any) +func GoVersion() string ``` ### Structs @@ -891,28 +902,30 @@ func GoVersion() string ```go // source at structs/alias.go -func NewAliases(checker func(alias string)) *Aliases +func NewAliases(checker func(alias string)) *Aliases // source at structs/convert.go -func ToMap(st any, optFns ...MapOptFunc) map[string]any -func MustToMap(st any, optFns ...MapOptFunc) map[string]any -func TryToMap(st any, optFns ...MapOptFunc) (map[string]any, error) -func StructToMap(st any, optFns ...MapOptFunc) (map[string]any, error) +func ToMap(st any, optFns ...MapOptFunc) map[string]any +func MustToMap(st any, optFns ...MapOptFunc) map[string]any +func TryToMap(st any, optFns ...MapOptFunc) (map[string]any, error) +func StructToMap(st any, optFns ...MapOptFunc) (map[string]any, error) // source at structs/data.go -func NewData() *Data +func NewData() *Data // source at structs/setval.go -func InitDefaults(ptr any, optFns ...InitOptFunc) error -func SetValues(ptr any, data map[string]any, optFns ...SetOptFunc) error +func InitDefaults(ptr any, optFns ...InitOptFunc) error +func SetValues(ptr any, data map[string]any, optFns ...SetOptFunc) error // source at structs/structs.go -func MapStruct(srcSt, dstSt any) +func MapStruct(srcSt, dstSt any) +func IsExported(fieldName string) bool +func IsUnexported(fieldName string) bool // source at structs/tags.go -func ParseTags(st any, tagNames []string) (map[string]maputil.SMap, error) -func ParseReflectTags(rt reflect.Type, tagNames []string) (map[string]maputil.SMap, error) -func NewTagParser(tagNames ...string) *TagParser -func ParseTagValueDefault(field, tagVal string) (mp maputil.SMap, err error) -func ParseTagValueDefine(sep string, defines []string) TagValFunc -func ParseTagValueNamed(field, tagVal string, keys ...string) (mp maputil.SMap, err error) +func ParseTags(st any, tagNames []string) (map[string]maputil.SMap, error) +func ParseReflectTags(rt reflect.Type, tagNames []string) (map[string]maputil.SMap, error) +func NewTagParser(tagNames ...string) *TagParser +func ParseTagValueDefault(field, tagVal string) (mp maputil.SMap, err error) +func ParseTagValueDefine(sep string, defines []string) TagValFunc +func ParseTagValueNamed(field, tagVal string, keys ...string) (mp maputil.SMap, err error) // source at structs/value.go -func NewValue(val any) *Value +func NewValue(val any) *Value ``` ### Strings @@ -921,183 +934,184 @@ func NewValue(val any) *Value ```go // source at strutil/bytes.go -func NewBuffer() *Buffer -func NewByteChanPool(maxSize, width, capWidth int) *ByteChanPool +func NewBuffer() *Buffer +func NewByteChanPool(maxSize, width, capWidth int) *ByteChanPool // source at strutil/check.go -func NoCaseEq(s, t string) bool -func IsNumChar(c byte) bool -func IsNumeric(s string) bool -func IsAlphabet(char uint8) bool -func IsAlphaNum(c uint8) bool -func StrPos(s, sub string) int -func BytePos(s string, bt byte) int -func HasOneSub(s string, subs []string) bool -func HasAllSubs(s string, subs []string) bool -func IsStartsOf(s string, prefixes []string) bool -func HasOnePrefix(s string, prefixes []string) bool -func HasPrefix(s string, prefix string) bool { return strings.HasPrefix(s, prefix) } -func IsStartOf(s, prefix string) bool { return strings.HasPrefix(s, prefix) } -func HasSuffix(s string, suffix string) bool { return strings.HasSuffix(s, suffix) } -func IsEndOf(s, suffix string) bool { return strings.HasSuffix(s, suffix) } -func IsValidUtf8(s string) bool { return utf8.ValidString(s) } -func IsSpace(c byte) bool -func IsEmpty(s string) bool { return len(s) == 0 } -func IsBlank(s string) bool -func IsNotBlank(s string) bool -func IsBlankBytes(bs []byte) bool -func IsSymbol(r rune) bool -func IsVersion(s string) bool -func Compare(s1, s2, op string) bool -func VersionCompare(v1, v2, op string) bool +func NoCaseEq(s, t string) bool +func IsNumChar(c byte) bool +func IsNumeric(s string) bool +func IsAlphabet(char uint8) bool +func IsAlphaNum(c uint8) bool +func StrPos(s, sub string) int +func BytePos(s string, bt byte) int +func HasOneSub(s string, subs []string) bool +func HasAllSubs(s string, subs []string) bool +func IsStartsOf(s string, prefixes []string) bool +func HasOnePrefix(s string, prefixes []string) bool +func HasPrefix(s string, prefix string) bool +func IsStartOf(s, prefix string) bool +func HasSuffix(s string, suffix string) bool +func IsEndOf(s, suffix string) bool +func IsValidUtf8(s string) bool +func IsSpace(c byte) bool +func IsEmpty(s string) bool +func IsBlank(s string) bool +func IsNotBlank(s string) bool +func IsBlankBytes(bs []byte) bool +func IsSymbol(r rune) bool +func IsVersion(s string) bool +func Compare(s1, s2, op string) bool +func VersionCompare(v1, v2, op string) bool // source at strutil/convert.go -func Quote(s string) string { return strconv.Quote(s) } -func Unquote(s string) string -func Join(sep string, ss ...string) string { return strings.Join(ss, sep) } -func JoinList(sep string, ss []string) string { return strings.Join(ss, sep) } -func Implode(sep string, ss ...string) string { return strings.Join(ss, sep) } -func String(val any) (string, error) -func QuietString(in any) string -func MustString(in any) string -func StringOrErr(val any) (string, error) -func ToString(val any) (string, error) -func AnyToString(val any, defaultAsErr bool) (str string, err error) -func Byte2str(b []byte) string -func Byte2string(b []byte) string -func ToBytes(s string) (b []byte) -func ToBool(s string) (bool, error) -func QuietBool(s string) bool -func MustBool(s string) bool -func Bool(s string) (bool, error) -func Int(s string) (int, error) -func ToInt(s string) (int, error) -func QuietInt(s string) int -func MustInt(s string) int -func IntOrPanic(s string) int -func Int64(s string) int64 -func QuietInt64(s string) int64 -func ToInt64(s string) (int64, error) -func Int64OrErr(s string) (int64, error) -func MustInt64(s string) int64 -func Int64OrPanic(s string) int64 -func Ints(s string, sep ...string) []int -func ToInts(s string, sep ...string) ([]int, error) { return ToIntSlice(s, sep...) } -func ToIntSlice(s string, sep ...string) (ints []int, err error) -func ToArray(s string, sep ...string) []string { return ToSlice(s, sep...) } -func Strings(s string, sep ...string) []string { return ToSlice(s, sep...) } -func ToStrings(s string, sep ...string) []string { return ToSlice(s, sep...) } -func ToSlice(s string, sep ...string) []string -func ToOSArgs(s string) []string -func MustToTime(s string, layouts ...string) time.Time -func ToTime(s string, layouts ...string) (t time.Time, err error) -func ToDuration(s string) (time.Duration, error) +func Quote(s string) string +func Unquote(s string) string +func Join(sep string, ss ...string) string +func JoinList(sep string, ss []string) string +func Implode(sep string, ss ...string) string +func String(val any) (string, error) +func QuietString(in any) string +func MustString(in any) string +func StringOrErr(val any) (string, error) +func ToString(val any) (string, error) +func AnyToString(val any, defaultAsErr bool) (str string, err error) +func Byte2str(b []byte) string +func Byte2string(b []byte) string +func ToBytes(s string) (b []byte) +func ToBool(s string) (bool, error) +func QuietBool(s string) bool +func MustBool(s string) bool +func Bool(s string) (bool, error) +func Int(s string) (int, error) +func ToInt(s string) (int, error) +func QuietInt(s string) int +func MustInt(s string) int +func IntOrPanic(s string) int +func Int64(s string) int64 +func QuietInt64(s string) int64 +func ToInt64(s string) (int64, error) +func Int64OrErr(s string) (int64, error) +func MustInt64(s string) int64 +func Int64OrPanic(s string) int64 +func Ints(s string, sep ...string) []int +func ToInts(s string, sep ...string) ([]int, error) +func ToIntSlice(s string, sep ...string) (ints []int, err error) +func ToArray(s string, sep ...string) []string +func Strings(s string, sep ...string) []string +func ToStrings(s string, sep ...string) []string +func ToSlice(s string, sep ...string) []string +func ToOSArgs(s string) []string +func MustToTime(s string, layouts ...string) time.Time +func ToTime(s string, layouts ...string) (t time.Time, err error) +func ToDuration(s string) (time.Duration, error) // source at strutil/crypto.go -func Md5(src any) string -func MD5(src any) string { return Md5(src) } -func GenMd5(src any) string { return Md5(src) } -func Md5Bytes(src any) []byte -func HashPasswd(pwd, key string) string -func VerifyPasswd(pwdMAC, pwd, key string) bool +func Md5(src any) string +func MD5(src any) string +func GenMd5(src any) string +func Md5Bytes(src any) []byte +func HashPasswd(pwd, key string) string +func VerifyPasswd(pwdMAC, pwd, key string) bool // source at strutil/encode.go -func EscapeJS(s string) string -func EscapeHTML(s string) string -func AddSlashes(s string) string -func StripSlashes(s string) string -func URLEncode(s string) string -func URLDecode(s string) string -func B32Encode(str string) string -func B32Decode(str string) string -func B64Encode(str string) string -func B64EncodeBytes(src []byte) []byte -func B64Decode(str string) string -func B64DecodeBytes(str string) []byte -func Encoding(base int, typ BaseType) BaseEncoder +func EscapeJS(s string) string +func EscapeHTML(s string) string +func AddSlashes(s string) string +func StripSlashes(s string) string +func URLEncode(s string) string +func URLDecode(s string) string +func B32Encode(str string) string +func B32Decode(str string) string +func B64Encode(str string) string +func B64EncodeBytes(src []byte) []byte +func B64Decode(str string) string +func B64DecodeBytes(str string) []byte +func Encoding(base int, typ BaseType) BaseEncoder // source at strutil/filter.go -func Trim(s string, cutSet ...string) string -func Ltrim(s string, cutSet ...string) string { return TrimLeft(s, cutSet...) } -func LTrim(s string, cutSet ...string) string { return TrimLeft(s, cutSet...) } -func TrimLeft(s string, cutSet ...string) string -func Rtrim(s string, cutSet ...string) string { return TrimRight(s, cutSet...) } -func RTrim(s string, cutSet ...string) string { return TrimRight(s, cutSet...) } -func TrimRight(s string, cutSet ...string) string -func FilterEmail(s string) string +func Trim(s string, cutSet ...string) string +func Ltrim(s string, cutSet ...string) string +func LTrim(s string, cutSet ...string) string +func TrimLeft(s string, cutSet ...string) string +func Rtrim(s string, cutSet ...string) string +func RTrim(s string, cutSet ...string) string +func TrimRight(s string, cutSet ...string) string +func FilterEmail(s string) string // source at strutil/format.go -func Title(s string) string { return strings.ToTitle(s) } -func Lower(s string) string { return strings.ToLower(s) } -func Lowercase(s string) string { return strings.ToLower(s) } -func Upper(s string) string { return strings.ToUpper(s) } -func Uppercase(s string) string { return strings.ToUpper(s) } -func UpperWord(s string) string -func LowerFirst(s string) string -func UpperFirst(s string) string -func SnakeCase(s string, sep ...string) string -func Camel(s string, sep ...string) string { return CamelCase(s, sep...) } -func CamelCase(s string, sep ...string) string -func Indent(s, prefix string) string -func IndentBytes(b, prefix []byte) []byte +func Title(s string) string +func Lower(s string) string +func Lowercase(s string) string +func Upper(s string) string +func Uppercase(s string) string +func UpperWord(s string) string +func LowerFirst(s string) string +func UpperFirst(s string) string +func SnakeCase(s string, sep ...string) string +func Camel(s string, sep ...string) string +func CamelCase(s string, sep ...string) string +func Indent(s, prefix string) string +func IndentBytes(b, prefix []byte) []byte // source at strutil/id.go -func MicroTimeID() string -func MicroTimeHexID() string +func MicroTimeID() string +func MicroTimeHexID() string // source at strutil/padding.go -func Padding(s, pad string, length int, pos PosFlag) string -func PadLeft(s, pad string, length int) string -func PadRight(s, pad string, length int) string -func Resize(s string, length int, align PosFlag) string -func PadBytes(bs []byte, pad byte, length int, pos PosFlag) []byte -func PadBytesLeft(bs []byte, pad byte, length int) []byte -func PadBytesRight(bs []byte, pad byte, length int) []byte -func PadRunes(rs []rune, pad rune, length int, pos PosFlag) []rune -func PadRunesLeft(rs []rune, pad rune, length int) []rune -func PadRunesRight(rs []rune, pad rune, length int) []rune -func Repeat(s string, times int) string -func RepeatRune(char rune, times int) []rune -func RepeatBytes(char byte, times int) []byte +func Padding(s, pad string, length int, pos PosFlag) string +func PadLeft(s, pad string, length int) string +func PadRight(s, pad string, length int) string +func Resize(s string, length int, align PosFlag) string +func PadBytes(bs []byte, pad byte, length int, pos PosFlag) []byte +func PadBytesLeft(bs []byte, pad byte, length int) []byte +func PadBytesRight(bs []byte, pad byte, length int) []byte +func PadRunes(rs []rune, pad rune, length int, pos PosFlag) []rune +func PadRunesLeft(rs []rune, pad rune, length int) []rune +func PadRunesRight(rs []rune, pad rune, length int) []rune +func Repeat(s string, times int) string +func RepeatRune(char rune, times int) []rune +func RepeatBytes(char byte, times int) []byte // source at strutil/random.go -func RandomChars(ln int) string -func RandomCharsV2(ln int) string -func RandomCharsV3(ln int) string -func RandomBytes(length int) ([]byte, error) -func RandomString(length int) (string, error) +func RandomChars(ln int) string +func RandomCharsV2(ln int) string +func RandomCharsV3(ln int) string +func RandomBytes(length int) ([]byte, error) +func RandomString(length int) (string, error) // source at strutil/runes.go -func RuneIsWord(c rune) bool -func RuneIsLower(c rune) bool -func RuneIsUpper(c rune) bool -func RunePos(s string, ru rune) int { return strings.IndexRune(s, ru) } -func IsSpaceRune(r rune) bool -func Utf8Len(s string) int { return utf8.RuneCountInString(s) } -func Utf8len(s string) int { return utf8.RuneCountInString(s) } -func RuneCount(s string) int { return len([]rune(s)) } -func RuneWidth(r rune) int -func TextWidth(s string) int { return Utf8Width(s) } -func Utf8Width(s string) int { return RunesWidth([]rune(s)) } -func RunesWidth(rs []rune) (w int) -func TextTruncate(s string, w int, tail string) string { return Utf8Truncate(s, w, tail) } -func Utf8Truncate(s string, w int, tail string) string -func TextSplit(s string, w int) []string { return Utf8Split(s, w) } -func Utf8Split(s string, w int) []string -func TextWrap(s string, w int) string { return WidthWrap(s, w) } -func WidthWrap(s string, w int) string -func WordWrap(s string, w int) string +func RuneIsWord(c rune) bool +func RuneIsLower(c rune) bool +func RuneIsUpper(c rune) bool +func RunePos(s string, ru rune) int +func IsSpaceRune(r rune) bool +func Utf8Len(s string) int +func Utf8len(s string) int +func RuneCount(s string) int +func RuneWidth(r rune) int +func TextWidth(s string) int +func Utf8Width(s string) int +func RunesWidth(rs []rune) (w int) +func TextTruncate(s string, w int, tail string) string +func Utf8Truncate(s string, w int, tail string) string +func TextSplit(s string, w int) []string +func Utf8Split(s string, w int) []string +func TextWrap(s string, w int) string +func WidthWrap(s string, w int) string +func WordWrap(s string, w int) string // source at strutil/similar_find.go -func NewComparator(src, dst string) *SimilarComparator -func Similarity(s, t string, rate float32) (float32, bool) +func NewComparator(src, dst string) *SimilarComparator +func Similarity(s, t string, rate float32) (float32, bool) // source at strutil/split.go -func Cut(s, sep string) (before string, after string, found bool) -func MustCut(s, sep string) (before string, after string) -func TrimCut(s, sep string) (string, string) -func SplitValid(s, sep string) (ss []string) { return Split(s, sep) } -func Split(s, sep string) (ss []string) -func SplitNValid(s, sep string, n int) (ss []string) { return SplitN(s, sep, n) } -func SplitN(s, sep string, n int) (ss []string) -func SplitTrimmed(s, sep string) (ss []string) -func SplitNTrimmed(s, sep string, n int) (ss []string) -func Substr(s string, pos, length int) string -func SplitInlineComment(val string) (string, string) +func Cut(s, sep string) (before string, after string, found bool) +func MustCut(s, sep string) (before string, after string) +func TrimCut(s, sep string) (string, string) +func SplitValid(s, sep string) (ss []string) +func Split(s, sep string) (ss []string) +func SplitNValid(s, sep string, n int) (ss []string) +func SplitN(s, sep string, n int) (ss []string) +func SplitTrimmed(s, sep string) (ss []string) +func SplitNTrimmed(s, sep string, n int) (ss []string) +func Substr(s string, pos, length int) string +func SplitInlineComment(val string) (string, string) // source at strutil/strutil.go -func Replaces(str string, pairs map[string]string) string -func PrettyJSON(v any) (string, error) -func RenderTemplate(input string, data any, fns template.FuncMap, isFile ...bool) string -func RenderText(input string, data any, fns template.FuncMap, isFile ...bool) string -func WrapTag(s, tag string) string +func Replaces(str string, pairs map[string]string) string +func PrettyJSON(v any) (string, error) +func RenderTemplate(input string, data any, fns template.FuncMap, isFile ...bool) string +func RenderText(input string, data any, fns template.FuncMap, isFile ...bool) string +func WrapTag(s, tag string) string +func SubstrCount(s string, substr string, params ...uint64) (int, error) ``` ### System Utils @@ -1106,59 +1120,59 @@ func WrapTag(s, tag string) string ```go // source at sysutil/exec.go -func NewCmd(bin string, args ...string) *cmdr.Cmd -func FlushExec(bin string, args ...string) error -func QuickExec(cmdLine string, workDir ...string) (string, error) -func ExecLine(cmdLine string, workDir ...string) (string, error) -func ExecCmd(binName string, args []string, workDir ...string) (string, error) -func ShellExec(cmdLine string, shells ...string) (string, error) +func NewCmd(bin string, args ...string) *cmdr.Cmd +func FlushExec(bin string, args ...string) error +func QuickExec(cmdLine string, workDir ...string) (string, error) +func ExecLine(cmdLine string, workDir ...string) (string, error) +func ExecCmd(binName string, args []string, workDir ...string) (string, error) +func ShellExec(cmdLine string, shells ...string) (string, error) // source at sysutil/stack.go -func CallersInfos(skip, num int, filters ...func(file string, fc *runtime.Func) bool) []*CallerInfo +func CallersInfos(skip, num int, filters ...func(file string, fc *runtime.Func) bool) []*CallerInfo // source at sysutil/sysenv.go -func IsMSys() bool -func IsConsole(out io.Writer) bool -func IsTerminal(fd uintptr) bool -func StdIsTerminal() bool -func Hostname() string -func CurrentShell(onlyName bool) (path string) -func HasShellEnv(shell string) bool -func IsShellSpecialVar(c uint8) bool -func EnvPaths() []string -func FindExecutable(binName string) (string, error) -func Executable(binName string) (string, error) -func HasExecutable(binName string) bool -func SearchPath(keywords string) []string +func IsMSys() bool +func IsConsole(out io.Writer) bool +func IsTerminal(fd uintptr) bool +func StdIsTerminal() bool +func Hostname() string +func CurrentShell(onlyName bool) (path string) +func HasShellEnv(shell string) bool +func IsShellSpecialVar(c uint8) bool +func EnvPaths() []string +func FindExecutable(binName string) (string, error) +func Executable(binName string) (string, error) +func HasExecutable(binName string) bool +func SearchPath(keywords string) []string // source at sysutil/sysgo.go -func GoVersion() string -func ParseGoVersion(line string) (*GoInfo, error) -func OsGoInfo() (*GoInfo, error) +func GoVersion() string +func ParseGoVersion(line string) (*GoInfo, error) +func OsGoInfo() (*GoInfo, error) // source at sysutil/sysutil.go -func Workdir() string -func BinDir() string -func BinFile() string +func Workdir() string +func BinDir() string +func BinFile() string // source at sysutil/sysutil_nonwin.go -func IsWin() bool -func IsWindows() bool -func IsMac() bool -func IsDarwin() bool -func IsLinux() bool -func Kill(pid int, signal syscall.Signal) error -func ProcessExists(pid int) bool -func OpenBrowser(URL string) error +func IsWin() bool +func IsWindows() bool +func IsMac() bool +func IsDarwin() bool +func IsLinux() bool +func Kill(pid int, signal syscall.Signal) error +func ProcessExists(pid int) bool +func OpenBrowser(URL string) error // source at sysutil/user.go -func MustFindUser(uname string) *user.User -func LoginUser() *user.User -func CurrentUser() *user.User -func UHomeDir() string -func UserHomeDir() string -func HomeDir() string -func UserDir(subPath string) string -func UserCacheDir(subPath string) string -func UserConfigDir(subPath string) string -func ExpandPath(path string) string +func MustFindUser(uname string) *user.User +func LoginUser() *user.User +func CurrentUser() *user.User +func UHomeDir() string +func UserHomeDir() string +func HomeDir() string +func UserDir(subPath string) string +func UserCacheDir(subPath string) string +func UserConfigDir(subPath string) string +func ExpandPath(path string) string // source at sysutil/user_nonwin.go -func ChangeUserByName(newUname string) (err error) -func ChangeUserUidGid(newUid int, newGid int) (err error) +func ChangeUserByName(newUname string) (err error) +func ChangeUserUidGid(newUid int, newGid int) (err error) ``` ### Testing Utils @@ -1167,27 +1181,27 @@ func ChangeUserUidGid(newUid int, newGid int) (err error) ```go // source at testutil/buffer.go -func NewBuffer() *Buffer +func NewBuffer() *Buffer // source at testutil/envmock.go -func MockEnvValue(key, val string, fn func(nv string)) -func MockEnvValues(kvMap map[string]string, fn func()) -func MockOsEnvByText(envText string, fn func()) -func MockOsEnv(mp map[string]string, fn func()) -func ClearOSEnv() { os.Clearenv() } -func RevertOSEnv() -func MockCleanOsEnv(mp map[string]string, fn func()) +func MockEnvValue(key, val string, fn func(nv string)) +func MockEnvValues(kvMap map[string]string, fn func()) +func MockOsEnvByText(envText string, fn func()) +func MockOsEnv(mp map[string]string, fn func()) +func ClearOSEnv() +func RevertOSEnv() +func MockCleanOsEnv(mp map[string]string, fn func()) // source at testutil/httpmock.go -func NewHttpRequest(method, path string, data *MD) *http.Request -func MockRequest(h http.Handler, method, path string, data *MD) *httptest.ResponseRecorder +func NewHttpRequest(method, path string, data *MD) *http.Request +func MockRequest(h http.Handler, method, path string, data *MD) *httptest.ResponseRecorder // source at testutil/testutil.go -func DiscardStdout() error -func ReadOutput() (s string) -func RewriteStdout() -func RestoreStdout(printData ...bool) (s string) -func RewriteStderr() -func RestoreStderr(printData ...bool) (s string) +func DiscardStdout() error +func ReadOutput() (s string) +func RewriteStdout() +func RestoreStdout(printData ...bool) (s string) +func RewriteStderr() +func RestoreStderr(printData ...bool) (s string) // source at testutil/writer.go -func NewTestWriter() *TestWriter +func NewTestWriter() *TestWriter ``` ### Timex @@ -1197,46 +1211,46 @@ func NewTestWriter() *TestWriter Provides an enhanced time.Time implementation, and add more commonly used functional methods. ```go // source at timex/template.go -func ToLayout(template string) string +func ToLayout(template string) string // source at timex/timex.go -func Now() *Time -func New(t time.Time) *Time -func Wrap(t time.Time) *Time -func FromTime(t time.Time) *Time -func Local() *Time -func FromUnix(sec int64) *Time -func FromDate(s string, template ...string) (*Time, error) -func FromString(s string, layouts ...string) (*Time, error) -func LocalByName(tzName string) *Time +func Now() *Time +func New(t time.Time) *Time +func Wrap(t time.Time) *Time +func FromTime(t time.Time) *Time +func Local() *Time +func FromUnix(sec int64) *Time +func FromDate(s string, template ...string) (*Time, error) +func FromString(s string, layouts ...string) (*Time, error) +func LocalByName(tzName string) *Time // source at timex/util.go -func NowUnix() int64 -func SetLocalByName(tzName string) error -func Format(t time.Time) string -func FormatBy(t time.Time, layout string) string -func Date(t time.Time, template string) string -func DateFormat(t time.Time, template string) string -func FormatByTpl(t time.Time, template string) string -func FormatUnix(sec int64) string -func FormatUnixBy(sec int64, layout string) string -func FormatUnixByTpl(sec int64, template string) string -func NowAddDay(day int) time.Time -func NowAddHour(hour int) time.Time -func NowAddMinutes(minutes int) time.Time -func NowAddSeconds(seconds int) time.Time -func NowHourStart() time.Time -func NowHourEnd() time.Time -func AddDay(t time.Time, day int) time.Time -func AddHour(t time.Time, hour int) time.Time -func AddMinutes(t time.Time, minutes int) time.Time -func AddSeconds(t time.Time, seconds int) time.Time -func HourStart(t time.Time) time.Time -func HourEnd(t time.Time) time.Time -func DayStart(t time.Time) time.Time -func DayEnd(t time.Time) time.Time -func TodayStart() time.Time -func TodayEnd() time.Time -func HowLongAgo(sec int64) string -func ToDuration(s string) (time.Duration, error) +func NowUnix() int64 +func SetLocalByName(tzName string) error +func Format(t time.Time) string +func FormatBy(t time.Time, layout string) string +func Date(t time.Time, template string) string +func DateFormat(t time.Time, template string) string +func FormatByTpl(t time.Time, template string) string +func FormatUnix(sec int64) string +func FormatUnixBy(sec int64, layout string) string +func FormatUnixByTpl(sec int64, template string) string +func NowAddDay(day int) time.Time +func NowAddHour(hour int) time.Time +func NowAddMinutes(minutes int) time.Time +func NowAddSeconds(seconds int) time.Time +func NowHourStart() time.Time +func NowHourEnd() time.Time +func AddDay(t time.Time, day int) time.Time +func AddHour(t time.Time, hour int) time.Time +func AddMinutes(t time.Time, minutes int) time.Time +func AddSeconds(t time.Time, seconds int) time.Time +func HourStart(t time.Time) time.Time +func HourEnd(t time.Time) time.Time +func DayStart(t time.Time) time.Time +func DayEnd(t time.Time) time.Time +func TodayStart() time.Time +func TodayEnd() time.Time +func HowLongAgo(sec int64) string +func ToDuration(s string) (time.Duration, error) ``` #### Timex Usage @@ -1357,6 +1371,116 @@ date := FormatUnixByTpl(ts, "Y-m-d H:I:S") // Get: 2022-04-20 19:40:34 ``` +## Code Check & Testing + +```bash +gofmt -w -l ./ +golint ./... + +# testing +go test -v ./... +go test -v -run ^TestErr$ +go test -v -run ^TestErr$ ./testutil/assert/... +``` + +## Related + +- https://github.com/duke-git/lancet +- https://github.com/samber/lo +- https://github.com/zyedidia/generic +- https://github.com/thoas/go-funk + +## Gookit packages + +- [gookit/ini](https://github.com/gookit/ini) Go config management, use INI files +- [gookit/rux](https://github.com/gookit/rux) Simple and fast request router for golang HTTP +- [gookit/gcli](https://github.com/gookit/gcli) Build CLI application, tool library, running CLI commands +- [gookit/slog](https://github.com/gookit/slog) Lightweight, easy to extend, configurable logging library written in Go +- [gookit/color](https://github.com/gookit/color) A command-line color library with true color support, universal API methods and Windows support +- [gookit/event](https://github.com/gookit/event) Lightweight event manager and dispatcher implements by Go +- [gookit/cache](https://github.com/gookit/cache) Generic cache use and cache manager for golang. support File, Memory, Redis, Memcached. +- [gookit/config](https://github.com/gookit/config) Go config management. support JSON, YAML, TOML, INI, HCL, ENV and Flags +- [gookit/filter](https://github.com/gookit/filter) Provide filtering, sanitizing, and conversion of golang data +- [gookit/validate](https://github.com/gookit/validate) Use for data validation and filtering. support Map, Struct, Form data +- [gookit/goutil](https://github.com/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](LICENSE) +AddSeconds(120) +``` + +compare time: + +```go +// before compare +tx.IsBefore(u time.Time) +tx.IsBeforeUnix(1647411580) +// after compare +tx.IsAfter(u time.Time) +tx.IsAfterUnix(1647411580) +``` + +**Helper functions** + +```go +ts := timex.NowUnix() // current unix timestamp + +t := NowAddDay(1) // from now add 1 day +t := NowAddHour(1) // from now add 1 hour +t := NowAddMinutes(3) // from now add 3 minutes +t := NowAddSeconds(180) // from now add 180 seconds +``` + +**Convert time to date by template** + +Template Chars: + +```text + Y,y - year + Y - year 2006 + y - year 06 + m - month 01-12 + d - day 01-31 + H,h - hour + H - hour 00-23 + h - hour 01-12 + I,i - minute + I - minute 00-59 + i - minute 0-59 + S,s - second + S - second 00-59 + s - second 0-59 +``` + +> More, please see [char map](./timex/template.go) + +Examples, use timex: + +```go +tx := timex.Now() +date := tx.DateFormat("Y-m-d H:I:S") // Output: 2022-04-20 19:09:03 +date = tx.DateFormat("y-m-d h:i:s") // Output: 22-04-20 07:9:3 +``` + +Format time.Time: + +```go +tx := time.Now() +date := timex.DateFormat(tx, "Y-m-d H:I:S") // Output: 2022-04-20 19:40:34 +``` + +More usage: + +```go +ts := timex.NowUnix() // current unix timestamp + +date := FormatUnix(ts, "2006-01-02 15:04:05") // Get: 2022-04-20 19:40:34 +date := FormatUnixByTpl(ts, "Y-m-d H:I:S") // Get: 2022-04-20 19:40:34 +``` + + ## Code Check & Testing ```bash diff --git a/dump/dump.go b/dump/dump.go index a7f5a8bfb..4894957f1 100644 --- a/dump/dump.go +++ b/dump/dump.go @@ -19,7 +19,6 @@ const ( ) const defaultSkip = 3 -const defaultSkip2 = 2 var ( // valid flag for print caller info diff --git a/fsutil/finder/finder.go b/fsutil/finder/finder.go index ceabf074c..bd266a45c 100644 --- a/fsutil/finder/finder.go +++ b/fsutil/finder/finder.go @@ -270,7 +270,7 @@ func (f *FileFinder) findInDir(dirPath string) { ok := true for _, df := range f.dirFilters { ok = df.FilterDir(fullPath, baseName) - if true == ok { // 有一个满足即可 + if ok { // 有一个满足即可 break } } diff --git a/fsutil/operate.go b/fsutil/operate.go index 310252428..0d55aa07b 100644 --- a/fsutil/operate.go +++ b/fsutil/operate.go @@ -4,7 +4,6 @@ import ( "archive/zip" "fmt" "io" - "io/ioutil" "os" "path" "path/filepath" @@ -27,12 +26,12 @@ func MkParentDir(fpath string) error { // DiscardReader anything from the reader func DiscardReader(src io.Reader) { - _, _ = io.Copy(ioutil.Discard, src) + _, _ = io.Copy(io.Discard, src) } // MustReadFile read file contents, will panic on error func MustReadFile(filePath string) []byte { - bs, err := ioutil.ReadFile(filePath) + bs, err := os.ReadFile(filePath) if err != nil { panic(err) } @@ -42,8 +41,7 @@ func MustReadFile(filePath string) []byte { // MustReadReader read contents from io.Reader, will panic on error func MustReadReader(r io.Reader) []byte { - // TODO go 1.16+ bs, err := io.ReadAll(r) - bs, err := ioutil.ReadAll(r) + bs, err := io.ReadAll(r) if err != nil { panic(err) } @@ -66,7 +64,7 @@ func GetContents(in any) []byte { // ReadExistFile read file contents if existed, will panic on error func ReadExistFile(filePath string) []byte { if IsFile(filePath) { - bs, err := ioutil.ReadFile(filePath) + bs, err := os.ReadFile(filePath) if err != nil { panic(err) } diff --git a/internal/gendoc/main.go b/internal/gendoc/main.go index b80b0fa64..348b946f5 100644 --- a/internal/gendoc/main.go +++ b/internal/gendoc/main.go @@ -242,7 +242,12 @@ func collectPgkFunc(ms []string, basePkg string) *bytes.Buffer { if len(lines) > 0 { bufWriteln(buf, "// source at", filename) for _, line := range lines { - bufWriteln(buf, strings.TrimRight(line, "{ ")) + idx := strings.IndexByte(line, '{') + if idx > 0 { + bufWriteln(buf, line[:idx]) + } else { + bufWriteln(buf, line) + } } } } diff --git a/jsonutil/jsonutil.go b/jsonutil/jsonutil.go index 11be66ed3..b1206b8ad 100644 --- a/jsonutil/jsonutil.go +++ b/jsonutil/jsonutil.go @@ -5,7 +5,6 @@ import ( "bytes" "encoding/json" "io" - "io/ioutil" "os" "regexp" "strings" @@ -18,7 +17,7 @@ func WriteFile(filePath string, data any) error { if err != nil { return err } - return ioutil.WriteFile(filePath, jsonBytes, 0664) + return os.WriteFile(filePath, jsonBytes, 0664) } // ReadFile Read JSON file data diff --git a/stdutil/conv_test.go b/stdutil/conv_test.go index 10b16222a..472eec6c2 100644 --- a/stdutil/conv_test.go +++ b/stdutil/conv_test.go @@ -66,5 +66,6 @@ func TestBaseTypeVal(t *testing.T) { assert.Err(t, err) val, err = stdutil.BaseTypeVal2(reflect.ValueOf(int32(2))) + assert.NoErr(t, err) assert.Eq(t, int64(2), val) } diff --git a/structs/setval.go b/structs/setval.go index 6461540f0..9eaaf1219 100644 --- a/structs/setval.go +++ b/structs/setval.go @@ -163,7 +163,7 @@ func SetValues(ptr any, data map[string]any, optFns ...SetOptFunc) error { } func setValues(rv reflect.Value, data map[string]any, opt *SetOptions) error { - if data == nil || len(data) == 0 { + if len(data) == 0 { return nil } diff --git a/strutil/secutil/aes_crypt.go b/strutil/secutil/aes_crypt.go index 12eb21f7f..0ed7a0a66 100644 --- a/strutil/secutil/aes_crypt.go +++ b/strutil/secutil/aes_crypt.go @@ -46,9 +46,9 @@ type AesCrypt struct { iv []byte key []byte - init bool - keyLen int - padding string + init bool + keyLen int + // padding string encryptType string } diff --git a/testutil/assert/assertions_methods.go b/testutil/assert/assertions_methods.go index 8d014ad2f..91ee53a99 100644 --- a/testutil/assert/assertions_methods.go +++ b/testutil/assert/assertions_methods.go @@ -13,48 +13,56 @@ func (as *Assertions) NotNil(val any, fmtAndArgs ...any) *Assertions { return as } +// True check, please see True() func (as *Assertions) True(give bool, fmtAndArgs ...any) *Assertions { as.t.Helper() as.ok = True(as.t, give, fmtAndArgs...) return as } +// False check, please see False() func (as *Assertions) False(give bool, fmtAndArgs ...any) *Assertions { as.t.Helper() as.ok = False(as.t, give, fmtAndArgs...) return as } +// Empty check, please see Empty() func (as *Assertions) Empty(give any, fmtAndArgs ...any) *Assertions { as.t.Helper() as.ok = Empty(as.t, give, fmtAndArgs...) return as } +// NotEmpty check, please see NotEmpty() func (as *Assertions) NotEmpty(give any, fmtAndArgs ...any) *Assertions { as.t.Helper() as.ok = NotEmpty(as.t, give, fmtAndArgs...) return as } +// Panics check, please see Panics() func (as *Assertions) Panics(fn PanicRunFunc, fmtAndArgs ...any) *Assertions { as.t.Helper() as.ok = Panics(as.t, fn, fmtAndArgs...) return as } +// NotPanics check, please see NotPanics() func (as *Assertions) NotPanics(fn PanicRunFunc, fmtAndArgs ...any) *Assertions { as.t.Helper() as.ok = NotPanics(as.t, fn, fmtAndArgs...) return as } +// PanicsMsg check, please see PanicsMsg() func (as *Assertions) PanicsMsg(fn PanicRunFunc, wantVal any, fmtAndArgs ...any) *Assertions { as.t.Helper() as.ok = PanicsMsg(as.t, fn, wantVal, fmtAndArgs...) return as } +// PanicsErrMsg check, please see PanicsErrMsg() func (as *Assertions) PanicsErrMsg(fn PanicRunFunc, errMsg string, fmtAndArgs ...any) *Assertions { as.t.Helper() as.ok = PanicsErrMsg(as.t, fn, errMsg, fmtAndArgs...) diff --git a/testutil/assert/util.go b/testutil/assert/util.go index d6c81ecc8..99b6914de 100644 --- a/testutil/assert/util.go +++ b/testutil/assert/util.go @@ -58,7 +58,14 @@ func truncatingFormat(data any) string { return "" } - value := fmt.Sprintf("%T(%v)", data, data) + var value string + switch data.(type) { + case string: + value = fmt.Sprintf("string(%q)", data) + default: + value = fmt.Sprintf("%T(%v)", data, data) + } + // Give us some space the type info too if needed. max := bufio.MaxScanTokenSize - 100 if len(value) > max {