____
____ _____ / __/_ ______
/ __ `/ __ \______/ /_/ / / / __ \
/ /_/ / /_/ /_____/ __/ /_/ / / / /
\__, /\____/ /_/ \__,_/_/ /_/
/____/
Go with Fun (Functions) is a small and useful Golang util function library. It Includes such as Empty、Blank、Strtotime、Similarity、HttpGet etc.
English | 简体中文
go get -u github.com/x-funs/go-funpackage 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))
}-
Timestamp(millis ...any) int64Return the current unix timestamp. -
Date(layouts ...any) stringReturn the formatted datetime string. -
StrToTime(args ...any) int64Auto parse datetime layout to int64 timestamp, just like PHP strtotime().
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)
}-
If(condition bool, trueVal, falseVal T) TVerify condition is true, return trueVal or falseVal -
Empty(value any) boolVerify whether value it is empty, support string, integer, array, slice, map 验证 -
EmptyAll(values ...any) boolVerify whether values all are empty -
EmptyAny(values ...any) boolVerify whether values any is empty -
MemoryBytes() map[string]int64Return the current main memory metrics. -
Memory(format string) map[string]int64Specified format return the current main memory metric. -
Bytes(s string) []byteEfficient string to byte array, reference fromGin -
String(b []byte) stringEfficient byte array to string, reference fromGin -
Command(bin string, argv []string, baseDir string) ([]byte, error)Execute system commands
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
}-
Md5(str string) stringReturn the Md5 string -
Md5Bit16(str string) stringReturn the 16-bit Md5 string -
Sha1(str string) stringReturn the Sha1 string -
Sha256(str string) stringReturn the Sha256 string -
Sha384(str string) stringReturn the Sha384 string -
Sha512(str string) stringReturn the Sha512 string -
Base64Encode(str string) stringReturn the Base64 string -
Base64Decode(str string) stringReturn the Base64 decode string -
Base64UrlEncode(str string) stringReturn the Url Safe Base64 string -
Base64UrlDecode(str string) stringReturn the Url Safe Base64 decode string
-
IsNumber(str string) boolDetermine whether all strings are numbers -
IsUtf8(p []byte) boolDetermine whether it is a UTF-8 code -
IsASCIILetter(str string) boolDetermine whether all strings are ASCII letters -
IsLetter(str string) boolDetermine whether all strings are letters -
IsASCII(s string) boolDetermine whether the string is all ASCII -
IsEmail(str string) boolVerify Email -
IsExist(path string) boolDoes the file or directory exist -
IsDir(path string) boolIs it a directory
-
MapKeys[K comparable, V any](m map[K]V) []KReturn slices of all keys of map -
MapValues[K comparable, V any](m map[K]V) []VReturn a slice of all values of map -
MapMerge[K comparable, V any](maps ...map[K]V) map[K]VMerge multiple maps, if there are the same keys, the latter will overwrite the former
-
Max(a, b int) intTake int maximum -
Min(a, b int) intTake int minimum -
MaxInt64(a, b int64) int64Take int64 maximum -
MinInt64(a, b int64) int64Take int64 minimum -
MaxN[T GenNumber](args ...T) TTake the maximum value of n numbers -
MinN[T GenNumber](args ...T) TTake the minimum value of n numbers
-
Random() intReturn a random number[0, MaxInt) -
RandomInt(min, max int) intReturn a random number[min, max) -
RandomInt64(min, max int64) int64Return a random number[min, max) -
RandomString(length int) stringReturn a random string of the specified length, including letters and numbers. -
RandomLetter(length int) stringReturn a random string of the specified length, containing only letters. -
RandomNumber(length int) stringReturn a random string of the specified length, containing only numbers. -
RandomPool(pool string, length int) stringReturn a random string of the specified length from the supplied string pool
Matches(str, pattern string) boolDetermines whether the string matches the specified regular expression.
-
Similarity(a, b string) float64Calculates the similarity of two original strings -
SimilarityText(a, b string) float64Calculate the similarity of two strings after removing special symbols -
LongestCommonSubString(x, y string) intCalculates the maximum common substring length of two strings
-
SliceSplit[T comparable](slice []T, size int) [][]TDivide numeric and string slices according to the specified length -
SliceUnion[T comparable](slices ...[]T) []TSequential merge and deweight -
SliceColumn[T, V any](slice []T, key any) []VReturn a column of all rows -
IntsToStrings(slice []int) []stringInt slice to string slice -
StringsToInts(slice []string) []intString slice to int slice -
SliceContains[T comparable](slice []T, v T) boolDetermine whether integer and string are in slice -
SliceUnique[T comparable](slice []T) []TDevaluation of numeric and string slices (changes the order of elements) -
SliceIndex[T comparable](slice []T, v T) intFind numeric and string slices according to the specified value -
SliceLastIndex[T comparable](slice []T, v T) intThe 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) []TRemoves the specified value from numeric and string slices -
SliceRemoveBlank(slice []string) []stringRemove null values from string slices -
SliceTrim(slice []string) []stringTrim string slices and automatically ignore null values -
SliceConcat[T any](slice []T, values ...[]T) []TMerge multiple slices, non-degravimetric, non-original slices -
SliceEqual[T comparable](slice1, slice2 []T) boolAre 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) boolAll elements in the slice satisfy the function, return true -
SliceNone[T any](slice []T, predicate func(index int, item T) bool) boolReturn true if all elements in the slice do not satisfy the function. -
SliceSome[T any](slice []T, predicate func(index int, item T) bool) boolIf one element in the slice satisfies the function, it Return true. -
SliceFilter[T any](slice []T, predicate func(index int, item T) bool) []TFilter 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) []UAll 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) TProcess all elements in slices to get results -
SliceReplace[T comparable](slice []T, old T, new T, n int) []TReturn a copy of the slice, with the first n elements replaced with the new -
SliceReplaceAll[T comparable](slice []T, old T, new T) []TReturn 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) []TOrder merge and de-heavy, support custom functions -
SliceIntersection[T comparable](slices ...[]T) []TSlices intersect and deweight (order cannot be guaranteed) -
SliceSortBy(slice any, field string, sortType ...string) errorSort by field (field case should be consistent with field)
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]
}-
StrBefore(s, char string) stringIntercept the substring before the position of the character when it first appears. -
StrBeforeLast(s, char string) stringIntercept the substring before the last appearance of the character -
StrAfter(s, char string) stringInterception of substrings after the position of the character when it first appears -
StrAfterLast(s, char string) stringInterception of substrings after the last appearance of the character -
Blank(str string) boolDetermine whether the string after Trim is blank. -
BlankAll(strs ...string) boolDetermine whether the string set after Trim is all blank. -
BlankAny(strs ...string) boolDetermine whether any string set after Trim contains a blank. -
HasPrefixCase(str, prefix string) boolDetermines whether the string starts with the specified prefix, ignoring case -
HasSuffixCase(str, prefix string) boolDetermine whether the string ends with the specified suffix, ignoring the case. -
SplitTrim(str, sep string) []stringThe split string is a string slice, the split value is Trim, and the null value is automatically ignored. -
SplitTrimToInts(str, sep string) []intThe split string is an int slice, the split value is Trim, and the null value is automatically ignored. -
Contains(str, substr string) boolDetermines whether the string contains the specified substring -
ContainsCase(str, substr string) boolDetermine whether the string contains the specified substring, case-insensitive -
ContainsAny(str string, substr ...string) boolDetermine whether the string contains any of the specified substrings. -
SnakeToCamel(str string, bigCamel bool) stringSerpentine hump -
CamelToSnake(str string) stringHump turns to snake -
PadLeft(str string, padStr string, padLen int) stringFill the string on the left to the specified length -
PadRight(str string, padStr string, padLen int) stringThe right side fills the string to the specified length. -
PadBoth(str string, padStr string, padLen int) stringBoth sides fill the string to the specified length -
Wrap(str string, wrapStr string) stringEnclosed the original string with a string -
Unwrap(str string, wrapStr string) stringRemove string bounding, non-recursive -
Reverse(str string) stringReverse string -
Remove(str, remove string) stringRemoves the specified string in the string -
RemovePrefix(str, prefix string) stringRemoves the string specified in the string on the left -
RemoveSuffix(str string, suffix string) stringThe right side removes the specified string in the string. -
RemoveAny(str string, removes ...string) stringRemoves the string set specified in the string -
RemoveSign(str string) stringWrite all the data of the string into one line in turn, and remove meaningless strings (punctuation marks, symbols) -
RemoveLines(str string) stringRemove line breaks, which include \n \r\n. -
SubString(str string, pos, length int) stringString interception -
NormaliseSpace(str string) stringNormalized 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) stringStandardize line breaks in this string, and merge multiple line breaks into one line break. -
Template(tpl string, data any) (string, error)Template rendering
package main
import (
"fmt"
"github.com/x-funs/go-fun"
)
func main() {
fmt.Println(fun.StrBefore("http://admin:[email protected]: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
}StructCopy(src, dst any)Copy struct object
-
Ip2Long(ipStr string) uint32String IP to integer -
Long2Ip(long uint32) stringInteger to string IP -
ToString(value any) stringConverts any type to a string -
ToInt(value any) intNumber or string to int type -
ToLong(value any) int64ToInt64 alias, number or string to int64 -
ToBool(str string) boolstring to bool type -
ToUint(value any) uintNumber or string to uint -
ToUint8(value any) uint8Number or string to uint8 -
ToInt64(value any) int64Number or string to int64 -
ToFloat32(value any) float32Number or string to float32 -
ToFloat64(value any) float64Number 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) stringConverts an object to a Json string -
ToJsonIndent(object any) stringConverts an object to a Indent Json string -
ToDuration(value any) time.DurationConverts number or string to time.Duration, default is Nanosecond, string support "ns,ms,us,s,m,h" -
ToDurationMs(value any) time.DurationConverts number or string to time.Duration, default is Millisecond, string support "ns,ms,us,s,m,h"
-
Mkdir(dir string, perm os.FileMode) errorCreate a directory, ignoring if the directory already exists -
FileExists(path string) boolCheck whether the directory or file exists, return bool -
WriteFile(name string, data []byte, flag int, perm os.FileMode, sync bool) errorwrite file shortcut, auto create directory -
WriteFileAppend(name string, data []byte, perm os.FileMode, sync bool) errorwrite file shortcut with append mode, auto create directory -
WriteFileDefault(name string, data []byte) errorwrite file shortcut with append mode, no sync, auto create directory -
WriteFileDefaultSync(name string, data []byte) errorwrite file shortcut with append mode, with sync, auto create directory
HttpXXResp the suffix, the return value is *Response
HttpXXDo the suffix, Need to pass parameters *Request
-
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() stringgenerates a random DESKTOP browser user-agent on every requests . -
UserAgentRandomMobile() stringgenerates a random MOBILE browser user-agent on every requests.
-
AesCBCEncrypt(text string, key string, iv string) (string, error)Aes CBC symmetric encryption, key length determines AES-128, AES-192, or AES-256 -
AesCBCDecrypt(cipherStr string, key string, iv string) (string, error)Aes CBC symmetric decryption -
AesGCMEncrypt(text string, key string, nonce string) (string, string, error)Aes GCM symmetric encryption, returns ciphertext and authentication tag -
AesGCMDecrypt(cipherStr string, tagStr string, key string, nonce string) (string, error)Aes GCM symmetric decryption