fun

package module
v0.94.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 7, 2024 License: Apache-2.0 Imports: 38 Imported by: 3

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 | 简体中文

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) 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().

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

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)

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

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.

Documentation

Index

Constants

View Source
const (
	SPACE      = " "
	DOT        = "."
	SLASH      = "/"
	UNDERSCORE = "_"
	COLON      = ":"
	DASH       = "-"
	LF         = "\n"
	CRLF       = "\r\n"
	CR         = "\r"
	TAB        = "\t"
)
View Source
const (
	DatePattern               = "2006-01-02"
	DatePatternSlash          = "2006/01/02"
	DatePatternUnderscore     = "2006_01_02"
	DatePatternZh             = "2006年01月02日"
	DatetimePattern           = "2006-01-02 15:04:05"
	DatetimeMilliPattern      = "2006-01-02 15:04:05.999"
	DatetimePatternSlash      = "2006/01/02 15:04:05"
	DatetimeMilliPatternSlash = "2006/01/02 15:04:05.999"
	DatetimePatternZh         = "2006年01月02日 15时04分05秒"
	DatetimePatternUtc        = "2006-01-02'T'15:04:05'Z'"
)
View Source
const (
	StringNumber          = "0123456789"
	StringUpperLetter     = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
	StringLowerLetter     = "abcdefghijklmnopqrstuvwxyz"
	StringLetter          = StringUpperLetter + StringLowerLetter
	StringLetterAndNumber = StringLetter + StringNumber
)
View Source
const (
	MimePlain             = "text/plain"
	MimeHtml              = "text/html"
	MimeJson              = "application/json"
	MimePostForm          = "application/x-www-form-urlencoded"
	MimeMultipartPostForm = "multipart/form-data"
	MimeProtobuf          = "application/x-protobuf"
	MimeYaml              = "application/x-yaml"
)
View Source
const (
	SizeB  = "B"
	SizeKB = "KB"
	SizeMB = "MB"
	SizeGB = "GB"
	SizeTB = "TB"
	SizePB = "PB"
	SizeEB = "EB"
)
View Source
const (
	BytesPerKB
	BytesPerMB
	BytesPerGB
	BytesPerTB
	BytesPerPB
	BytesPerEB
)
View Source
const (
	HttpDefaultTimeOut        = 10000
	HttpDefaultUserAgent      = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36"
	HttpDefaultAcceptEncoding = "gzip, deflate"
)
View Source
const (
	RegexLetter       string = "^[a-zA-Z]+$"
	RegexLetterNumber string = "^[a-zA-Z0-9]+$"
	RegexNumber       string = "^[0-9]+$"
	RegexChinese      string = "^[\u4e00-\u9fa5]+$"
	RegexEmail        string = "" /* 1277-byte string literal not displayed */
	RegexDateTime     string = "" /* 235-byte string literal not displayed */
)

Variables

View Source
var (
	RegexEmailPattern    = regexp.MustCompile(RegexEmail)
	RegexDateTimePattern = regexp.MustCompile(RegexDateTime)
)
View Source
var HttpDefaultTransport = &http.Transport{
	DialContext:           (&net.Dialer{Timeout: time.Second}).DialContext,
	ForceAttemptHTTP2:     true,
	MaxIdleConns:          150,
	MaxIdleConnsPerHost:   3,
	IdleConnTimeout:       60 * time.Second,
	TLSHandshakeTimeout:   10 * time.Second,
	ExpectContinueTimeout: 1 * time.Second,
	TLSClientConfig:       &tls.Config{InsecureSkipVerify: true},
}

HttpDefaultTransport 默认全局使用的 http.Transport

Functions

func AesCBCDecrypt added in v0.85.0

func AesCBCDecrypt(cipherStr string, key string, iv string) (string, error)

AesCBCDecrypt Aes CBC 对称加密

func AesCBCEncrypt added in v0.85.0

func AesCBCEncrypt(text string, key string, iv string) (string, error)

AesCBCEncrypt Aes CBC 对称加密, key 的长度决定 AES-128, AES-192, or AES-256

func Base64Decode

func Base64Decode(str string) string

Base64Decode 返回 Base64 值对应的字符串

func Base64Encode

func Base64Encode(str string) string

Base64Encode 返回字符串 Base64 值

func Base64UrlDecode

func Base64UrlDecode(str string) string

Base64UrlDecode 返回 Url Safe Base64 值对应的字符串

func Base64UrlEncode

func Base64UrlEncode(str string) string

Base64UrlEncode 返回字符串 Url Safe Base64 值

func Blank

func Blank(str string) bool

Blank 判断 Trim 后的字符串, 是否为空白

func BlankAll

func BlankAll(strs ...string) bool

BlankAll 判断 Trim 后的字符串集, 是否全部为空白

func BlankAny

func BlankAny(strs ...string) bool

BlankAny 判断 Trim 后的字符串集, 是否任意一个包含空白

func Bytes

func Bytes(s string) []byte

Bytes 更高效的字符串转字节数组

func CamelToSnake

func CamelToSnake(str string) string

CamelToSnake 驼峰转蛇形

func Command

func Command(bin string, argv []string, baseDir string) ([]byte, error)

Command 执行系统命令

func Contains

func Contains(str, substr string) bool

Contains 判断字符串是否包含指定的子串

func ContainsAny

func ContainsAny(str string, substr ...string) bool

ContainsAny 判断字符串是否包含任意一个指定的多个子串

func ContainsCase

func ContainsCase(str, substr string) bool

ContainsCase 判断字符串是否包含指定的子串, 不区分大小写

func Date

func Date(layouts ...any) string

Date 返回格式化后的日期时间字符串。 支持 Date()、Date(unixStamp)、Date(layout)、Date(layout, unixStamp)

func Empty

func Empty(value any) bool

Empty 判断是否为空, 支持字符串、数值、数组、Slice、Map

func EmptyAll

func EmptyAll(values ...any) bool

EmptyAll 判断是否全部为空

func EmptyAny

func EmptyAny(values ...any) bool

EmptyAny 判断是否任意一个为空

func FileExists added in v0.89.0

func FileExists(path string) bool

FileExists 检测目录或者文件是否存在,返回 bool

func HasPrefixCase

func HasPrefixCase(str, prefix string) bool

HasPrefixCase 判断字符串是否以指定前缀开头, 忽略大小写

func HasSuffixCase

func HasSuffixCase(str, prefix string) bool

HasSuffixCase 判断字符串是否以指定后缀结尾, 忽略大小写

func HttpDelete

func HttpDelete(urlStr string, args ...any) ([]byte, error)

HttpDelete 参数为请求地址 (HttpReq, 超时时间) HttpDelete(url)、HttpDelete(url, HttpReq)、HttpDelete(url, timeout)、HttpDelete(url, HttpReq, timeout) 返回 body, 错误信息

func HttpDeleteDo

func HttpDeleteDo(urlStr string, r *HttpReq, timeout int) ([]byte, error)

HttpDeleteDo Http Delete 请求, 参数为请求地址, HttpReq, 超时时间(毫秒) 返回 body, 错误信息

func HttpDo

func HttpDo(req *http.Request, r *HttpReq, timeout int) ([]byte, error)

HttpDo Http 请求, 参数为 http.Request, HttpReq, 超时时间(毫秒) 返回 body, 错误信息

func HttpGet

func HttpGet(urlStr string, args ...any) ([]byte, error)

HttpGet 参数为请求地址 (HttpReq, 超时时间) HttpGet(url)、HttpGet(url, HttpReq)、HttpGet(url, timeout)、HttpGet(url, HttpReq, timeout) 返回 body, 错误信息

func HttpGetDo

func HttpGetDo(urlStr string, r *HttpReq, timeout int) ([]byte, error)

HttpGetDo Http Get 请求, 参数为请求地址, HttpReq, 超时时间(毫秒) 返回 body, 错误信息

func HttpPost

func HttpPost(urlStr string, args ...any) ([]byte, error)

HttpPost 参数为请求地址 (body io.Reader, HttpReq, 超时时间) HttpPost(url)、HttpPost(url, timeout)、HttpPost(url, body)、HttpPost(url, body, timeout)、HttpPost(url, body, HttpReq)、HttpPostForm(url, body, HttpReq, timeout) 返回 body, 错误信息

func HttpPostDo

func HttpPostDo(urlStr string, body io.Reader, r *HttpReq, timeout int) ([]byte, error)

HttpPostDo Http Post, 参数为请求地址, body io.Reader, HttpReq, 超时时间(毫秒) 返回 body, 错误信息

func HttpPostForm

func HttpPostForm(urlStr string, args ...any) ([]byte, error)

HttpPostForm 参数为请求地址 (Form 数据 map[string]string, HttpReq, 超时时间) HttpPostForm(url)、HttpPostForm(url, timeout)、HttpPostForm(url, posts)、HttpPostForm(url, posts, timeout)、HttpPostForm(url, posts, HttpReq)、HttpPostForm(url, posts, HttpReq, timeout) 返回 body, 错误信息

func HttpPostFormDo

func HttpPostFormDo(urlStr string, posts map[string]string, r *HttpReq, timeout int) ([]byte, error)

HttpPostFormDo Http Post Form, 参数为请求地址, Form 数据 map[string]string, HttpReq, 超时时间(毫秒) 返回 body, 错误信息

func HttpPostJson

func HttpPostJson(urlStr string, args ...any) ([]byte, error)

HttpPostJson 参数为请求地址 (Json 数据 string, HttpReq, 超时时间) HttpPostJson(url)、HttpPostJson(url, timeout)、HttpPostJson(url, json)、HttpPost(url, json, timeout)、HttpPost(url, json, HttpReq)、HttpPost(url, json, HttpReq, timeout) 返回 body, 错误信息

func HttpPostJsonDo

func HttpPostJsonDo(urlStr string, json string, r *HttpReq, timeout int) ([]byte, error)

HttpPostJsonDo Http Post Json 请求, 参数为请求地址, Json 数据 string, HttpReq, 超时时间(毫秒) 返回 body, 错误信息

func HttpPut

func HttpPut(urlStr string, args ...any) ([]byte, error)

HttpPut 参数为请求地址 (body io.Reader, HttpReq, 超时时间) HttpPut(url)、HttpPut(url, timeout)、HttpPut(url, body)、HttpPut(url, body, timeout)、HttpPut(url, body, HttpReq)、HttpPut(url, body, HttpReq, timeout) 返回 body, 错误信息

func HttpPutDo

func HttpPutDo(urlStr string, body io.Reader, r *HttpReq, timeout int) ([]byte, error)

HttpPutDo Http Put, 参数为请求地址, body io.Reader, HttpReq, 超时时间(毫秒) 返回 body, 错误信息

func HttpPutForm

func HttpPutForm(urlStr string, args ...any) ([]byte, error)

HttpPutForm 参数为请求地址 (Form 数据 map[string]string, HttpReq, 超时时间) HttpPutForm(url)、HttpPutForm(url, timeout)、HttpPutForm(url, posts)、HttpPutForm(url, posts, timeout)、HttpPutForm(url, posts, HttpReq)、HttpPutForm(url, posts, HttpReq, timeout) 返回 body, 错误信息

func HttpPutFormDo

func HttpPutFormDo(urlStr string, posts map[string]string, r *HttpReq, timeout int) ([]byte, error)

HttpPutFormDo Http Put Form, 参数为请求地址, Form 数据 map[string]string, HttpReq, 超时时间(毫秒) 返回 body, 错误信息

func HttpPutJson

func HttpPutJson(urlStr string, args ...any) ([]byte, error)

HttpPutJson 参数为请求地址 (Json 数据 string, HttpReq, 超时时间) HttpPutJson(url)、HttpPutJson(url, timeout)、HttpPutJson(url, json)、HttpPutJson(url, json, timeout)、HttpPutJson(url, json, httpReq)、HttpPutJson(url, json, httpReq, timeout) 返回 body, 错误信息

func HttpPutJsonDo

func HttpPutJsonDo(urlStr string, json string, r *HttpReq, timeout int) ([]byte, error)

HttpPutJsonDo Http Put Json 请求, 参数为请求地址, Json 数据 string, HttpReq, 超时时间(毫秒) 返回 body, 错误信息

func If added in v0.87.0

func If[T any](condition bool, trueVal, falseVal T) T

If 三元运算符

func IntsToStrings

func IntsToStrings(slice []int) []string

IntsToStrings int 切片转换为字符串切片

func Ip2Long

func Ip2Long(ipStr string) uint32

Ip2Long 字符串 IP 转整型

func IsASCII

func IsASCII(s string) bool

IsASCII 判断字符串是否全部 ASCII

func IsASCIILetter

func IsASCIILetter(str string) bool

IsASCIILetter 判断字符串是否全部为ASCII的字母

func IsDir

func IsDir(path string) bool

IsDir 是否是目录

func IsEmail

func IsEmail(str string) bool

IsEmail 验证 Email 是否合法

func IsExist

func IsExist(path string) bool

IsExist 文件或目录是否存在

func IsIp added in v0.93.0

func IsIp(ipStr string) bool

IsIp 是否是有效的 IP

func IsIpV4 added in v0.93.0

func IsIpV4(ipStr string) bool

IsIpV4 是否是有效的 IpV4

func IsIpV6 added in v0.93.0

func IsIpV6(ipStr string) bool

IsIpV6 是否是有效的 IpV6

func IsLetter

func IsLetter(str string) bool

IsLetter 判断字符串是否全部为字母

func IsNumber

func IsNumber(str string) bool

IsNumber 判断字符串是否全部为数字

func IsUtf8

func IsUtf8(p []byte) bool

IsUtf8 判断是否为 UTF-8 编码

func Long2Ip

func Long2Ip(long uint32) string

Long2Ip 整型转字符串 IP

func LongestCommonSubString

func LongestCommonSubString(x, y string) int

LongestCommonSubString 计算两个字符串最大公共子串长度

func MapKeys

func MapKeys[K comparable, V any](m map[K]V) []K

MapKeys 返回map的键切片

func MapMerge

func MapMerge[K comparable, V any](maps ...map[K]V) map[K]V

MapMerge 合并多个map, 如果有相同的键, 则后者会覆盖前者

func MapValues

func MapValues[K comparable, V any](m map[K]V) []V

MapValues 返回map的值切片

func Matches

func Matches(str, pattern string) bool

Matches 判断字符串是否匹配指定的正则表达式

func Max

func Max(a, b int) int

Max 取 int 最大值

func MaxInt64

func MaxInt64(a, b int64) int64

MaxInt64 取 int64 最大值

func MaxN

func MaxN[T GenNumber](args ...T) T

MaxN 取 N 个数字的最大值

func Md5

func Md5(str string) string

Md5 返回字符串 Md5 值

func Md5Bit16

func Md5Bit16(str string) string

Md5Bit16 返回 16位 字符串 Md5 值

func Memory

func Memory(format string) map[string]int64

Memory 指定格式返回当前主要的内存指标信息, (ReadMemStats 会 stopTheWorld, 谨慎非频繁使用)

func MemoryBytes

func MemoryBytes() map[string]int64

MemoryBytes 返回当前主要的内存指标信息 (ReadMemStats 会 stopTheWorld, 谨慎非频繁使用)

func Min

func Min(a, b int) int

Min 取 int 最小值

func MinInt64

func MinInt64(a, b int64) int64

MinInt64 取 int64 最小值

func MinN

func MinN[T GenNumber](args ...T) T

MinN 取 N 个数字的最小值

func Mkdir added in v0.89.0

func Mkdir(dir string, perm os.FileMode) error

Mkdir 创建一个目录,如果目录已存在则忽略

func NormaliseLine

func NormaliseLine(str string) string

NormaliseLine 规范化此字符串中的换行, 多个换行合并为一个换行

func NormaliseSpace

func NormaliseSpace(str string) string

NormaliseSpace 规范化此字符串中的空白, 多个空格合并为一个空格, 所有空白字符例如换行符、制表符, 都转换为一个简单的空格。

func PadBoth

func PadBoth(str string, padStr string, padLen int) string

PadBoth 两侧填充字符串到指定长度

func PadLeft

func PadLeft(str string, padStr string, padLen int) string

PadLeft 左侧填充字符串到指定长度

func PadRight

func PadRight(str string, padStr string, padLen int) string

PadRight 右侧填充字符串到指定长度

func Random

func Random() int

Random 返回随机数 `[0, MaxInt)`

func RandomInt

func RandomInt(min, max int) int

RandomInt 返回随机数 `[min, max)`

func RandomInt64

func RandomInt64(min, max int64) int64

RandomInt64 返回随机数 `[min, max)`

func RandomLetter

func RandomLetter(length int) string

RandomLetter 返回指定长度的随机字符串, 仅包含字母

func RandomNumber

func RandomNumber(length int) string

RandomNumber 返回指定长度的随机字符串, 仅包含数字

func RandomPool

func RandomPool(pool string, length int) string

RandomPool 从提供的字符串池中返回指定长度的随机字符串

func RandomString

func RandomString(length int) string

RandomString 返回指定长度的随机字符串, 包含字母和数字

func Remove

func Remove(str, remove string) string

Remove 移除字符串中指定的字符串

func RemoveAny

func RemoveAny(str string, removes ...string) string

RemoveAny 移除字符串中指定的字符串集

func RemoveLines

func RemoveLines(str string) string

RemoveLines 移除换行符, 换行符包括 \n \r\n, 性能原因, 不使用 strings.NewReplacer

func RemovePrefix

func RemovePrefix(str, prefix string) string

RemovePrefix 左侧移除字符串中指定的字符串

func RemoveSign

func RemoveSign(str string) string

RemoveSign 将字符串的所有数据依次写成一行, 去除无意义字符串(标点符号、符号), 性能原因, 不使用 strings.NewReplacer

func RemoveSuffix

func RemoveSuffix(str string, suffix string) string

RemoveSuffix 右侧移除字符串中指定的字符串

func Reverse

func Reverse(str string) string

Reverse 反转字符串

func Sha1

func Sha1(str string) string

Sha1 返回字符串 Sha1 值

func Sha256

func Sha256(str string) string

Sha256 返回字符串 Sha256 值

func Sha384

func Sha384(str string) string

Sha384 返回字符串 Sha384 值

func Sha512

func Sha512(str string) string

Sha512 返回字符串 Sha512 值

func Similarity

func Similarity(a, b string) float64

Similarity 计算两个原始字符串的相似度

func SimilarityText

func SimilarityText(a, b string) float64

SimilarityText 计算两个字符串移除特殊符号后的相似度

func SliceColumn

func SliceColumn[T, V any](slice []T, key any) []V

SliceColumn 返回所有行的某一列

func SliceConcat

func SliceConcat[T any](slice []T, values ...[]T) []T

SliceConcat 合并多个切片, 非去重, 非原始切片

func SliceContains

func SliceContains[T comparable](slice []T, v T) bool

SliceContains 判断整型和字符串是否在切片中

func SliceEqual

func SliceEqual[T comparable](slice1, slice2 []T) bool

SliceEqual 切片是否相等: 长度相同且所有元素的顺序和值相等

func SliceEvery

func SliceEvery[T any](slice []T, predicate func(index int, item T) bool) bool

SliceEvery 切片中的所有元素都满足函数,则返回 true

func SliceFilter

func SliceFilter[T any](slice []T, predicate func(index int, item T) bool) []T

SliceFilter 筛选出切片中满足函数的所有元素

func SliceForEach

func SliceForEach[T any](slice []T, iteratee func(index int, item T))

SliceForEach 切片中所有元素都执行函数

func SliceIndex

func SliceIndex[T comparable](slice []T, v T) int

SliceIndex 对数值和字符串切片按照指定值进行查找

func SliceIntersection

func SliceIntersection[T comparable](slices ...[]T) []T

SliceIntersection 切片交集且去重(顺序不能保证)

func SliceLastIndex

func SliceLastIndex[T comparable](slice []T, v T) int

SliceLastIndex 对数值和字符串切片按照指定值进行查找, 返回最后一个匹配的索引

func SliceMap

func SliceMap[T any, U any](slice []T, iteratee func(index int, item T) U) []U

SliceMap 切片中所有元素都执行函数, 有返回值

func SliceNone

func SliceNone[T any](slice []T, predicate func(index int, item T) bool) bool

SliceNone 切片中的所有元素都不满足函数,则返回 true

func SliceReduce

func SliceReduce[T any](slice []T, iteratee func(index int, result, item T) T, initial T) T

SliceReduce 处理所有切片中元素得到结果

func SliceRemove

func SliceRemove[T comparable](slice []T, v T) []T

SliceRemove 移除数值和字符串切片中的指定值

func SliceRemoveBlank

func SliceRemoveBlank(slice []string) []string

SliceRemoveBlank 移除字符串切片中的空值

func SliceReplace

func SliceReplace[T comparable](slice []T, old T, new T, n int) []T

SliceReplace 返回切片的副本,前n个元素替换为新的

func SliceReplaceAll

func SliceReplaceAll[T comparable](slice []T, old T, new T) []T

SliceReplaceAll 返回切片的副本,所有匹配到的元素都替换为新的

func SliceSome

func SliceSome[T any](slice []T, predicate func(index int, item T) bool) bool

SliceSome 切片中有一个元素满足函数,就返回true

func SliceSortBy

func SliceSortBy(slice any, field string, sortType ...string) error

SliceSortBy 根据字段排序(field的大小写应该和字段保持一致)

func SliceSplit

func SliceSplit[T comparable](slice []T, size int) [][]T

SliceSplit 对数值和字符串切片按照指定长度进行分割

func SliceTrim

func SliceTrim(slice []string) []string

SliceTrim 对字符串切片进行 Trim, 并自动忽略空值

func SliceUnion

func SliceUnion[T comparable](slices ...[]T) []T

SliceUnion 顺序合并且去重

func SliceUnionBy

func SliceUnionBy[T any, V comparable](predicate func(item T) V, slices ...[]T) []T

SliceUnionBy 顺序合并且去重, 支持自定义函数

func SliceUnique

func SliceUnique[T comparable](slice []T) []T

SliceUnique 对数值和字符串切片进行去重(会改变元素的顺序)

func SnakeToCamel

func SnakeToCamel(str string, bigCamel bool) string

SnakeToCamel 蛇形转驼峰

func SplitTrim

func SplitTrim(str, sep string) []string

SplitTrim 分割字符串为字符串切片, 对分割后的值进行 Trim , 并自动忽略空值

func SplitTrimToInts

func SplitTrimToInts(str, sep string) []int

SplitTrimToInts 分割字符串为 int 切片, 对分割后的值进行 Trim , 并自动忽略空值

func StrAfter

func StrAfter(s, char string) string

StrAfter 截取在字符首次出现时的位置之后的子字符串

func StrAfterLast

func StrAfterLast(s, char string) string

StrAfterLast 截取在字符最后出现时的位置之后的子字符串

func StrBefore

func StrBefore(s, char string) string

StrBefore 截取在字符首次出现时的位置之前的子字符串

func StrBeforeLast

func StrBeforeLast(s, char string) string

StrBeforeLast 截取在字符最后出现时的位置之前的子字符串

func StrToTime

func StrToTime(args ...any) int64

StrToTime 日期时间字符串转时间戳 支持 StrToTime()、StrToTime(string)、StrToTime(string, int64)

func String

func String(b []byte) string

String 更高效的字节数组转字符串

func StringsToInts

func StringsToInts(slice []string) []int

StringsToInts 字符串切片转换为 int 切片

func StructCopy

func StructCopy(src, dst any)

StructCopy 复制 struct 对象

func SubString

func SubString(str string, pos, length int) string

SubString 字符串截取

func Template

func Template(tpl string, data any) (string, error)

Template 模板渲染

func Timestamp

func Timestamp(millis ...any) int64

Timestamp 返回当前时间的 Unix 时间戳。 默认返回秒级, 支持 Timestamp(true) 返回毫秒级

func ToBool

func ToBool(str string) bool

ToBool 字符串转 bool 类型

func ToDuration added in v0.90.0

func ToDuration(value any) time.Duration

ToDuration 将数字、字符串转换为 time.Duration,默认是 ns, 如果是字符串,支持 ns,ms,us,s,m,h

func ToDurationMs added in v0.90.0

func ToDurationMs(value any) time.Duration

ToDurationMs 将数字、字符串转换为 time.Duration,默认是 ms, 如果是字符串,支持 ns,ms,us,s,m,h

func ToFloat32 added in v0.90.0

func ToFloat32(value any) float32

ToFloat32 数字或字符串转 float32

func ToFloat64 added in v0.90.0

func ToFloat64(value any) float64

ToFloat64 数字或字符串转 float64

func ToInt

func ToInt(value any) int

ToInt 数字或字符串转 int 类型

func ToInt64

func ToInt64(value any) int64

ToInt64 数字或字符串转 int64

func ToJson

func ToJson(object any) string

ToJson 将对象转换为 Json 字符串

func ToJsonIndent added in v0.90.0

func ToJsonIndent(object any) string

ToJsonIndent 将对象转换为 Json 字符串, 带缩进

func ToLong

func ToLong(value any) int64

ToLong ToInt64 别名, 数字或字符串转 int64

func ToString

func ToString(value any) string

ToString 将任意一个类型转换为字符串

func ToUint

func ToUint(value any) uint

ToUint 数字或字符串转 uint

func ToUint8

func ToUint8(value any) uint8

ToUint8 数字或字符串转 uint8

func ToUtf8

func ToUtf8(origin []byte, encode string) ([]byte, error)

ToUtf8 指定字符集转 utf-8

func Unwrap

func Unwrap(str string, wrapStr string) string

Unwrap 去除字符串包围, 非递归

func UrlParse

func UrlParse(rawURL string) (*url.URL, error)

UrlParse url.Parse 在没有 scheme 时不会出错

func UserAgentRandom added in v0.92.0

func UserAgentRandom() string

UserAgentRandom generates a random DESKTOP browser user-agent on every requests

func UserAgentRandomMobile added in v0.92.0

func UserAgentRandomMobile() string

UserAgentRandomMobile generates a random MOBILE browser user-agent on every requests

func Utf8To

func Utf8To(utf8 []byte, encode string) ([]byte, error)

Utf8To utf-8 转指定字符集

func Wrap

func Wrap(str string, wrapStr string) string

Wrap 使用字符串包围原字符串

func WriteFile added in v0.89.0

func WriteFile(name string, data []byte, flag int, perm os.FileMode, sync bool) error

WriteFile 写入文件

func WriteFileAppend added in v0.89.0

func WriteFileAppend(name string, data []byte, perm os.FileMode, sync bool) error

WriteFileAppend 追加写入文件

Types

type GenFloat

type GenFloat interface {
	float32 | float64
}

GenFloat 浮点型范型集合

type GenInteger

type GenInteger interface {
	int | int8 | int16 | int32 | int64 | uint | uint8 | uint16 | uint32 | uint64
}

GenInteger 整型范型集合

type GenNumber

type GenNumber interface {
	GenInteger | GenFloat
}

GenNumber 数值范型集合

type HttpReq

type HttpReq struct {
	// UserAgent 优先于请求头 Headers 中的 User-Agent 字段
	UserAgent string

	// 请求头
	Headers map[string]string

	// 限制最大返回大小
	MaxContentLength int64

	// 限制允许访问 ContentType 列表, 前缀匹配
	AllowedContentTypes []string

	// 最大 Redirect 次数, 范围 [0,10), 否则采用默认的跳转策略 (最大限制 10 次)
	MaxRedirect int

	// 禁止跳转
	DisableRedirect bool

	// 请求失败错误时仍然读取 Body
	ReadBodyWithFail bool

	// http.Transport
	Transport http.RoundTripper

	// http.CookieJar
	Jar http.CookieJar
}

type HttpResp

type HttpResp struct {
	// 是否成功 (200-299), 成功仍可能返回 err
	Success bool

	// Http 状态码
	StatusCode int

	// 响应体
	Body []byte

	// ContentLength (字节数)
	ContentLength int64

	// 响应头
	Headers *http.Header

	// 最后请求
	RequestURL *url.URL
}

func HttpDeleteResp

func HttpDeleteResp(urlStr string, r *HttpReq, timeout int) (*HttpResp, error)

HttpDeleteResp Http Delete 请求, 参数为请求地址, HttpReq, 超时时间(毫秒) 返回 HttpResp, 错误信息

func HttpDoResp

func HttpDoResp(req *http.Request, r *HttpReq, timeout int) (*HttpResp, error)

HttpDoResp Http 请求, 参数为 http.Request, HttpReq, 超时时间(毫秒) 返回 HttpResp, 错误信息

func HttpGetResp

func HttpGetResp(urlStr string, r *HttpReq, timeout int) (*HttpResp, error)

HttpGetResp Http Get 请求, 参数为请求地址, HttpReq, 超时时间(毫秒) 返回 HttpResp, 错误信息

func HttpPostFormResp

func HttpPostFormResp(urlStr string, posts map[string]string, r *HttpReq, timeout int) (*HttpResp, error)

HttpPostFormResp Http Post Form, 参数为请求地址, Form 数据 map[string]string, HttpReq, 超时时间(毫秒) 返回 HttpResp, 错误信息

func HttpPostJsonResp

func HttpPostJsonResp(urlStr string, json string, r *HttpReq, timeout int) (*HttpResp, error)

HttpPostJsonResp Http Post Json 请求, 参数为请求地址, Json 数据 string, HttpReq, 超时时间(毫秒) 返回 HttpResp, 错误信息

func HttpPostResp

func HttpPostResp(urlStr string, body io.Reader, r *HttpReq, timeout int) (*HttpResp, error)

HttpPostResp Http Post, 参数为请求地址, body io.Reader, HttpReq, 超时时间(毫秒) 返回 HttpResp, 错误信息

func HttpPutFormResp

func HttpPutFormResp(urlStr string, posts map[string]string, r *HttpReq, timeout int) (*HttpResp, error)

HttpPutFormResp Http Put Form, 参数为请求地址, Form 数据 map[string]string, HttpReq, 超时时间(毫秒) 返回 HttpResp, 错误信息

func HttpPutJsonResp

func HttpPutJsonResp(urlStr string, json string, r *HttpReq, timeout int) (*HttpResp, error)

HttpPutJsonResp Http Put Json 请求, 参数为请求地址, Json 数据 string, HttpReq, 超时时间(毫秒) 返回 HttpResp, 错误信息

func HttpPutResp

func HttpPutResp(urlStr string, body io.Reader, r *HttpReq, timeout int) (*HttpResp, error)

HttpPutResp Http Put, 参数为请求地址, body io.Reader, HttpReq, 超时时间(毫秒) 返回 HttpResp, 错误信息

Directories

Path Synopsis
Package strtotime provides a Go implementation of the popular PHP function.
Package strtotime provides a Go implementation of the popular PHP function.
tree
tire
Package tire TireTree 实现
Package tire TireTree 实现

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL