A package of Go helper functions for business development.
Make sure that Go is installed on your computer. Type the following command in your terminal:
go get github.com/imajinyun/gohelper
Add following line in your *.go
file:
import "github.com/imajinyun/gohelper"
- Simplify the judgment of if else to a single line of code:
flag, expr := 0, "some version"
if expr == "v1" {
flag = 1
} else if expr == "v2" {
flag = 2
}
flag = gohelper.If(expr == "v1", 1, gohelper.If(expr == "v2", 2, 0))
- Convert data to string:
// Output: [hello world]
gohelper.ToString([]string{"hello", "world"})
- Convert data to JSON string:
// Output: {"id":1,"name":"jack"}
gohelper.ToJson(map[string]any{"id": 1, "name": "jack"})
- Get the current date and time object:
// Output: 2024-09-12 12:02:15
tim, err := gohelper.NowDateTime("Asia/Shanghai", "2006-01-02 15:04:05")
if err != nil {
panic(err)
}
tim.ToString()
- Get the year, month, day, hour, minute, and second of the date and time object:
// Output: 2024
tim.Year()
// Output: 256
tim.YearDay()
// Output: September
tim.Month()
// Output: 12
tim.Day()
// Output: 12
tim.Hour()
// Output: 2
tim.Minute()
// Output: 15
tim.Second()
- Get the begin and end of the day of the date and time object:
// Output: 2024-09-12 00:00:00
tim.BeginOfDay().Format(time.DateTime)
// Output: 2024-09-12 23:59:59
tim.BeginOfDay().Format(time.DateTime)
// Output: 2024-09-01 00:00:00
tim.BeginOfMonth().Format(time.DateTime)
// Output: 2024-09-01 23:59:59
tim.EndOfMonth().Format(time.DateTime)
// Output: 2024-01-01 00:00:00
tim.BeginOfYear().Format(time.DateTime)
// Output: 2024-12-31 23:59:59
tim.EndOfYear().Format(time.DateTime)
- If the specified key cannot obtain a value, return the given default value:
// Output: default value
mps := make(map[string]any)
mps.GetOrDefault("mykey", "default value")
- Generate string with options (include uppercase, numbers, and symbols):
// Output: knvmfcmpfqiqcbrh
gohelper.RandStr(16)
// Output: nD>fKDvaF\R+1h.G
gohelper.RandStrWithOption(16, Option{
IncludeNumber: true,
IncludeUppercase: true,
IncludeSymbol: true,
})