### Install goutil/x/finder Source: https://github.com/gookit/goutil/blob/master/x/finder/README.md Install the finder package using go get. ```shell go get github.com/gookit/goutil/x/finder ``` -------------------------------- ### Install strutil Package Source: https://github.com/gookit/goutil/blob/master/strutil/README.md Use 'go get' to install the strutil package. ```bash go get github.com/gookit/goutil/strutil ``` -------------------------------- ### Install assert package Source: https://github.com/gookit/goutil/blob/master/testutil/assert/README.md Install the assert package using go get. ```bash go get github.com/gookit/goutil/x/assert ``` -------------------------------- ### Install Goutil Clipboard Source: https://github.com/gookit/goutil/blob/master/x/clipboard/README.md Install the clipboard package using go get. ```bash go get github.com/gookit/goutil/x/clipboard ``` -------------------------------- ### Install Netutil Package Source: https://github.com/gookit/goutil/blob/master/netutil/README.md Install the netutil package using go get. ```bash go get github.com/gookit/goutil/netutil ``` -------------------------------- ### Install testutil Package Source: https://github.com/gookit/goutil/blob/master/testutil/README.md Install the testutil package using go get. ```bash go get github.com/gookit/goutil/testutil ``` -------------------------------- ### Install Mathutil Package Source: https://github.com/gookit/goutil/blob/master/mathutil/README.md Install the mathutil package using go get. ```bash go get github.com/gookit/goutil/mathutil ``` -------------------------------- ### Install fsutil Package Source: https://github.com/gookit/goutil/blob/master/fsutil/README.md Install the fsutil package using go get. ```shell go get github.com/gookit/goutil/fsutil ``` -------------------------------- ### Install httpreq Package Source: https://github.com/gookit/goutil/blob/master/netutil/httpreq/README.md Install the httpreq package using go get. ```bash go get github.com/gookit/goutil/netutil/httpreq ``` -------------------------------- ### Install Goutil GoInfo Source: https://github.com/gookit/goutil/blob/master/x/goinfo/README.md Use 'go get' to install the goinfo package for your project. ```bash go get github.com/gookit/goutil/x/goinfo ``` -------------------------------- ### Install textscan Package Source: https://github.com/gookit/goutil/blob/master/strutil/textscan/README.md Install the textscan package using go get. ```shell go get github.com/gookit/goutil/strutil/textscan ``` -------------------------------- ### Install maputil Package Source: https://github.com/gookit/goutil/blob/master/maputil/README.md Install the maputil package using the go get command. ```bash go get github.com/gookit/goutil/maputil ``` -------------------------------- ### Install arrutil Package Source: https://github.com/gookit/goutil/blob/master/arrutil/README.md Use 'go get' to install the arrutil package. This command fetches and installs the package and its dependencies. ```shell go get github.com/gookit/goutil/arrutil ``` -------------------------------- ### Install cliutil Package Source: https://github.com/gookit/goutil/blob/master/cliutil/README.md Use 'go get' to install the cliutil package. ```shell go get -u github.com/gookit/goutil/cliutil ``` -------------------------------- ### Install Goutil Dump Package Source: https://github.com/gookit/goutil/blob/master/dump/README.md Use 'go get' to install the goutil/dump package. ```bash go get github.com/gookit/goutil/dump ``` -------------------------------- ### Install Goutil Source: https://github.com/gookit/goutil/blob/master/README.md Install the Gookit Goutil library using the go get command. ```shell go get github.com/gookit/goutil ``` -------------------------------- ### Running the cflag Example Command Source: https://github.com/gookit/goutil/blob/master/cflag/README.md Examples of how to run the compiled cflag command with different argument and option combinations. ```shell go run ./cflag/_example/cmd.go --name inhere -a 12 --lo val ab cd ``` ```shell go run ./cflag/_example/cmd.go ab --name inhere -a 12 --lo val cd ``` -------------------------------- ### Create and Use HTTP Client Source: https://github.com/gookit/goutil/blob/master/netutil/httpreq/README.md Shows how to create a new HTTP client with a base URL and send GET and POST requests. ```go package main import ( "fmt" "github.com/gookit/goutil/netutil/httpreq" ) func main() { // create a client client := httpreq.New("http://httpbin.org") // Send a GET request resp, err := client.Get("/get") fmt.Println(httpreq.ResponseToString(resp), err) // Send a POST request resp, err = client.Post("/post", `{"name":"inhere"}`, httpreq.WithJSONType) fmt.Println(httpreq.ResponseToString(resp), err) } ``` -------------------------------- ### Install Timex Package Source: https://github.com/gookit/goutil/blob/master/timex/README.md Use 'go get' to install the timex package. This command fetches and installs the package and its dependencies. ```go go get github.com/gookit/goutil/timex ``` -------------------------------- ### Install envutil Package Source: https://github.com/gookit/goutil/blob/master/envutil/README.md Install the envutil package using go get. ```shell go get github.com/gookit/goutil/envutil ``` -------------------------------- ### Install CColor Package Source: https://github.com/gookit/goutil/blob/master/x/ccolor/README.md Use 'go get' to install the CColor package for your Go project. This command fetches and installs the library, making it available for import. ```bash go get github.com/gookit/goutil/x/ccolor ``` -------------------------------- ### Install reflects Package Source: https://github.com/gookit/goutil/blob/master/reflects/README.md Use 'go get' to install the reflects package. This command fetches and installs the specified package and its dependencies. ```bash go get github.com/gookit/goutil/reflects ``` -------------------------------- ### Install stdio Package Source: https://github.com/gookit/goutil/blob/master/x/stdio/README.md Use this command to install the stdio package for your Go project. ```bash go get github.com/gookit/goutil/x/stdio ``` -------------------------------- ### Install cflag Package Source: https://github.com/gookit/goutil/blob/master/cflag/README.md Install the cflag package using the go get command. ```shell go get github.com/gookit/goutil/cflag ``` -------------------------------- ### Install byteutil Package Source: https://github.com/gookit/goutil/blob/master/byteutil/README.md Use this command to install the byteutil package. ```shell go get github.com/gookit/goutil/byteutil ``` -------------------------------- ### Install errorx Package Source: https://github.com/gookit/goutil/blob/master/errorx/README.md Use 'go get' to install the errorx package for your Go project. ```go go get github.com/gookit/goutil/errorx ``` -------------------------------- ### Build Multi-Command App with Capp Source: https://github.com/gookit/goutil/blob/master/cflag/README.md Example of creating a multi-command CLI application using capp. Defines options, arguments, and command functions. ```go package main import ( "fmt" "github.com/gookit/goutil/cflag/capp" ) var demoOpts = struct { age int name string }{} func main() { app := capp.NewApp() app.Name = "myapp" app.Desc = "this is my cli application" app.Version = "1.0.2" cmd := capp.NewCmd("demo", "this is a demo command") cmd.IntVar(&demoOpts.age, "age", 0, "this is an int option;;a") cmd.StringVar(&demoOpts.name, "name", "", "this is a string option and required;true") cmd.AddArg("arg1", "this is arg1", true, nil) cmd.AddArg("arg2", "this is arg2", false, nil) cmd.Func = func(c *capp.Cmd) error { fmt.Println("age:", demoOpts.age) fmt.Println("name:", demoOpts.name) fmt.Println("arg1:", c.Arg("arg1").String()) fmt.Println("arg2:", c.Arg("arg2").String()) return nil } app.Add(cmd) app.Run() } ``` -------------------------------- ### Get Go Version Source: https://github.com/gookit/goutil/blob/master/x/goinfo/README.md Retrieve the current Go version string. Example output is '1.15.6'. ```go gover := goinfo.GoVersion() // eg: "1.15.6" ``` -------------------------------- ### Check Operating System Source: https://github.com/gookit/goutil/blob/master/internal/gendoc/template/readme-parts/envutil.md Use these functions to determine the current operating system. No setup is required. ```go envutil.IsWin() envutil.IsMac() envutil.IsLinux() ``` -------------------------------- ### Run Specific Go Tests by Regexp Source: https://github.com/gookit/goutil/blob/master/arrutil/README.md Runs tests that match a regular expression. This example runs tests starting with 'TestSetByKeys' in the cliutil package. ```shell go test -v -run ^TestSetByKeys ./cliutil/... ``` -------------------------------- ### Example Usage Source: https://github.com/gookit/goutil/blob/master/reflects/README.md Demonstrates how to use the reflects package to get a struct field value. ```APIDOC ```go import "github.com/gookit/goutil/reflects" // get struct field value reflects.GetFieldValue(obj, "Name") ``` ``` -------------------------------- ### Basic Usage Source: https://github.com/gookit/goutil/blob/master/netutil/httpreq/README.md Demonstrates how to send GET and POST requests using the package's top-level functions. ```APIDOC ## Basic Usage This section shows how to perform basic HTTP requests like GET and POST using the package's exported functions. ### Example: ```go package main import ( "fmt" "github.com/gookit/goutil/netutil/httpreq" ) func main() { // Send a GET request resp, err := httpreq.Get("http://httpbin.org/get") fmt.Println(httpreq.ResponseToString(resp), err) // Send a POST request resp, err = httpreq.Post("http://httpbin.org/post", `{"name":"inhere"}`, httpreq.WithJSONType) fmt.Println(httpreq.ResponseToString(resp), err) } ``` ``` -------------------------------- ### Run Specific Tests by Regexp Source: https://github.com/gookit/goutil/blob/master/strutil/README.md Filter and run tests in the strutil package that match a specific regular expression. This example runs tests starting with 'TestSetByKeys'. ```shell go test -v -run ^TestSetByKeys ./strutil/... ``` -------------------------------- ### Send GET and POST Requests Source: https://github.com/gookit/goutil/blob/master/netutil/httpreq/README.md Demonstrates sending a GET request to a URL and a POST request with JSON data using the global functions. ```go package main import ( "fmt" "github.com/gookit/goutil/netutil/httpreq" ) func main() { // Send a GET request resp, err := httpreq.Get("http://httpbin.org/get") fmt.Println(httpreq.ResponseToString(resp), err) // Send a POST request resp, err = httpreq.Post("http://httpbin.org/post", `{"name":"inhere"}`, httpreq.WithJSONType) fmt.Println(httpreq.ResponseToString(resp), err) } ``` -------------------------------- ### Convert Types Source: https://github.com/gookit/goutil/blob/master/README.md Shows examples of converting values to different types using goutil functions like String, Int, Int64, and Uint. ```go // convert type str = goutil.String(23) // "23" iVal = goutil.Int("-2") // 2 i64Val = goutil.Int64("-2") // -2 u64Val = goutil.Uint("2") // 2 ``` -------------------------------- ### CLI Argument Parsing Output Example Source: https://github.com/gookit/goutil/blob/master/internal/gendoc/template/readme-parts/cliutil.md Demonstrates the output of parsing a command-line string and building a command line string using cliutil. ```shell PRINT AT github.com/gookit/goutil/cliutil_test.TestParseLine(line_parser_test.go:30) []string [ #len=5 string("./app"), #len=5 string("top"), #len=3 string("sub"), #len=3 string("--msg"), #len=5 string("has multi words"), #len=15 ] Build line: ./myapp -a val0 -m "this is message" arg0 ``` -------------------------------- ### Basic cflag Usage Example Source: https://github.com/gookit/goutil/blob/master/cflag/README.md Demonstrates the basic usage of cflag for defining options, arguments, and parsing command-line input. Includes integer, string options, required and optional arguments, and custom validation. ```go package main import ( "fmt" "github.com/gookit/goutil/cflag" ) var opts struct { age int name string str1 string lOpt string }{} func main() { c := cflag.New(func(c *cflag.CFlags) { c.Desc = "this is a demo command" c.Version = "0.5.1" }) c.IntVar(&opts.age, "age", 0, "this is an int option;;a") c.StringVar(&opts.name, "name", "", "this is a string option and required;true") c.StringVar(&opts.str1, "str1", "def-val", "this is a string option with default value;;s") c.StringVar(&opts.lOpt, "long-opt", "", "this is a string option with shortcuts;;lo") c.AddArg("arg1", "this is arg1", true, nil) c.AddArg("arg2", "this is arg2", false, "default value") c.Func = func(c *cflag.CFlags) error { fmt.Println("command:", c.Name()) fmt.Println("option.age:", opts.age) fmt.Println("option.name:", opts.name) fmt.Println("option.str1:", opts.str1) fmt.Println("option.lOpt:", opts.lOpt) fmt.Println("arg1:", c.Arg("arg1").String()) fmt.Println("arg2:", c.Arg("arg2").String()) fmt.Println("remain args:", c.RemainArgs()) return nil } c.MustParse(nil) } ``` -------------------------------- ### System Utility Functions Source: https://github.com/gookit/goutil/blob/master/README.md Provides functions for getting working directory, binary directory, binary name, and opening files or URLs. ```Go func Workdir() string func BinDir() string func BinName() string func BinFile() string func Open(fileOrURL string) error func OpenBrowser(fileOrURL string) error func OpenFile(path string) error ``` -------------------------------- ### Basic Text Scanning Example Source: https://github.com/gookit/goutil/blob/master/strutil/textscan/README.md Demonstrates how to use TextScanner to parse key-value pairs and comments from input text. It configures matchers for comments and key-value entries, processes tokens, and collects data into a map. ```go package main import ( "fmt" "github.com/gookit/goutil/dump" "github.com/gookit/goutil/strutil/textscan" "github.com/gookit/goutil/x/assert" ) func main() { ts := textscan.TextScanner{} ts.AddMatchers( &textscan.CommentsMatcher{}, &textscan.KeyValueMatcher{}, ) ts.SetInput(` # comments 1 name = inhere // comments 2 age = 28 /* multi line comments 3 */ desc = ''' a multi line string ''' `) data := make(map[string]string) err := ts.Each(func(t textscan.Token) { fmt.Println("====> Token kind:", t.Kind()) fmt.Println(t.String()) if t.Kind() == textscan.TokValue { v := t.(*textscan.ValueToken) data[v.Key()] = v.Value() } }) dump.P(data, err) } ``` -------------------------------- ### Check Operating System Type Source: https://github.com/gookit/goutil/blob/master/README.md Use these functions to determine the current operating system. No setup is required. ```go envutil.IsWin() envutil.IsMac() envutil.IsLinux() ``` -------------------------------- ### Example Error Output with Stack Trace Source: https://github.com/gookit/goutil/blob/master/README.md Illustrates the typical output format of an error created with errorx.New, including the message and the detailed call stack. ```text the error message STACK: github.com/gookit/goutil/errorx_test.returnXErr() /Users/inhere/Workspace/godev/gookit/goutil/errorx/errorx_test.go:21 github.com/gookit/goutil/errorx_test.returnXErrL2() /Users/inhere/Workspace/godev/gookit/goutil/errorx/errorx_test.go:25 github.com/gookit/goutil/errorx_test.TestNew() /Users/inhere/Workspace/godev/gookit/goutil/errorx/errorx_test.go:29 testing.tRunner() /usr/local/Cellar/go/1.18/libexec/src/testing/testing.go:1439 runtime.goexit() /usr/local/Cellar/go/1.18/libexec/src/runtime/asm_amd64.s:1571 ``` -------------------------------- ### Format and Lint Go Code Source: https://github.com/gookit/goutil/blob/master/strutil/README.md Use `gofmt` to format Go source files and `golint` to check for style guide violations. Apply these commands recursively to the current directory. ```bash gofmt -w -l ./ golint ./+ ``` -------------------------------- ### Basic File/Directory Finder Usage Source: https://github.com/gookit/goutil/blob/master/x/finder/README.md Demonstrates how to initialize a finder, add scan paths, exclude directories and files by pattern, and apply built-in matchers. Use this to perform custom file searches. ```go package main import ( "github.com/gookit/goutil/dump" "github.com/gookit/goutil/x/finder" ) func main() { ff := finder.NewFinder() ff.AddScan("/tmp", "/usr/local", "/usr/local/share") ff.ExcludeDir("abc", "def").ExcludeFile("*.log", "*.tmp") // add built-in matchers ff.Exclude(finder.MatchSuffix("_test.go"), finder.MatchExt(".md")) ss := ff.FindPaths() dump.P(ss) } ``` -------------------------------- ### Helper Functions for CLI Source: https://github.com/gookit/goutil/blob/master/cliutil/README.md Utilize helper functions to get the current working directory, program executable directory, or execute shell commands. ```go cliutil.Workdir() // current workdir cliutil.BinDir() // the program exe file dir cliutil.QuickExec("echo $SHELL") ``` -------------------------------- ### String Prefix and Suffix Checks Source: https://github.com/gookit/goutil/blob/master/README.md Determines if a string starts with a specific prefix or ends with a specific suffix. Supports checking against multiple prefixes or suffixes. ```go 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 HasOneSuffix(s string, suffixes []string) bool ``` -------------------------------- ### CLI Helper Functions Source: https://github.com/gookit/goutil/blob/master/internal/gendoc/template/readme-parts/cliutil.md Provides utility functions for common CLI tasks such as getting the current working directory, the program's executable directory, and reading user input. ```go cliutil.Workdir() // current workdir cliutil.BinDir() // the program exe file dir cliutil.ReadInput("Your name?") cliutil.ReadPassword("Input password:") ans, _ := cliutil.ReadFirstByte("continue?[y/n] ") ``` -------------------------------- ### Test Go Project in Docker (Linux/macOS) Source: https://github.com/gookit/goutil/blob/master/README.md Set up a Docker environment to test your Go project. Mount the current directory into the container and set the GOPROXY. Then run tests inside the container. ```shell cd goutil docker run -ti -v $(pwd):/go/goutil -e GOPROXY=https://goproxy.cn,direct golang:1.23 # on Windows docker run -ti -v "${PWD}:/go/goutil" -e GOPROXY=https://goproxy.cn,direct golang:1.23 root@xx:/go/goutil# go test ./... ``` -------------------------------- ### Go Documentation Link Source: https://github.com/gookit/goutil/blob/master/byteutil/README.md Access the official Go documentation for the byteutil package. ```markdown - [Go docs](https://pkg.go.dev/github.com/gookit/goutil/byteutil) ``` -------------------------------- ### QuickOpenFile Source: https://github.com/gookit/goutil/blob/master/fsutil/README.md Opens a file with specified flags, using default permissions if creating. ```APIDOC ## QuickOpenFile ### Description Opens a file with the specified `fileFlag`. If the file is being created, default permissions (0666) will be used. This is a convenience function for common file opening scenarios. ### Signature ```go func QuickOpenFile(filepath string, fileFlag ...int) (*os.File, error) ``` ### Parameters * `filepath` (string) - The path to the file to open. * `fileFlag` ([]int) - Optional flags for opening the file (e.g., `os.O_RDWR | os.O_CREATE`). ### Returns * `*os.File` - A pointer to the opened file. * `error` - An error if the file cannot be opened. ``` -------------------------------- ### Run Specific Reflects Test by Regexp Source: https://github.com/gookit/goutil/blob/master/reflects/README.md Run tests in the reflects package that match a specific regular expression, for example, tests starting with 'TestSetByKeys'. ```shell go test -v -run ^TestSetByKeys ./reflects/... ``` -------------------------------- ### Go Test Assertions with x/assert Source: https://github.com/gookit/goutil/blob/master/testutil/README.md Demonstrates using the x/assert package for testing errors. Ensure you have imported the necessary packages. ```go package assert_test import ( t "testing" "github.com/gookit/goutil/errorx" "github.com/gookit/goutil/x/assert" ) func TestErr(t *testing.T) { err := errorx.Raw("this is a error") assert.NoErr(t, err, "user custom message") assert.ErrMsg(t, err, "this is a error") } ``` -------------------------------- ### Time Manipulation Functions Source: https://github.com/gookit/goutil/blob/master/timex/README.md These functions allow for adding days, hours, minutes, and seconds to a given time. They also provide utilities for getting the start and end of a day or hour, and for formatting time values. ```go 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 Date(t time.Time, template string) string func DateFormat(t time.Time, template string) string func DayEnd(t time.Time) time.Time func DayStart(t time.Time) time.Time func Format(t time.Time) string func FormatBy(t time.Time, layout 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 HourEnd(t time.Time) time.Time func HourStart(t time.Time) time.Time func HowLongAgo(sec int64) 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 NowHourEnd() time.Time func NowHourStart() time.Time func NowUnix() int64 func SetLocalByName(tzName string) error func ToDuration(s string) (time.Duration, error) func ToLayout(template string) string func TodayEnd() time.Time func TodayStart() time.Time ``` -------------------------------- ### Build Command Line String from Args Source: https://github.com/gookit/goutil/blob/master/cliutil/README.md Construct a command line string from a binary name and a slice of arguments. ```go s := cliutil.BuildLine("./myapp", []string{ "-a", "val0", "-m", "this is message", "arg0", }) fmt.Println("Build line:", s) ``` -------------------------------- ### Create File Info from Path and FileInfo Source: https://github.com/gookit/goutil/blob/master/README.md Use fsutil.NewFileInfo to construct a file info object using a file path and its FileInfo interface. ```Go // source at fsutil/define.go func NewFileInfo(fPath string, info fs.FileInfo) FileInfo ``` -------------------------------- ### SearchNameUp Source: https://github.com/gookit/goutil/blob/master/fsutil/README.md Searches for a file or directory by name upwards from a starting directory. ```APIDOC ## SearchNameUp ### Description Searches for a file or directory named `name` starting from `dirPath` and moving upwards towards the root directory. It returns the full path if found, or an empty string if not found. ### Signature ```go func SearchNameUp(dirPath, name string) string ``` ### Parameters * `dirPath` (string) - The directory to start the search from. * `name` (string) - The name of the file or directory to search for. ### Returns * `string` - The full path to the found file or directory, or an empty string if not found. ``` -------------------------------- ### Get Environment Variable Source: https://github.com/gookit/goutil/blob/master/internal/gendoc/template/readme-parts/envutil.md Functions to retrieve environment variable values with optional default values. ```APIDOC ## Get Environment Variable ### Description Retrieve environment variable values, with support for default values and type casting. ### Functions - `envutil.Getenv(key string, defaultValue string) string`: Retrieves the environment variable specified by `key`. If the variable is not set, `defaultValue` is returned. - `envutil.GetInt(key string, defaultValue int) int`: Retrieves the environment variable specified by `key` and attempts to parse it as an integer. If the variable is not set or cannot be parsed, `defaultValue` is returned. - `envutil.GetBool(key string, defaultValue bool) bool`: Retrieves the environment variable specified by `key` and attempts to parse it as a boolean. If the variable is not set or cannot be parsed, `defaultValue` is returned. ``` -------------------------------- ### Define Required, Optional, and Aliased Options Source: https://github.com/gookit/goutil/blob/master/cflag/README.md Demonstrates how to define options with different requirements and aliases using StringVar. ```go // Required option. c.StringVar(&opts.name, "name", "", "user name;true") // Optional option with short alias "-s". c.StringVar(&opts.str1, "str1", "def-val", "string value;;s") // Optional option with aliases "-lo" and "-l". c.StringVar(&opts.lOpt, "long-opt", "", "long option;;lo,l") ``` -------------------------------- ### Go Documentation Link Source: https://github.com/gookit/goutil/blob/master/arrutil/README.md Access detailed Go documentation for the arrutil package via the provided pkg.go.dev link. ```link https://pkg.go.dev/github.com/gookit/goutil/arrutil ``` -------------------------------- ### Helper Functions for Time Addition Source: https://github.com/gookit/goutil/blob/master/internal/gendoc/template/readme-parts/timex.md Utility functions to get the current time plus a specified duration. ```APIDOC ## Helper Functions for Time Addition ### Description Convenience functions to get the current time after adding a specific duration. ### Functions - `timex.NowAddDay(days int)`: Returns the current time plus the specified number of days. - `timex.NowAddHour(hours int)`: Returns the current time plus the specified number of hours. - `timex.NowAddMinutes(minutes int)`: Returns the current time plus the specified number of minutes. - `timex.NowAddSeconds(seconds int)`: Returns the current time plus the specified number of seconds. ### Examples ```go t := timex.NowAddDay(1) t := timex.NowAddHour(1) t := timex.NowAddMinutes(3) t := timex.NowAddSeconds(180) ``` ``` -------------------------------- ### Time Manipulation Functions Source: https://github.com/gookit/goutil/blob/master/timex/README.md Functions for adding and subtracting time units, getting start/end of day/hour, and formatting time. ```APIDOC ## Functions ### Add Day Adds a specified number of days to a given time. ```go func AddDay(t time.Time, day int) time.Time ``` ### Add Hour Adds a specified number of hours to a given time. ```go func AddHour(t time.Time, hour int) time.Time ``` ### Add Minutes Adds a specified number of minutes to a given time. ```go func AddMinutes(t time.Time, minutes int) time.Time ``` ### Add Seconds Adds a specified number of seconds to a given time. ```go func AddSeconds(t time.Time, seconds int) time.Time ``` ### Date Formats a time object into a string based on a template. ```go func Date(t time.Time, template string) string ``` ### DateFormat Formats a time object into a string using a specified layout template. ```go func DateFormat(t time.Time, template string) string ``` ### DayEnd Returns the time at the end of the day for a given time. ```go func DayEnd(t time.Time) time.Time ``` ### DayStart Returns the time at the start of the day for a given time. ```go func DayStart(t time.Time) time.Time ``` ### Format Formats a time object into a default string representation. ```go func Format(t time.Time) string ``` ### FormatBy Formats a time object into a string using a specified layout. ```go func FormatBy(t time.Time, layout string) string ``` ### FormatByTpl Formats a time object into a string using a specified template. ```go func FormatByTpl(t time.Time, template string) string ``` ### FormatUnix Formats a Unix timestamp (seconds) into a default string representation. ```go func FormatUnix(sec int64) string ``` ### FormatUnixBy Formats a Unix timestamp (seconds) into a string using a specified layout. ```go func FormatUnixBy(sec int64, layout string) string ``` ### FormatUnixByTpl Formats a Unix timestamp (seconds) into a string using a specified template. ```go func FormatUnixByTpl(sec int64, template string) string ``` ### HourEnd Returns the time at the end of the hour for a given time. ```go func HourEnd(t time.Time) time.Time ``` ### HourStart Returns the time at the start of the hour for a given time. ```go func HourStart(t time.Time) time.Time ``` ### HowLongAgo Converts a Unix timestamp (seconds) into a human-readable string indicating how long ago it was. ```go func HowLongAgo(sec int64) string ``` ### NowAddDay Returns the current time plus a specified number of days. ```go func NowAddDay(day int) time.Time ``` ### NowAddHour Returns the current time plus a specified number of hours. ```go func NowAddHour(hour int) time.Time ``` ### NowAddMinutes Returns the current time plus a specified number of minutes. ```go func NowAddMinutes(minutes int) time.Time ``` ### NowAddSeconds Returns the current time plus a specified number of seconds. ```go func NowAddSeconds(seconds int) time.Time ``` ### NowHourEnd Returns the time at the end of the current hour. ```go func NowHourEnd() time.Time ``` ### NowHourStart Returns the time at the start of the current hour. ```go func NowHourStart() time.Time ``` ### NowUnix Returns the current Unix timestamp in seconds. ```go func NowUnix() int64 ``` ### SetLocalByName Sets the local timezone by its name. Returns an error if the timezone is invalid. ```go func SetLocalByName(tzName string) error ``` ### ToDuration Converts a string representation of a duration into a `time.Duration` object. ```go func ToDuration(s string) (time.Duration, error) ``` ### ToLayout Converts a template string into a Go time layout string. ```go func ToLayout(template string) string ``` ### TodayEnd Returns the time at the end of the current day. ```go func TodayEnd() time.Time ``` ### TodayStart Returns the time at the start of the current day. ```go func TodayStart() time.Time ``` ``` -------------------------------- ### Display App Help Source: https://github.com/gookit/goutil/blob/master/cflag/README.md Run the multi-command application with -h to view its help message, including available commands. ```shell go run ./cflag/_example/app.go -h ``` -------------------------------- ### Get Internal IPv4 Address Source: https://github.com/gookit/goutil/blob/master/netutil/README.md Retrieve the internal IPv4 address of the machine. Ensure the netutil package is imported. ```go // Get internal IPv4 address netutil.InternalIPv4() ``` -------------------------------- ### Get Unique Elements from Slice Source: https://github.com/gookit/goutil/blob/master/arrutil/README.md Returns a new slice containing only the unique elements from the input slice. Duplicates are removed. ```go func Unique(arr any) interface{} ``` -------------------------------- ### Range and Boundary Functions Source: https://github.com/gookit/goutil/blob/master/mathutil/README.md Functions to check if a value falls within a specified range or to get values based on boundaries. ```APIDOC ## GreaterOr ### Description Returns the greater of two values or a default value if the first is not greater than the second. ### Signature `func GreaterOr[T comdef.XintOrFloat](val, min, defVal T) T` ## GteOr ### Description Returns the first value if it is greater than or equal to the minimum, otherwise returns a default value. ### Signature `func GteOr[T comdef.XintOrFloat](val, min, defVal T) T` ## InRange ### Description Checks if a value is within a specified inclusive range (min and max). ### Signature `func InRange[T comdef.IntOrFloat](val, min, max T) bool` ## InUintRange ### Description Checks if an unsigned integer value is within a specified inclusive range (min and max). ### Signature `func InUintRange[T comdef.Uint](val, min, max T) bool` ## LessOr ### Description Returns the lesser of two values or a default value if the first is not less than the second. ### Signature `func LessOr[T comdef.XintOrFloat](val, max, devVal T) T` ## LteOr ### Description Returns the first value if it is less than or equal to the maximum, otherwise returns a default value. ### Signature `func LteOr[T comdef.XintOrFloat](val, max, devVal T) T` ## OutRange ### Description Checks if a value is outside a specified inclusive range (min and max). ### Signature `func OutRange[T comdef.IntOrFloat](val, min, max T) bool` ## OrElse ### Description Returns the given value if it is not zero, otherwise returns a default value. ### Signature `func OrElse[T comdef.XintOrFloat](val, defVal T) T` ## ZeroOr ### Description Returns the given value if it is not zero, otherwise returns a default value. ### Signature `func ZeroOr[T comdef.XintOrFloat](val, defVal T) T` ``` -------------------------------- ### Create and Use an HTTP Echo Server Source: https://github.com/gookit/goutil/blob/master/testutil/README.md Quickly create an HTTP echo server for testing HTTP requests and responses. The server address is available via PrintHttpHost(). ```go var testSrvAddr string func TestMain(m *testing.M) { s := testutil.NewEchoServer() defer s.Close() testSrvAddr = s.PrintHttpHost() m.Run() } func TestNewEchoServer(t *testing.T) { // 可直接请求测试server r, err := http.Post(testSrvAddr, "text/plain", strings.NewReader("hello!")) assert.NoErr(t, err) // 将响应信息绑定到 testutil.EchoReply rr := testutil.ParseRespToReply(r) dump.P(rr) assert.Eq(t, "POST", rr.Method) assert.Eq(t, "text/plain", rr.ContentType()) assert.Eq(t, "hello!", rr.Body) } ``` -------------------------------- ### Get Random Element from Slice Source: https://github.com/gookit/goutil/blob/master/arrutil/README.md Retrieves a random element from a slice. Returns an interface{} which may need type assertion. ```go func RandomOne(arr any) interface{} ``` -------------------------------- ### Generate README Source: https://github.com/gookit/goutil/blob/master/internal/dev.md Run the make command to generate the README file. ```bash make readme ``` -------------------------------- ### Run Specific Go Tests Source: https://github.com/gookit/goutil/blob/master/x/goinfo/README.md Run Go tests filtered by a regular expression, targeting tests starting with 'TestSetByKeys'. ```shell go test -v -run ^TestSetByKeys ./goinfo/... ``` -------------------------------- ### Format Unix Timestamp with Timex Source: https://github.com/gookit/goutil/blob/master/README.md Provides examples of formatting a Unix timestamp into a human-readable date string using different templates. ```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 ``` -------------------------------- ### Parse and Build Command Lines Source: https://github.com/gookit/goutil/blob/master/README.md Parse a command line string into arguments or build a command line string from a binary name and arguments. Handles arguments with spaces correctly. ```go package main import ( "fmt" "github.com/gookit/goutil/cliutil" "github.com/gookit/goutil/dump" ) func main() { args := cliutil.ParseLine(`./app top sub --msg "has multi words"`) dump.P(args) s := cliutil.BuildLine("./myapp", []string{ "-a", "val0", "-m", "this is message", "arg0", }) fmt.Println("Build line:", s) } ``` -------------------------------- ### Execute Command Line Source: https://github.com/gookit/goutil/blob/master/sysutil/README.md Quickly execute a command line string. Ensure the command and its arguments are correctly formatted. ```go out, err := sysutil.ExecCmd("ls", []string{" -al"}) ``` -------------------------------- ### Write and Read String to Clipboard Source: https://github.com/gookit/goutil/blob/master/x/clipboard/README.md Demonstrates writing a string to the clipboard and then reading it back. Ensure the clipboard is accessible and writable. ```go src := "hello, this is clipboard" err = clipboard.WriteString(src) assert.NoErr(t, err) // str: "hello, this is clipboard" str, err = clipboard.ReadString() assert.NoErr(t, err) assert.NotEmpty(t, str) assert.Eq(t, src, str) ``` -------------------------------- ### Helper Functions Source: https://github.com/gookit/goutil/blob/master/internal/gendoc/template/readme-parts/cliutil.md Provides utility functions for common command-line operations such as getting the working directory, program directory, and reading user input. ```APIDOC ## CLI Util Helper Functions ### Description Helper functions for common CLI tasks. ### Functions - `cliutil.Workdir()`: Returns the current working directory. - `cliutil.BinDir()`: Returns the directory of the program executable. - `cliutil.ReadInput(prompt string)`: Reads a line of text input from the user after displaying a prompt. - `cliutil.ReadPassword(prompt string)`: Reads a password input from the user without echoing it to the console, after displaying a prompt. - `cliutil.ReadFirstByte(prompt string)`: Reads a single byte of input from the user after displaying a prompt. ``` -------------------------------- ### Add Positional Arguments Source: https://github.com/gookit/goutil/blob/master/cflag/README.md Shows how to bind positional arguments with descriptions, requirements, default values, and array support. ```go c.AddArg("arg1", "this is arg1") c.AddArg("arg2", "this is required arg2", true) c.AddArg("arg3", "this arg has default value", false, "default value") c.AddArg("extras", "array argument, must be the last one", false, nil, true) ``` -------------------------------- ### Build and Execute Command Source: https://github.com/gookit/goutil/blob/master/sysutil/README.md Build commands using a fluent API and execute them. The `OnBefore` hook can be used for assertions before execution. ```go c := cmdr.NewCmd("ls"). WithArg("-l"). WithArgs([]string{" -h"}). AddArg("-a"). AddArgf("%s", "./") c.OnBefore(func(c *cmdr.Cmd) { assert.Eq(t, "ls -l -h -a ./", c.Cmdline()) }) out := c.SafeOutput() fmt.Println(out) ``` -------------------------------- ### Get String Environment Variable Source: https://github.com/gookit/goutil/blob/master/envutil/README.md Retrieve a string environment variable, with an optional default value. If the variable is not set, the default value is returned. ```go func Getenv(name string, def ...string) string ``` -------------------------------- ### Get Integer Environment Variable Source: https://github.com/gookit/goutil/blob/master/envutil/README.md Retrieve an integer environment variable, with an optional default value. Parses the environment variable string into an integer. ```go func GetInt(name string, def ...int) int ``` -------------------------------- ### Timex Instance Creation Source: https://github.com/gookit/goutil/blob/master/internal/gendoc/template/readme-parts/timex.md Demonstrates various ways to create a Timex instance, including from the current time, a time.Time object, a Unix timestamp, and a formatted string. ```APIDOC ## Timex Instance Creation ### Description Create a timex instance using different methods. ### Methods - `timex.Now()`: Creates a Timex instance for the current time. - `timex.New(t time.Time)`: Creates a Timex instance from a `time.Time` object. - `timex.FromTime(t time.Time)`: Alias for `timex.New`. - `timex.FromUnix(timestamp int64)`: Creates a Timex instance from a Unix timestamp. - `timex.FromString(datetime string, layouts ...string)`: Creates a Timex instance from a datetime string, attempting to auto-match the layout or using provided layouts. - `timex.FromDate(datetime string, layout string)`: Creates a Timex instance from a datetime string using a specific layout. ### Examples ```go // Current time now := timex.Now() // From time.Time tx := timex.New(time.Now()) tx := timex.FromTime(time.Now()) // From Unix timestamp tx := timex.FromUnix(1647411580) // From datetime string (auto-match layout) tx, err := timex.FromString("2022-04-20 19:40:34") // From datetime string (custom layout) tx, err := timex.FromString("2022-04-20 19:40:34", "2006-01-02 15:04:05") // From date string with template layout tx, err := timex.FromDate("2022-04-20 19:40:34", "Y-m-d H:I:S") ``` ``` -------------------------------- ### Deep Get Value from Map Source: https://github.com/gookit/goutil/blob/master/maputil/README.md Retrieve values from a nested map using a dot-separated key path. Supports accessing elements in slices by index. ```go mp := map[string]any { "top1": "val1", "arr1": []string{"ab", "cd"} "map1": map[string]any{ "sub1": "val2", }, } fmt.Println(maputil.DeepGet(mp, "map1.sub1")) // Output: VAL3 // get value from slice. fmt.Println(maputil.DeepGet(mp, "arr1.1")) // Output: cd fmt.Println(maputil.DeepGet(mp, "arr1[1]")) // Output: cd ``` -------------------------------- ### Mkdir Source: https://github.com/gookit/goutil/blob/master/fsutil/README.md Creates a directory with specified permissions. ```APIDOC ## Mkdir ### Description Creates a single directory at the specified path with the given permissions. If the directory already exists, the function returns an error unless the `os.O_EXCL` flag is used in conjunction with `os.O_CREATE`. ### Signature ```go func Mkdir(dirPath string, perm os.FileMode) error ``` ### Parameters * `dirPath` (string) - The path of the directory to create. * `perm` (os.FileMode) - The file mode permissions for the directory. ### Returns * `error` - An error if the directory cannot be created. ``` -------------------------------- ### Create File Entry from Path and Entry Source: https://github.com/gookit/goutil/blob/master/README.md Use fsutil.NewEntry to create a file entry object from a file path and its directory entry information. ```Go // source at fsutil/define.go func NewEntry(fPath string, ent fs.DirEntry) Entry ``` -------------------------------- ### Get Struct Field Value using reflects Source: https://github.com/gookit/goutil/blob/master/reflects/README.md Demonstrates how to retrieve the value of a struct field by its name using the reflects.GetFieldValue function. Ensure the object and field name are valid. ```go import "github.com/gookit/goutil/reflects" // get struct field value reflects.GetFieldValue(obj, "Name") ``` -------------------------------- ### Run All Tests Source: https://github.com/gookit/goutil/blob/master/errorx/README.md Execute all tests within the Go project using 'go test'. ```bash go test -v ./errorx/... ``` -------------------------------- ### Get Environment Variable with Default Source: https://github.com/gookit/goutil/blob/master/internal/gendoc/template/readme-parts/envutil.md Retrieve environment variable values by key, with an option to provide a default value if the variable is not set. Supports string, integer, and boolean types. ```go envutil.Getenv("APP_ENV", "dev") envutil.GetInt("LOG_LEVEL", 1) envutil.GetBool("APP_DEBUG", true) ``` -------------------------------- ### Create New Error with errorx.New Source: https://github.com/gookit/goutil/blob/master/errorx/README.md Demonstrates creating a new error using errorx.New and printing its details, including the stack trace. ```go err := errorx.New("the error message") fmt.Println(err) // fmt.Printf("%v\n", err) // fmt.Printf("%#v\n", err) ``` -------------------------------- ### CLI Helper Functions Source: https://github.com/gookit/goutil/blob/master/README.md Utilize helper functions for common CLI operations like getting the current working directory, program directory, reading user input, and handling passwords. ```go cliutil.Workdir() // current workdir cliutil.BinDir() // the program exe file dir cliutil.ReadInput("Your name?") cliutil.ReadPassword("Input password:") ans, _ := cliutil.ReadFirstByte("continue?[y/n] ") ``` -------------------------------- ### Import Netutil Package Source: https://github.com/gookit/goutil/blob/master/netutil/README.md Import the netutil package to use its functionalities. ```go import "github.com/gookit/goutil/netutil" ``` -------------------------------- ### Running Go Tests Source: https://github.com/gookit/goutil/blob/master/dump/README.md Standard command to run verbose Go tests for a package. ```shell go test -v ./timex/... ``` -------------------------------- ### Timex Time Methods Source: https://github.com/gookit/goutil/blob/master/timex/README.md Methods available on the custom `Time` type for manipulating and formatting time. These include adding/subtracting time units, getting day/hour start/end, calculating differences, and formatting. ```go func (t *Time) AddDay(day int) *Time func (t *Time) AddHour(hours int) *Time func (t *Time) AddMinutes(minutes int) *Time func (t *Time) AddSeconds(seconds int) *Time func (t *Time) CustomHMS(hour, min, sec int) *Time func (t *Time) DateFormat(template string) string func (t *Time) Datetime() string func (t *Time) DayAfter(day int) *Time func (t *Time) DayAgo(day int) *Time func (t *Time) DayEnd() *Time func (t *Time) DayStart() *Time func (t Time) Diff(u time.Time) time.Duration func (t Time) DiffSec(u time.Time) int func (t *Time) Format(layout string) string func (t *Time) HourEnd() *Time func (t *Time) HourStart() *Time func (t Time) HowLongAgo(before time.Time) string func (t *Time) IsAfter(u time.Time) bool func (t *Time) IsAfterUnix(ux int64) bool func (t *Time) IsBefore(u time.Time) bool func (t *Time) IsBeforeUnix(ux int64) bool func (t *Time) SubDay(day int) *Time func (t *Time) SubHour(hours int) *Time func (t *Time) SubMinutes(minutes int) *Time func (t *Time) SubSeconds(seconds int) *Time func (t Time) SubUnix(u time.Time) int func (t Time) T() time.Time func (t Time) Timestamp() int64 func (t *Time) Tomorrow() *Time func (t *Time) TplFormat(template string) string func (t *Time) UnmarshalJSON(data []byte) error func (t *Time) UnmarshalText(data []byte) error func (t *Time) Yesterday() *Time ``` -------------------------------- ### Timex Helper Functions Source: https://github.com/gookit/goutil/blob/master/internal/gendoc/template/readme-parts/timex.md Utilize helper functions to get the current Unix timestamp or to calculate future time points by adding days, hours, minutes, or seconds to the current time. ```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 ``` -------------------------------- ### HTTP Mocking Utilities for Testing Source: https://github.com/gookit/goutil/blob/master/README.md Functions for creating mock HTTP requests, servers, and responses for testing HTTP clients. ```Go func NewHTTPRequest(method, path string, data *MD) *http.Request func MockRequest(h http.Handler, method, path string, data *MD) *httptest.ResponseRecorder func MockHttpServer() *EchoServer func TestMain(m *testing.M) func NewEchoServer() *EchoServer func BuildEchoReply(r *http.Request) *EchoReply func ParseRespToReply(w *http.Response) *EchoReply func ParseBodyToReply(bd io.ReadCloser) *EchoReply ``` -------------------------------- ### Run Go Tests Source: https://github.com/gookit/goutil/blob/master/x/goinfo/README.md Execute all tests within the goinfo package. ```shell go test -v ./goinfo/... ``` -------------------------------- ### Get Boolean Environment Variable Source: https://github.com/gookit/goutil/blob/master/envutil/README.md Retrieve a boolean environment variable, with an optional default value. Handles common boolean string representations like 'true', 'false', '1', '0'. ```go func GetBool(name string, def ...bool) bool ```