https://github.com/x-funs/go-fun
Go with Fun (Functions) is a small and useful Golang util function library. It Includes such as Empty、Blank、Strtotime、Similarity、HttpGet etc.
https://github.com/x-funs/go-fun
go golang utility-library utils
Last synced: 28 days ago
JSON representation
Go with Fun (Functions) is a small and useful Golang util function library. It Includes such as Empty、Blank、Strtotime、Similarity、HttpGet etc.
- Host: GitHub
- URL: https://github.com/x-funs/go-fun
- Owner: x-funs
- License: apache-2.0
- Created: 2022-05-06T07:14:02.000Z (almost 4 years ago)
- Default Branch: main
- Last Pushed: 2024-12-09T09:51:23.000Z (about 1 year ago)
- Last Synced: 2024-12-09T10:38:17.453Z (about 1 year ago)
- Topics: go, golang, utility-library, utils
- Language: Go
- Homepage:
- Size: 251 KB
- Stars: 229
- Watchers: 1
- Forks: 4
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
```
____
____ _____ / __/_ ______
/ __ `/ __ \______/ /_/ / / / __ \
/ /_/ / /_/ /_____/ __/ /_/ / / / /
\__, /\____/ /_/ \__,_/_/ /_/
/____/
```
Go with Fun (Functions) is a small and useful Golang util function library. It Includes such as Empty、Blank、Strtotime、Similarity、HttpGet etc.
English | [简体中文](./README_zh.md)
## Installation
```shell
go get -u github.com/x-funs/go-fun
```
## Example
```go
package main
import (
"fmt"
"github.com/x-funs/go-fun"
)
func main() {
// Whether any type value is empty
fmt.Println(fun.Empty(""))
// Whether string value is blank
fmt.Println(fun.Blank(" "))
// Return MD5 string from a string
fmt.Println(fun.Md5("go-fun"))
// Auto parse datetime layout to int64 timestamp
fmt.Println(fun.StrToTime("2015-04-06 16:03:03"))
fmt.Println(fun.StrToTime("2015/04/06 16:03:03"))
fmt.Println(fun.StrToTime("2022-01-24T14:19:00Z"))
fmt.Println(fun.StrToTime("2022-01-24T14:19:01+07:00"))
// Slice deduplication filter
fmt.Println(fun.SliceUnique([]string{"a", "b", "c", "a", "b", "c"}))
// Send a Simple HTTP GET request, Return HTML string
html, _ := fun.HttpGet("https://www.github.com")
fmt.Println(fun.String(html))
}
```
## Documentation
### DateTime
#### Function List
- **`Timestamp(millis ...any) int64`** Return the current unix timestamp.
- **`Date(layouts ...any) string`** Return the formatted datetime string.
- **`StrToTime(args ...any) int64`** Auto parse datetime layout to int64 timestamp, just like PHP strtotime().
```go
package main
import (
"fmt"
"github.com/x-funs/go-fun"
)
func main() {
// second timestamp
fmt.Println(fun.Timestamp())
// 1673225645
// millisecond timestamp
fmt.Println(fun.Timestamp(true))
// 1673225645077
// no arguments, format datetime now (default by '2006-01-02 15:04:05')
fmt.Println(fun.Date())
// 2006-01-02 15:04:05
// format datetime by timestamp (default by '2006-01-02 15:04:05')
fmt.Println(fun.Date(1650732457))
// 2022-04-24 00:47:37
// use layout format datetime by timestamp
fmt.Println(fun.Date(time.RFC3339, 1650732457))
// 2022-04-24T00:47:37+08:00
// no arguments, same as Timestamp()
fmt.Println(fun.StrToTime())
// 1673226381
// one day before now timestamp
fmt.Println(fun.StrToTime("-1 day"))
// 1673139981 (yesterday)
fmt.Println(fun.StrToTime("+1 day", 1673225645))
// 1673312045 (one day after a certain timestamp)
}
```
### Helpers
#### Function List
- **`If(condition bool, trueVal, falseVal T) T`** Verify condition is true, return trueVal or falseVal
- **`Empty(value any) bool`** Verify whether value it is empty, support string, integer, array, slice, map 验证
- **`EmptyAll(values ...any) bool`** Verify whether values all are empty
- **`EmptyAny(values ...any) bool`** Verify whether values any is empty
- **`MemoryBytes() map[string]int64`** Return the current main memory metrics.
- **`Memory(format string) map[string]int64`** Specified format return the current main memory metric.
- **`Bytes(s string) []byte`** Efficient string to byte array, reference from `Gin`
- **`String(b []byte) string`** Efficient byte array to string, reference from `Gin`
- **`Command(bin string, argv []string, baseDir string) ([]byte, error)`** Execute system commands
```go
package main
import (
"fmt"
"github.com/x-funs/go-fun"
)
func main() {
fmt.Println(fun.Empty(nil))
// true
fmt.Println(fun.Empty(0))
// true
fmt.Println(fun.Empty(""))
// true
fmt.Println(fun.Empty(false))
// true
fmt.Println(fun.Empty(" "))
// false
fmt.Println(fun.Empty(1))
// false
fmt.Println(fun.Empty(true))
// false
}
```
### Hash
#### Function List
- **`Md5(str string) string`** Return the Md5 string
- **`Md5Bit16(str string) string`** Return the 16-bit Md5 string
- **`Sha1(str string) string`** Return the Sha1 string
- **`Sha256(str string) string`** Return the Sha256 string
- **`Sha384(str string) string`** Return the Sha384 string
- **`Sha512(str string) string`** Return the Sha512 string
- **`Base64Encode(str string) string`** Return the Base64 string
- **`Base64Decode(str string) string`** Return the Base64 decode string
- **`Base64UrlEncode(str string) string`** Return the Url Safe Base64 string
- **`Base64UrlDecode(str string) string`** Return the Url Safe Base64 decode string
### Judgment
#### Function List
- **`IsNumber(str string) bool`** Determine whether all strings are numbers
- **`IsUtf8(p []byte) bool`** Determine whether it is a UTF-8 code
- **`IsASCIILetter(str string) bool`** Determine whether all strings are ASCII letters
- **`IsLetter(str string) bool`** Determine whether all strings are letters
- **`IsASCII(s string) bool`** Determine whether the string is all ASCII
- **`IsEmail(str string) bool`** Verify Email
- **`IsExist(path string) bool`** Does the file or directory exist
- **`IsDir(path string) bool`** Is it a directory
### Map
#### Function List
- **`MapKeys[K comparable, V any](m map[K]V) []K`** Return slices of all keys of map
- **`MapValues[K comparable, V any](m map[K]V) []V`** Return a slice of all values of map
- **`MapMerge[K comparable, V any](maps ...map[K]V) map[K]V`** Merge multiple maps, if there are the same keys, the latter will overwrite the former
### Math
#### Function List
- **`Max(a, b int) int`** Take int maximum
- **`Min(a, b int) int`** Take int minimum
- **`MaxInt64(a, b int64) int64`** Take int64 maximum
- **`MinInt64(a, b int64) int64`** Take int64 minimum
- **`MaxN[T GenNumber](args ...T) T`** Take the maximum value of n numbers
- **`MinN[T GenNumber](args ...T) T`** Take the minimum value of n numbers
### Random
#### Function List
- **`Random() int`** Return a random number `[0, MaxInt)`
- **`RandomInt(min, max int) int`** Return a random number `[min, max)`
- **`RandomInt64(min, max int64) int64`** Return a random number `[min, max)`
- **`RandomString(length int) string`** Return a random string of the specified length, including letters and numbers.
- **`RandomLetter(length int) string`** Return a random string of the specified length, containing only letters.
- **`RandomNumber(length int) string`** Return a random string of the specified length, containing only numbers.
- **`RandomPool(pool string, length int) string`** Return a random string of the specified length from the supplied string pool
### Regex
#### Function List
- **`Matches(str, pattern string) bool`** Determines whether the string matches the specified regular expression.
### Similarity
#### Function List
- **`Similarity(a, b string) float64`** Calculates the similarity of two original strings
- **`SimilarityText(a, b string) float64`** Calculate the similarity of two strings after removing special symbols
- **`LongestCommonSubString(x, y string) int`** Calculates the maximum common substring length of two strings
### Slice
#### Function List
- **`SliceSplit[T comparable](slice []T, size int) [][]T`** Divide numeric and string slices according to the specified length
- **`SliceUnion[T comparable](slices ...[]T) []T`** Sequential merge and deweight
- **`SliceColumn[T, V any](slice []T, key any) []V`** Return a column of all rows
- **`IntsToStrings(slice []int) []string`** Int slice to string slice
- **`StringsToInts(slice []string) []int`** String slice to int slice
- **`SliceContains[T comparable](slice []T, v T) bool`** Determine whether integer and string are in slice
- **`SliceUnique[T comparable](slice []T) []T`** Devaluation of numeric and string slices (changes the order of elements)
- **`SliceIndex[T comparable](slice []T, v T) int`** Find numeric and string slices according to the specified value
- **`SliceLastIndex[T comparable](slice []T, v T) int`** The value and string slices are searched according to the specified value, and the last matching index is returned.
- **`SliceRemove[T comparable](slice []T, v T) []T`** Removes the specified value from numeric and string slices
- **`SliceRemoveBlank(slice []string) []string`** Remove null values from string slices
- **`SliceTrim(slice []string) []string`** Trim string slices and automatically ignore null values
- **`SliceConcat[T any](slice []T, values ...[]T) []T`** Merge multiple slices, non-degravimetric, non-original slices
- **`SliceEqual[T comparable](slice1, slice2 []T) bool`** Are slices equal: the same length and the order and value of all elements are equal
- **`SliceEvery[T any](slice []T, predicate func(index int, item T) bool) bool`** All elements in the slice satisfy the function, return true
- **`SliceNone[T any](slice []T, predicate func(index int, item T) bool) bool`** Return true if all elements in the slice do not satisfy the function.
- **`SliceSome[T any](slice []T, predicate func(index int, item T) bool) bool`** If one element in the slice satisfies the function, it Return true.
- **`SliceFilter[T any](slice []T, predicate func(index int, item T) bool) []T`** Filter out all elements in the slice that satisfy the function
- **`SliceForEach[T any](slice []T, iteratee func(index int, item T))`** All elements in the slice execute functions
- **`SliceMap[T any, U any](slice []T, iteratee func(index int, item T) U) []U`** All elements in the slice execute functions and have return values.
- **`SliceReduce[T any](slice []T, iteratee func(index int, result, item T) T, initial T) T`** Process all elements in slices to get results
- **`SliceReplace[T comparable](slice []T, old T, new T, n int) []T`** Return a copy of the slice, with the first n elements replaced with the new
- **`SliceReplaceAll[T comparable](slice []T, old T, new T) []T`** Return a copy of the slice, and all matching elements are replaced with new ones.
- **`SliceUnionBy[T any, V comparable](predicate func(item T) V, slices ...[]T) []T`** Order merge and de-heavy, support custom functions
- **`SliceIntersection[T comparable](slices ...[]T) []T`** Slices intersect and deweight (order cannot be guaranteed)
- **`SliceSortBy(slice any, field string, sortType ...string) error`** Sort by field (field case should be consistent with field)
```go
package main
import (
"fmt"
"github.com/x-funs/go-fun"
)
func main() {
fmt.Println(fun.SliceSplit([]string{"a", "b", "c", "d", "e", "f", "g"}, 3))
// [[a b c] [d e f] [g]]
fmt.Println(fun.SliceUnion([]string{"123", "124"}, []string{"124", "125"}, []string{"123", "125"}))
// [123 124 125]
fmt.Println(
fun.SliceColumn[map[string]string, string]([]map[string]string{
{"name": "admin", "code": "YF4133"},
{"name": "user", "code": "MM8541"},
{"name": "test", "code": "KH0002"},
{"name": "demo", "code": "SJ9642"},
}, "code"),
)
// [YF4133 MM8541 KH0002 SJ9642]
}
```
### String
#### Function List
- **`StrBefore(s, char string) string`** Intercept the substring before the position of the character when it first appears.
- **`StrBeforeLast(s, char string) string`** Intercept the substring before the last appearance of the character
- **`StrAfter(s, char string) string`** Interception of substrings after the position of the character when it first appears
- **`StrAfterLast(s, char string) string`** Interception of substrings after the last appearance of the character
- **`Blank(str string) bool`** Determine whether the string after Trim is blank.
- **`BlankAll(strs ...string) bool`** Determine whether the string set after Trim is all blank.
- **`BlankAny(strs ...string) bool`** Determine whether any string set after Trim contains a blank.
- **`HasPrefixCase(str, prefix string) bool`** Determines whether the string starts with the specified prefix, ignoring case
- **`HasSuffixCase(str, prefix string) bool`** Determine whether the string ends with the specified suffix, ignoring the case.
- **`SplitTrim(str, sep string) []string`** The split string is a string slice, the split value is Trim, and the null value is automatically ignored.
- **`SplitTrimToInts(str, sep string) []int`** The split string is an int slice, the split value is Trim, and the null value is automatically ignored.
- **`Contains(str, substr string) bool`** Determines whether the string contains the specified substring
- **`ContainsCase(str, substr string) bool`** Determine whether the string contains the specified substring, case-insensitive
- **`ContainsAny(str string, substr ...string) bool`** Determine whether the string contains any of the specified substrings.
- **`SnakeToCamel(str string, bigCamel bool) string`** Serpentine hump
- **`CamelToSnake(str string) string`** Hump turns to snake
- **`PadLeft(str string, padStr string, padLen int) string`** Fill the string on the left to the specified length
- **`PadRight(str string, padStr string, padLen int) string`** The right side fills the string to the specified length.
- **`PadBoth(str string, padStr string, padLen int) string`** Both sides fill the string to the specified length
- **`Wrap(str string, wrapStr string) string`** Enclosed the original string with a string
- **`Unwrap(str string, wrapStr string) string`** Remove string bounding, non-recursive
- **`Reverse(str string) string`** Reverse string
- **`Remove(str, remove string) string`** Removes the specified string in the string
- **`RemovePrefix(str, prefix string) string`** Removes the string specified in the string on the left
- **`RemoveSuffix(str string, suffix string) string`** The right side removes the specified string in the string.
- **`RemoveAny(str string, removes ...string) string`** Removes the string set specified in the string
- **`RemoveSign(str string) string`** Write all the data of the string into one line in turn, and remove meaningless strings (punctuation marks, symbols)
- **`RemoveLines(str string) string`** Remove line breaks, which include \n \r\n.
- **`SubString(str string, pos, length int) string`** String interception
- **`NormaliseSpace(str string) string`** Normalized the white space in this string, multiple spaces are merged into one space, and all white space characters such as line breaks and tabs are converted to a simple space.
- **`NormaliseLine(str string) string`** Standardize line breaks in this string, and merge multiple line breaks into one line break.
- **`Template(tpl string, data any) (string, error)`** Template rendering
```go
package main
import (
"fmt"
"github.com/x-funs/go-fun"
)
func main() {
fmt.Println(fun.StrBefore("http://admin:123123@127.0.0.1:27017", ":"))
// http
fmt.Println(fun.StrAfter("https://github.com", "://"))
// github.com
fmt.Println(fun.StrBeforeLast("video.mp4.bak", "."))
// video.mp4
fmt.Println(fun.StrAfterLast("video.mp4.bak", "."))
// bak
}
```
### Struct
#### Function List
- **`StructCopy(src, dst any)`** Copy struct object
### To
#### Function List
- **`Ip2Long(ipStr string) uint32`** String IP to integer
- **`Long2Ip(long uint32) string`** Integer to string IP
- **`ToString(value any) string`** Converts any type to a string
- **`ToInt(value any) int`** Number or string to int type
- **`ToLong(value any) int64`** ToInt64 alias, number or string to int64
- **`ToBool(str string) bool`** string to bool type
- **`ToUint(value any) uint`** Number or string to uint
- **`ToUint8(value any) uint8`** Number or string to uint8
- **`ToInt64(value any) int64`** Number or string to int64
- **`ToFloat32(value any) float32`** Number or string to float32
- **`ToFloat64(value any) float64`** Number or string to float64
- **`ToUtf8(origin []byte, encode string) ([]byte, error)`** Specify character set conversion utf-8
- **`Utf8To(utf8 []byte, encode string) ([]byte, error)`** utf-8 to specify character set
- **`ToJson(object any) string`** Converts an object to a Json string
- **`ToJsonIndent(object any) string`** Converts an object to a Indent Json string
- **`ToDuration(value any) time.Duration`** Converts number or string to time.Duration, default is Nanosecond, string support "ns,ms,us,s,m,h"
- **`ToDurationMs(value any) time.Duration`** Converts number or string to time.Duration, default is Millisecond, string support "ns,ms,us,s,m,h"
### File
#### Function List
- **`Mkdir(dir string, perm os.FileMode) error`** Create a directory, ignoring if the directory already exists
- **`FileExists(path string) bool`** Check whether the directory or file exists, return bool
- **`WriteFile(name string, data []byte, flag int, perm os.FileMode, sync bool) error`** write file shortcut
- **`WriteFileAppend(name string, data []byte, perm os.FileMode, sync bool) error`** write file shortcut with append mode
### Http
> HttpXXResp the suffix, the return value is *Response
> HttpXXDo the suffix, Need to pass parameters *Request
#### Function List
- **`HttpGet(urlStr string, args ...any) ([]byte, error)`** The HttpGet parameter is the request address (HttpReq, timeout)
- **`HttpPost(urlStr string, args ...any) ([]byte, error)`** The HttpPost parameter is the request address (body io.Reader, HttpReq, timeout)
- **`HttpPostForm(urlStr string, args ...any) ([]byte, error)`** The HttpPostForm parameter is the request address (FormData map[string]string, HttpReq, timeout)
- **`HttpPostJson(urlStr string, args ...any) ([]byte, error)`** The HttpPostJson parameter is the request address (JsonData string, HttpReq, timeout)
- **`UrlParse(rawURL string) (*url.URL, error)`** Parses the string URL to the URL object. There will be no mistakes without scheme.
- **`UserAgentRandom() string`** generates a random DESKTOP browser user-agent on every requests .
- **`UserAgentRandomMobile() string`** generates a random MOBILE browser user-agent on every requests.