x-funs/go-fun
Acerca de
Go with Fun (Functions) is a small and useful Golang util function library. It Includes such as Empty、Blank、Strtotime、Similarity、HttpGet etc.
Herramientas de desarrolloCrecimiento de estrellas medido
- in 24h
- 0
- in 7 days
- 0
- in 15 days
- 0
- in 1 month
- Recopilando historial
Cambios netos en períodos que se solapan, no totales diarios. Los datos no disponibles se dejan en blanco. Las estrellas indican interés, no calidad.
README.md
Original ____
____ _____ / __/_ ______
/ __ `/ __ \______/ /_/ / / / __ \
/ /_/ / /_/ /_____/ __/ /_/ / / / /
\__, /\____/ /_/ \__,_/_/ /_/
/____/
Go with Fun (Functions) is a small and useful Golang utility function library. It includes helpers such as Empty, Blank, StrToTime, Similarity, and HttpGet.
English | 简体中文
Installation
go get -u github.com/x-funs/go-fun
Example
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) 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"
"time"
"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) TVerify condition is true, return trueVal or falseValEmpty(value any) boolVerify whether a value is empty; supports strings, numbers, arrays, slices, and mapsEmptyAll(values ...any) boolVerify whether values all are emptyEmptyAny(values ...any) boolVerify whether values any is emptyMemoryBytes() 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 fromGinString(b []byte) stringEfficient byte array to string, reference fromGinCommand(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
}
Hash
Function List
Md5(str string) stringReturn the Md5 stringMd5Bit16(str string) stringReturn the 16-bit Md5 stringSha1(str string) stringReturn the Sha1 stringSha256(str string) stringReturn the Sha256 stringSha384(str string) stringReturn the Sha384 stringSha512(str string) stringReturn the Sha512 stringBase64Encode(str string) stringReturn the Base64 stringBase64Decode(str string) stringReturn the Base64 decode stringBase64UrlEncode(str string) stringReturn the Url Safe Base64 stringBase64UrlDecode(str string) stringReturn the Url Safe Base64 decode string
Judgment
Function List
IsNumber(str string) boolDetermine whether all strings are numbersIsUtf8(p []byte) boolDetermine whether bytes are valid UTF-8IsASCIILetter(str string) boolDetermine whether all strings are ASCII lettersIsLetter(str string) boolDetermine whether all strings are lettersIsASCII(s string) boolDetermine whether the string is all ASCIIIsEmail(str string) boolVerify EmailIsExist(path string) boolDoes the file or directory existIsDir(path string) boolIs it a directoryIsIp(ipStr string) boolDetermine whether a string is a valid IP addressIsIpV4(ipStr string) boolDetermine whether a string is a valid IPv4 addressIsIpV6(ipStr string) boolDetermine whether a string is a valid IPv6 address
Map
Function List
MapKeys[K comparable, V any](m map[K]V) []KReturn slices of all keys of mapMapValues[K comparable, V any](m map[K]V) []VReturn a slice of all values of mapMapMerge[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
Math
Function List
Max(a, b int) intTake int maximumMin(a, b int) intTake int minimumMaxInt64(a, b int64) int64Take int64 maximumMinInt64(a, b int64) int64Take int64 minimumMaxN[T GenNumber](args ...T) TTake the maximum value of n numbersMinN[T GenNumber](args ...T) TTake the minimum value of n numbers
Random
Function List
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
Regex
Function List
Matches(str, pattern string) boolDetermines whether the string matches the specified regular expression.
Similarity
Function List
Similarity(a, b string) float64Calculates the similarity of two original stringsSimilarityText(a, b string) float64Calculate the similarity of two strings after removing special symbolsLongestCommonSubString(x, y string) intCalculates the longest common subsequence length of two strings
Slice
Function List
SliceSplit[T comparable](slice []T, size int) [][]TDivide numeric and string slices according to the specified lengthSliceUnion[T comparable](slices ...[]T) []TSequential merge and deweightSliceColumn[T, V any](slice []T, key any) []VReturn a column of all rowsIntsToStrings(slice []int) []stringInt slice to string sliceStringsToInts(slice []string) []intString slice to int sliceSliceContains[T comparable](slice []T, v T) boolDetermine whether integer and string are in sliceSliceUnique[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 valueSliceLastIndex[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 slicesSliceRemoveBlank(slice []string) []stringRemove null values from string slicesSliceTrim(slice []string) []stringTrim string slices and automatically ignore null valuesSliceConcat[T any](slice []T, values ...[]T) []TMerge multiple slices, non-degravimetric, non-original slicesSliceEqual[T comparable](slice1, slice2 []T) boolAre slices equal: the same length and the order and value of all elements are equalSliceEvery[T any](slice []T, predicate func(index int, item T) bool) boolAll elements in the slice satisfy the function, return trueSliceNone[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 functionSliceForEach[T any](slice []T, iteratee func(index int, item T))All elements in the slice execute functionsSliceMap[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 resultsSliceReplace[T comparable](slice []T, old T, new T, n int) []TReturn a copy of the slice, with the first n elements replaced with the newSliceReplaceAll[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 functionsSliceIntersection[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]
}
String
Function List
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 characterStrAfter(s, char string) stringInterception of substrings after the position of the character when it first appearsStrAfterLast(s, char string) stringInterception of substrings after the last appearance of the characterBlank(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 caseHasSuffixCase(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 substringContainsCase(str, substr string) boolDetermine whether the string contains the specified substring, case-insensitiveContainsAny(str string, substr ...string) boolDetermine whether the string contains any of the specified substrings.SnakeToCamel(str string, bigCamel bool) stringSerpentine humpCamelToSnake(str string) stringHump turns to snakePadLeft(str string, padStr string, padLen int) stringFill the string on the left to the specified lengthPadRight(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 lengthWrap(str string, wrapStr string) stringEnclosed the original string with a stringUnwrap(str string, wrapStr string) stringRemove string bounding, non-recursiveReverse(str string) stringReverse stringRemove(str, remove string) stringRemoves the specified string in the stringRemovePrefix(str, prefix string) stringRemoves the string specified in the string on the leftRemoveSuffix(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 stringRemoveSign(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 interceptionNormaliseSpace(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
}
Struct
Function List
StructCopy(src, dst any) errorCopy matching exported fields from one struct to anotherStructCompareSomeField(some, dst any) (bool, error)Compare selected fields from one struct against another
To
Function List
Ip2Long(ipStr string) uint32String IP to integerIp2LongE(ipStr string) (uint32, error)String IP to integer, with error returnLong2Ip(long uint32) stringInteger to string IPToString(value any) stringConverts any type to a stringToInt(value any) intNumber or string to int typeToIntE(value any) (int, error)Number or string to int type, with error returnToLong(value any) int64ToInt64 alias, number or string to int64ToLongE(value any) (int64, error)ToInt64E alias, with error returnToBool(str string) boolstring to bool typeToBoolE(str string) (bool, error)string to bool type, with error returnToUint(value any) uintNumber or string to uintToUintE(value any) (uint, error)Number or string to uint, with error returnToUint8(value any) uint8Number or string to uint8ToUint8E(value any) (uint8, error)Number or string to uint8, with error returnToInt64(value any) int64Number or string to int64ToInt64E(value any) (int64, error)Number or string to int64, with error returnToUint64(value any) uint64Number or string to uint64ToUint64E(value any) (uint64, error)Number or string to uint64, with error returnToFloat32(value any) float32Number or string to float32ToFloat32E(value any) (float32, error)Number or string to float32, with error returnToFloat64(value any) float64Number or string to float64ToFloat64E(value any) (float64, error)Number or string to float64, with error returnToUtf8(origin []byte, encode string) ([]byte, error)Specify character set conversion utf-8Utf8To(utf8 []byte, encode string) ([]byte, error)utf-8 to specify character setToJson(object any) stringConverts an object to a Json stringToJsonIndent(object any) stringConverts an object to an indented JSON stringToDuration(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"
File
Function List
Mkdir(dir string, perm os.FileMode) errorCreate a directory, ignoring if the directory already existsMkdirAll(dir string, perm os.FileMode) errorCreate a directory and any necessary parent directoriesIsExist(path string) boolCheck whether the directory or file existsWriteFile(name string, data []byte, flag int, perm os.FileMode, sync bool) errorwrite file shortcut, auto create directoryWriteFileAppend(name string, data []byte, perm os.FileMode, sync bool) errorwrite file shortcut with append mode, auto create directoryWriteFileDefault(name string, data []byte) errorwrite file shortcut with truncate mode, no sync, auto create directoryWriteFileDefaultSync(name string, data []byte) errorwrite file shortcut with truncate mode and sync, auto create directory
Http
HttpXXRespfunctions return*HttpResp.
HttpXXDofunctions return[]byteand accept concrete request data plus*HttpReqwhere applicable.
Function List
HttpGet(urlStr string, args ...any) ([]byte, error)The HttpGet parameter is the request address (HttpReq, timeout)HttpDelete(urlStr string, args ...any) ([]byte, error)The HttpDelete 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)HttpPut(urlStr string, args ...any) ([]byte, error)The HttpPut parameter is the request address (body io.Reader, HttpReq, timeout)HttpPutForm(urlStr string, args ...any) ([]byte, error)The HttpPutForm parameter is the request address (FormData map[string]string, HttpReq, timeout)HttpPutJson(urlStr string, args ...any) ([]byte, error)The HttpPutJson parameter is the request address (JsonData string, HttpReq, timeout)HttpDo(req *http.Request, r *HttpReq, timeout int) ([]byte, error)Execute a custom HTTP request and return the response bodyHttpDoResp(req *http.Request, r *HttpReq, timeout int) (*HttpResp, error)Execute a custom HTTP request and return response metadataHttpXXResp(...) (*HttpResp, error)Response variants are available for GET, DELETE, POST, POST form/json, PUT, and PUT form/jsonHttpXXDo(...) ([]byte, error)Body-only variants are available for GET, DELETE, POST, POST form/json, PUT, and PUT form/jsonUrlParse(rawURL string) (*url.URL, error)Parse a URL string and require a valid hostname; include a scheme such ashttp://for plain domainsUserAgentRandom() stringgenerates a random DESKTOP browser user-agent on every requests .UserAgentRandomMobile() stringgenerates a random MOBILE browser user-agent on every requests.
AES
Function List
AesCBCEncrypt(text string, key string, iv string) (string, error)Aes CBC symmetric encryption, key length determines AES-128, AES-192, or AES-256AesCBCDecrypt(cipherStr string, key string, iv string) (string, error)Aes CBC symmetric decryptionAesGCMEncrypt(text string, key string, nonce string) (string, string, error)Aes GCM symmetric encryption, returns ciphertext and authentication tagAesGCMDecrypt(cipherStr string, tagStr string, key string, nonce string) (string, error)Aes GCM symmetric decryption
Explorar proyectos relacionados
Cargando…