utils

package
v0.0.0-...-9a26220 Latest Latest
Warning

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

Go to latest
Published: Apr 6, 2025 License: AGPL-3.0 Imports: 92 Imported by: 0

Documentation

Overview

Package bytefmt contains helper methods and constants for converting to and from a human-readable byte format.

bytefmt.ByteSize(100.5*bytefmt.MEGABYTE) // "100.5M"
bytefmt.ByteSize(uint64(1024)) // "1K"

sshclient implements an ssh client

Index

Examples

Constants

View Source
const (
	BYTE = 1 << (10 * iota)
	KILOBYTE
	MEGABYTE
	GIGABYTE
	TERABYTE
	PETABYTE
	EXABYTE
)
View Source
const (
	DatabaseCacheItemNormal databaseCacheItemStatus = iota // save to database before  expired
	DatabaseCacheItemSave                                  // expired, save to database and delete(default) or update(Update-status)
	DatabaseCacheItemUpdate                                // someone peek the instruction when save, update the instruction after save
	DatabaseCacheItemNotFound
)
View Source
const (
	AllSepcialChars = ",./<>?;':\"[]{}`~!@#$%^&*()_+-=\\|"
	LittleChar      = "abcdefghijklmnopqrstuvwxyz"
	BigChar         = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
	NumberChar      = "1234567890"
	LetterChar      = LittleChar + BigChar
	AlphaNumChar    = LittleChar + BigChar + NumberChar
	PasswordChar    = passwordSepcialChars + LittleChar + BigChar + NumberChar
)
View Source
const CRLF = "\r\n"
View Source
const DefaultDateFormat = "2006-01-02"
View Source
const DefaultTimeFormat = "2006_01_02-15_04_05"
View Source
const DefaultTimeFormat2 = "20060102_15_04_05"

Variables

View Source
var (
	GbkToUtf8 = codec.GbkToUtf8
	Utf8ToGbk = codec.Utf8ToGbk
)
View Source
var BashCompleteScriptTpl = `` /* 1147-byte string literal not displayed */
View Source
var ErrClosedPipe = errors.New("bufpipe: read/write on closed pipe")

ErrClosedPipe is the error used for read or write operations on a closed pipe.

View Source
var ErrCoolDownSkipCache = Error("Skip cache")
View Source
var GBKSafeString = codec.GBKSafeString
View Source
var ParseStringToInts = ParseStringToPorts
View Source
var ShrinkString = codec.ShrinkString
View Source
var (
	TargetIsLoopback = Errorf("loopback")
)
View Source
var WaitBySignal = func(fn func(), sigs ...os.Signal) {
	sigC := NewSignalChannel(sigs...)
	defer signal.Stop(sigC)

	for {
		select {
		case <-sigC:
			log.Warn("recv signal abort")
			fn()
			return
		}
	}
}
View Source
var WaitReleaseBySignal = func(fn func()) {
	sigC := NewSignalChannel(os.Interrupt, syscall.SIGTERM, syscall.SIGINT, syscall.SIGKILL)
	defer signal.Stop(sigC)

	for {
		select {
		case <-sigC:
			log.Warn("recv signal abort")
			fn()
			return
		}
	}
}
View Source
var ZshCompleteScriptTpl = `` /* 1072-byte string literal not displayed */

Functions

func AddressFamilyUint32ToString

func AddressFamilyUint32ToString(i uint32) string

func AppendDefaultPort

func AppendDefaultPort(raw string, port int) string

AppendDefaultPort returns host:port format. If the port is already specified in the host, it will be returned directly. wss -> 443 ws -> 80 http -> 80 https -> 443

func AppendSliceItemWhenNotExists

func AppendSliceItemWhenNotExists[T comparable](s []T, t T) []T

func AsDebugString

func AsDebugString(i interface{}, raws ...bool) string

func AsciiBytesToRegexpMatchedRunes

func AsciiBytesToRegexpMatchedRunes(in []byte) []rune

func AsciiBytesToRegexpMatchedString

func AsciiBytesToRegexpMatchedString(in []byte) string

func AsciiEqualFold

func AsciiEqualFold(s, t string) bool

AsciiEqualFold is strings.EqualFold, ASCII only. It reports whether s and t are equal, ASCII-case-insensitively.

func AsciiToLower

func AsciiToLower(s string) (lower string, ok bool)

asciiToLower returns the lowercase version of s if s is ASCII and printable, and whether or not it was.

func AttemptWithDelay

func AttemptWithDelay(maxIteration int, delay time.Duration, f func() error) error

func AttemptWithDelayFast

func AttemptWithDelayFast(f func() error) error

func BKDRHash

func BKDRHash(str []byte) uint32

BKDR Hash Function

func BufioReadLine

func BufioReadLine(reader *bufio.Reader) ([]byte, error)

func BufioReadLineString

func BufioReadLineString(reader *bufio.Reader) (string, error)

func ByteCountBinary

func ByteCountBinary(b int64) string

func ByteCountDecimal

func ByteCountDecimal(b int64) string

func ByteSize

func ByteSize(bytes uint64) string

ByteSize returns a human-readable byte string of the form 10M, 12.5K, and so forth. The following units are available:

E: Exabyte
P: Petabyte
T: Terabyte
G: Gigabyte
M: Megabyte
K: Kilobyte
B: Byte

The unit that results in the smallest number greater than or equal to 1 is always chosen.

func BytesClone

func BytesClone(raw []byte) (newBytes []byte)

func CacheFunc

func CacheFunc[T any](duration time.Duration, f func() (T, error)) func() (T, error)

func CalcMd5

func CalcMd5(items ...interface{}) string

func CalcSSDeepStability

func CalcSSDeepStability(req ...[]byte) (float64, error)

CalcSSDeepStability 使用模糊哈希算法计算多段文本之间的相似度,返回相似度与错误。传入的文本应该为大文本,即长度大于 30 kb。 Example: ``` p, err = str.CalcSSDeepStability(str.RandStr(100000), str.RandStr(100000)) ```

func CalcSha1

func CalcSha1(items ...interface{}) string

func CalcSha1WithSuffix

func CalcSha1WithSuffix(items []interface{}, suffix string) string

func CalcSha256

func CalcSha256(items ...interface{}) string

func CalcSimHashStability

func CalcSimHashStability(req ...[]byte) (float64, error)

CalcSimHashStability 使用 SimHash 算法计算多段文本之间的相似度,返回相似度与错误。 Example: ``` p, err = str.CalcSimHashStability("hello", "hello world") // p = 0.96484375 ```

func CalcSimilarity

func CalcSimilarity(raw ...[]byte) float64

CalcSimilarity 计算多段文本之间的相似度,根据最长的文本长度选择不同的算法 如果最长的文本长度小于等于 2000,使用文本子串匹配算法 如果最短的文本长度大于等于 30000,使用模糊哈希算法 如果上述算法出现错误,则使用 SimHash 算法 Example: ``` str.CalcSimilarity("hello", "hello world") // 0.625 ```

func CalcTextSubStringStability

func CalcTextSubStringStability(raw ...[]byte) (float64, error)

CalcTextMaxSubStrStability 使用文本子串匹配算法计算多段文本之间的相似度,返回相似度与错误 Example: ``` p, err = str.CalcTextMaxSubStrStability("hello", "hello world") // p = 0.625 ```

func CallWithCtx

func CallWithCtx(ctx context.Context, cb func()) error

func CallWithTimeout

func CallWithTimeout(timeout float64, cb func()) error

func ChanStringToSlice

func ChanStringToSlice(c chan string) (result []string)

func ConcatPorts

func ConcatPorts(ports []int) string

func ConcurrentCopyDirectory

func ConcurrentCopyDirectory(source string, destination string, threads int, isMove bool) error

func ConnExpect

func ConnExpect(c net.Conn, timeout time.Duration, callback func([]byte) bool) (bool, error)

func ContainsAll

func ContainsAll[T comparable](s []T, vals ...T) bool

func ContainsAny

func ContainsAny[T comparable](s []T, vals ...T) bool

func ContainsJSON

func ContainsJSON(raw string) (string, bool)

func ConvertTextFileToYakFuzztagByPath

func ConvertTextFileToYakFuzztagByPath(file_bin_path string) (string, error)

func ConvertToStringSlice

func ConvertToStringSlice(raw ...interface{}) (r []string)

func CopyBytes

func CopyBytes(rsp []byte) []byte

func CopyDirectory

func CopyDirectory(source string, destination string, isMove bool) error

func CopyDirectoryEx

func CopyDirectoryEx(source string,
	destination string,
	isMove bool,
	fs fi.FileSystem,
) error

func CopyFile

func CopyFile(source, destination string) error

func CopyFileEx

func CopyFileEx(
	source string,
	destination string,
	fs fi.FileSystem,
) error

func CopyMapInterface

func CopyMapInterface(i map[string]interface{}) map[string]interface{}

func CopyMapShallow

func CopyMapShallow[K comparable, V any](originalMap map[K]V) map[K]V

func DataVerbose

func DataVerbose(i interface{}) string

func DatePretty

func DatePretty() string

func DatetimePretty

func DatetimePretty() string

func DatetimePretty2

func DatetimePretty2() string

func Debug

func Debug(f func())

func DebugMockEchoWs

func DebugMockEchoWs(point string) (string, int)

func DebugMockGMHTTP

func DebugMockGMHTTP(ctx context.Context, handler func(req []byte) []byte) (string, int)

func DebugMockHTTP

func DebugMockHTTP(rsp []byte) (string, int)

func DebugMockHTTP2

func DebugMockHTTP2(ctx context.Context, handler func(req []byte) []byte) (string, int)

func DebugMockHTTPEx

func DebugMockHTTPEx(handle func(req []byte) []byte) (string, int)

func DebugMockHTTPExContext

func DebugMockHTTPExContext(ctx context.Context, handle func(req []byte) []byte) (string, int)

func DebugMockHTTPHandlerFunc

func DebugMockHTTPHandlerFunc(handlerFunc http.HandlerFunc) (string, int)

func DebugMockHTTPHandlerFuncContext

func DebugMockHTTPHandlerFuncContext(ctx context.Context, handlerFunc http.HandlerFunc) (string, int)

func DebugMockHTTPKeepAliveEx

func DebugMockHTTPKeepAliveEx(handle func(req []byte) []byte) (string, int)

func DebugMockHTTPS

func DebugMockHTTPS(rsp []byte) (string, int)

func DebugMockHTTPSEx

func DebugMockHTTPSEx(handle func(req []byte) []byte) (string, int)

func DebugMockHTTPSKeepAliveEx

func DebugMockHTTPSKeepAliveEx(handle func(req []byte) []byte) (string, int)

func DebugMockHTTPServerWithContext

func DebugMockHTTPServerWithContext(ctx context.Context, https, h2, gmtlsFlag, onlyGmtls, keepAlive bool, handle func([]byte) []byte) (string, int)

func DebugMockHTTPServerWithContextWithAddress

func DebugMockHTTPServerWithContextWithAddress(ctx context.Context, addr string, https, h2, gmtlsFlag, onlyGmtls, keepAlive bool, checkServerName bool, handle func([]byte) []byte) (string, int)

func DebugMockHTTPWithTimeout

func DebugMockHTTPWithTimeout(du time.Duration, rsp []byte) (string, int)

func DebugMockOnlyGMHTTP

func DebugMockOnlyGMHTTP(ctx context.Context, handler func(req []byte) []byte) (string, int)

func DebugMockTCP

func DebugMockTCP(rsp []byte) (string, int)

func DebugMockTCPEx

func DebugMockTCPEx(handleFunc handleTCPFunc) (string, int)

func DebugMockTCPHandlerFuncContext

func DebugMockTCPHandlerFuncContext(ctx context.Context, handlerFunc handleTCPFunc) (string, int)

func DebugMockWs

func DebugMockWs(handler func(conn *websocket.Conn)) (string, int)

func DomainToURLFilter

func DomainToURLFilter(domain string) (*regexp.Regexp, error)

func DownloadFile

func DownloadFile(client *http.Client, u string, localFile string, every1s ...func(float64)) error

func DumpFileWithTextAndFiles

func DumpFileWithTextAndFiles(raw string, divider string, files ...string) (string, error)

func DumpHTTPRequest

func DumpHTTPRequest(req *http.Request, loadBody bool) ([]byte, error)

DumpHTTPRequest dumps http request to bytes **NO NOT HANDLE SMUGGLE HERE!** Transfer-Encoding is handled vai req.TransferEncoding / req.Header["Transfer-Encoding"] Content-Length is handled vai req.ContentLength / req.Header["Content-Length"] if Transfer-Encoding existed, check body chunked? if not, encode it if Transfer-Encoding and Content-Length existed at same time, use transfer-encoding

func DumpHTTPResponse

func DumpHTTPResponse(rsp *http.Response, loadBody bool, wr ...io.Writer) ([]byte, error)

DumpHTTPResponse dumps http response to bytes if loadBody is true, it will load body to memory

transfer-encoding is a special header

func DumpHostFileWithTextAndFiles

func DumpHostFileWithTextAndFiles(raw string, divider string, files ...string) (string, error)

func EnableDebug

func EnableDebug()

func Error

func Error(i interface{}) error

func ErrorStack

func ErrorStack(origin any) (err error)

ErrorStack 捕获 panic 并返回 error

func Errorf

func Errorf(format string, args ...interface{}) error

func EscapeInvalidUTF8Byte

func EscapeInvalidUTF8Byte(s []byte) string

func ExportAppConfigToMap

func ExportAppConfigToMap(ins any) (map[string]string, error)

func ExtractFaviconURL

func ExtractFaviconURL(siteURL string, content []byte) (string, error)

ExtractFaviconURL will receive a site url and html content return the favicon url Example:

http.ExtractFaviconURL("https://www.baidu.com", []byte(`<link rel="shortcut icon" href="/favicon.ico" type="image/x-icon">`))
http.ExtractFaviconURL("https://www.baidu.com", []byte(`<link rel="icon" href="/favicon.ico" type="image/x-icon">`))
http.ExtractFaviconURL("https://www.baidu.com", []byte(`<link rel="icon" href="/favicon.png" type="image/png">`))

func ExtractHost

func ExtractHost(raw string) string

ExtractHost 尝试从字符串中解析出host和port,并返回host Example: ``` str.ExtractHost("127.0.0.1:8888") // 127.0.0.1 str.ExtractHost("https://example.com") // example.com ```

func ExtractHostPort

func ExtractHostPort(raw string) string

ExtractHostPort 尝试从字符串中解析出host和port,并返回host:port Example: ``` str.ExtractHostPort("https://127.0.0.1:8888") // 127.0.0.1:8888 str.ExtractHostPort("https://baidu.com") // 127.0.0.1:443 ```

func ExtractMapValueBool

func ExtractMapValueBool(m any, key string) bool

func ExtractMapValueGeneralMap

func ExtractMapValueGeneralMap(m any, key string) map[string]any

func ExtractMapValueInt

func ExtractMapValueInt(m any, key string) int

func ExtractMapValueRaw

func ExtractMapValueRaw(m any, key string) any

func ExtractMapValueString

func ExtractMapValueString(m any, key string) string

func ExtractRawPath

func ExtractRawPath(target string) string

func ExtractStrContextByKeyword

func ExtractStrContextByKeyword(raw string, res []string) []string

ExtractStrContext 从字符串raw中提取一组关键字res上下文的内容,上下文的长度是512个字符确定。 Example: ``` str.ExtractStrContext("hello yak", ["hello"]) // ["hello yak"] ```

func ExtractTitleFromHTMLTitle

func ExtractTitleFromHTMLTitle(s string, defaultValue string) string

func FileLineReader

func FileLineReader(file string) (chan []byte, error)

func FileLineReaderWithContext

func FileLineReaderWithContext(file string, ctx context.Context) (chan []byte, error)

func FixForParseIP

func FixForParseIP(host string) string

func FixHTTPRequestForGolangNativeHTTPClient

func FixHTTPRequestForGolangNativeHTTPClient(req *http.Request)

FixHTTPRequestForGolangNativeHTTPClient utils.Read/DumpRequest is working as pair... if u want to use transport(golang native) do this `FixHTTPRequestForGolangNativeHTTPClient` helps because golang native transport will encode chunked body again

func FixHTTPRequestForHTTPDo

func FixHTTPRequestForHTTPDo(r *http.Request) (*http.Request, error)

func FixHTTPRequestForHTTPDoWithHttps

func FixHTTPRequestForHTTPDoWithHttps(r *http.Request, isHttps bool) (*http.Request, error)

func FixHTTPResponseForGolangNativeHTTPClient

func FixHTTPResponseForGolangNativeHTTPClient(ins *http.Response)

func FixJsonRawBytes

func FixJsonRawBytes(rawBytes []byte) []byte

func FloatSecondDuration

func FloatSecondDuration(f float64) time.Duration

func FlushWriter

func FlushWriter(writer io.Writer)

func Format

func Format(raw string, data map[string]string) string

func GetAllFiles

func GetAllFiles(path string) (fileNames []string, err error)

func GetCClassByIPv4

func GetCClassByIPv4(s string) (network string, err error)

IPv4ToCClassNetwork 尝试从一个 IPv4 地址中获取 C 类网络地址,并返回错误 Example: ``` network, err = str.IPv4ToCClassNetwork("192.168.0.1") // network = "192.168.0.0/24", err = nil ```

func GetCachedLog

func GetCachedLog() (res []string)

func GetConnectedToHostPortFromHTTPRequest

func GetConnectedToHostPortFromHTTPRequest(t *http.Request) (string, error)

func GetCurrentDate

func GetCurrentDate() (time.Time, error)

func GetCurrentWeekMonday

func GetCurrentWeekMonday() (time.Time, error)

func GetDatabaseCacheStatus

func GetDatabaseCacheStatus[K comparable, T any](c *DataBaseCacheWithKey[K, T], key K) databaseCacheItemStatus

func GetDate

func GetDate(t time.Time) (time.Time, error)

func GetDefaultGMTLSConfig

func GetDefaultGMTLSConfig(i float64) *gmtls.Config

func GetDefaultOnlyGMTLSConfig

func GetDefaultOnlyGMTLSConfig(i float64) *gmtls.Config

func GetDefaultTLSConfig

func GetDefaultTLSConfig(i float64) *tls.Config

func GetExecutableFromEnv

func GetExecutableFromEnv(cmd string) (string, error)

func GetFileAbsDir

func GetFileAbsDir(filePath string) (string, error)

func GetFileAbsPath

func GetFileAbsPath(filePath string) (string, error)

func GetFileMd5

func GetFileMd5(filepath string) string

func GetFileModTime

func GetFileModTime(path string) int64

func GetFirstExcludedHighPort

func GetFirstExcludedHighPort(excluded ...string) int

func GetFirstExistedExecutablePath

func GetFirstExistedExecutablePath(paths ...string) string

func GetFirstExistedFile

func GetFirstExistedFile(paths ...string) string

func GetFirstExistedFileE

func GetFirstExistedFileE(paths ...string) (string, error)

func GetFirstExistedPath

func GetFirstExistedPath(paths ...string) string

func GetFirstExistedPathE

func GetFirstExistedPathE(paths ...string) (string, error)

func GetHTTPHeader

func GetHTTPHeader(headers http.Header, key string) string

func GetHomeDir

func GetHomeDir() (string, error)

func GetHomeDirDefault

func GetHomeDirDefault(d string) string

func GetLastElement

func GetLastElement[T any](list []T) T

func GetLatestFile

func GetLatestFile(dir, suffix string) (filename string, err error)

func GetLocalIPAddress

func GetLocalIPAddress() string

func GetLocalIPAddressViaIface

func GetLocalIPAddressViaIface() string

func GetMachineCode

func GetMachineCode() string

func GetNExcludeExcludeHighPort

func GetNExcludeExcludeHighPort(n int, excluded ...string) []int

func GetRandomAvailableTCPPort

func GetRandomAvailableTCPPort() int

func GetRandomAvailableUDPPort

func GetRandomAvailableUDPPort() int

func GetRandomIPAddress

func GetRandomIPAddress() string

func GetRandomLocalAddr

func GetRandomLocalAddr() string

func GetRangeAvailableTCPPort

func GetRangeAvailableTCPPort(startPort, endPort, maxRetries int) (int, error)

func GetSameSubStrings

func GetSameSubStrings(raw ...string) []string

func GetSameSubStringsRunes

func GetSameSubStringsRunes(text1, text2 []rune) [][]rune

func GetSortedMapKeys

func GetSortedMapKeys[K Ordered, V any](m map[K]V) []K

func GetSystemDnsServers

func GetSystemDnsServers() ([]string, error)

func GetSystemMachineCode

func GetSystemMachineCode() (_ string, err error)

func GetSystemNameServerList

func GetSystemNameServerList() ([]string, error)

func GetUnexportedField

func GetUnexportedField(field reflect.Value) interface{}

func GetWeekStartMonday

func GetWeekStartMonday(t time.Time) (time.Time, error)

func GetWeekStartSunday

func GetWeekStartSunday() (time.Time, error)

func GormTransaction

func GormTransaction(db *gorm.DB, callback func(tx *gorm.DB) error) (err error)

func GormTransactionReturnDb

func GormTransactionReturnDb(db *gorm.DB, callback func(tx *gorm.DB)) (tx *gorm.DB)

func GzipCompress

func GzipCompress(i interface{}) ([]byte, error)

func GzipDeCompress

func GzipDeCompress(ret []byte) ([]byte, error)

func HTTPFrameParser

func HTTPFrameParser(raw io.Reader) ([][2]string, [][2]string, io.Reader, error)

func HTTPPacketIsLargerThanMaxContentLength

func HTTPPacketIsLargerThanMaxContentLength(res interface{}, maxLength int) bool

func HandleStdout

func HandleStdout(ctx context.Context, handle func(string)) error

func HandleStdoutBackgroundForTest

func HandleStdoutBackgroundForTest(handle func(string)) (func(), func(), error)

func HostContains

func HostContains(rule string, target string) bool

func HostPort

func HostPort(host string, port interface{}) string

HostPort 将 host 和 port 拼接成 host:port 的形式 Example: ``` str.HostPort("yaklang.com", 443) // yaklang.com:443 ```

func HttpDumpWithBody

func HttpDumpWithBody(i interface{}, body bool) ([]byte, error)

func HttpShow

func HttpShow(i interface{}) []byte

func IContains

func IContains(s, sub string) bool

func IHasPrefix

func IHasPrefix(s, sub string) bool

func IOCopy

func IOCopy(dst io.Writer, src io.Reader, buf []byte) (written int64, err error)

func IPv4ToCClassNetwork

func IPv4ToCClassNetwork(s string) (string, error)

func IPv4ToUint32

func IPv4ToUint32(ip net.IP) (uint32, error)

func IPv4ToUint64

func IPv4ToUint64(ip string) (int64, error)

func IStringContainsAnyOfSubString

func IStringContainsAnyOfSubString(s string, subs []string) bool

func ImportAppConfigToStruct

func ImportAppConfigToStruct(template any, data map[string]string) (err error)

func InDebugMode

func InDebugMode() bool

func InGithubActions

func InGithubActions() bool

func InTestcase

func InTestcase() bool

func IncludeExcludeChecker

func IncludeExcludeChecker(includes, excludes []string, target string) (passed bool)

func IndexAllSubstrings

func IndexAllSubstrings(s string, patterns ...string) (result [][2]int)

IndexAllSubstrings 只遍历一次查找所有子串位置 返回值是一个二维数组,每个元素是一个[2]int类型匹配结果,其中第一个元素是规则index,第二个元素是索引位置

func InetAtoN

func InetAtoN(ip net.IP) int64

func InetNtoA

func InetNtoA(ip int64) net.IP

func InitialCapitalizationEachWords

func InitialCapitalizationEachWords(str string) string

每个单词首字母大写

func InsertSliceItem

func InsertSliceItem[T comparable](slices []T, e T, index int) []T

func Int64SliceToIntSlice

func Int64SliceToIntSlice(i []int64) []int

func IntArrayContains

func IntArrayContains(array []int, element int) bool

func IntLargerZeroOr

func IntLargerZeroOr(s ...int) int

func IntSliceToInt64Slice

func IntSliceToInt64Slice(i []int) []int64

func InterfaceToBoolean

func InterfaceToBoolean(i any) bool

func InterfaceToBytes

func InterfaceToBytes(i interface{}) (result []byte)

func InterfaceToBytesSlice

func InterfaceToBytesSlice(i interface{}) [][]byte

func InterfaceToGeneralMap

func InterfaceToGeneralMap(params interface{}) (finalResult map[string]interface{})

func InterfaceToInt

func InterfaceToInt(i any) int

func InterfaceToJsonString

func InterfaceToJsonString(i interface{}) string

func InterfaceToMap

func InterfaceToMap(i interface{}) map[string][]string

func InterfaceToMapInterface

func InterfaceToMapInterface(i interface{}) map[string]interface{}

func InterfaceToMapInterfaceE

func InterfaceToMapInterfaceE(i interface{}) (map[string]interface{}, error)

func InterfaceToQuotedString

func InterfaceToQuotedString(i interface{}) string

func InterfaceToSliceInterface

func InterfaceToSliceInterface(i interface{}) []any

func InterfaceToSliceInterfaceE

func InterfaceToSliceInterfaceE(i interface{}) ([]any, error)

func InterfaceToString

func InterfaceToString(i interface{}) string

func InterfaceToStringSlice

func InterfaceToStringSlice(i interface{}) (result []string)

ToStringSlice 将任意类型的数据转换为字符串切片 Example: ``` str.ToStringSlice("hello") // ["hello"] str.ToStringSlice([1, 2]) // ["1", "2"] ```

func IsASCIIPrint

func IsASCIIPrint(s string) bool

isASCIIPrint returns whether s is ASCII and printable according to https://tools.ietf.org/html/rfc20#section-4.2.

func IsBase64

func IsBase64(s string) bool

func IsCommonHTTPRequestMethod

func IsCommonHTTPRequestMethod(i any) bool

func IsConnectResetError

func IsConnectResetError(err error) bool

func IsDir

func IsDir(path string) bool

func IsErrorNetOpTimeout

func IsErrorNetOpTimeout(err error) bool

func IsFile

func IsFile(path string) bool

func IsFloat

func IsFloat(v interface{}) bool

func IsGzip

func IsGzip(raw []byte) bool

func IsGzipBytes

func IsGzipBytes(i interface{}) bool

func IsHttpOrHttpsUrl

func IsHttpOrHttpsUrl(raw string) bool

func IsIPv4

func IsIPv4(raw string) bool

IsIPv4 判断字符串是否是 IPv4 地址 Example: ``` str.IsIPv4("::1") // false str.IsIPv4("127.0.0.1") // true ```

func IsIPv6

func IsIPv6(raw string) bool

IsIPv6 判断字符串是否是 IPv6 地址 Example: ``` str.IsIPv6("::1") // true str.IsIPv6("127.0.0.1") // false ```

func IsImage

func IsImage(i []byte) bool

func IsInt

func IsInt(v interface{}) bool

func IsJSON

func IsJSON(raw string) (string, bool)

func IsLinux

func IsLinux() bool

func IsLoopback

func IsLoopback(t string) bool

func IsMac

func IsMac() bool

func IsMap

func IsMap(input any) bool

func IsNil

func IsNil(input any) bool

func IsPlainText

func IsPlainText(raw []byte) bool

func IsPortAvailable

func IsPortAvailable(host string, p int) bool

func IsPortAvailableWithUDP

func IsPortAvailableWithUDP(host string, p int) bool

func IsPrivateIP

func IsPrivateIP(ip net.IP) bool

func IsProtobuf

func IsProtobuf(raw []byte) bool

func IsStrongPassword

func IsStrongPassword(s string) bool

IsStrongPassword 判断字符串是否为强密码,强密码的定义为:长度大于8,同时包含特殊字符、小写字母、大写字母、数字 Example: ``` str.IsStrongPassword("12345678") // false str.IsStrongPassword("12345678a") // false str.IsStrongPassword("12345678aA") // false str.IsStrongPassword("12345678aA!") // true ```

func IsSubPath

func IsSubPath(sub, parent string) bool

func IsTCPPortAvailable

func IsTCPPortAvailable(p int) bool

func IsTCPPortAvailableWithLoopback

func IsTCPPortAvailableWithLoopback(p int) bool

func IsTCPPortOpen

func IsTCPPortOpen(host string, p int) bool

func IsUDPPortAvailable

func IsUDPPortAvailable(p int) bool

func IsUDPPortAvailableWithLoopback

func IsUDPPortAvailableWithLoopback(p int) bool

func IsValidBool

func IsValidBool(raw string) bool

func IsValidCIDR

func IsValidCIDR(raw string) bool

func IsValidDomain

func IsValidDomain(raw string) bool

func IsValidFloat

func IsValidFloat(raw string) bool

func IsValidHost

func IsValidHost(raw string) bool

func IsValidHostsRange

func IsValidHostsRange(raw string) bool

func IsValidInteger

func IsValidInteger(raw string) bool

func IsValidPortsRange

func IsValidPortsRange(ports string) bool

func IsWebsocketUrl

func IsWebsocketUrl(raw string) bool

func IsWindows

func IsWindows() bool

func JavaTimeFormatter

func JavaTimeFormatter(t time.Time, formatter string) string

func JitterBackoff

func JitterBackoff(min, max time.Duration, attempt int) time.Duration

Return capped exponential backoff with jitter http://www.awsarchitectureblog.com/2015/03/backoff.html

func JoinErrors

func JoinErrors(errs ...error) error

func Jsonify

func Jsonify(i interface{}) []byte

func LastLine

func LastLine(s []byte) []byte

func LoopEvery1sBreakUntil

func LoopEvery1sBreakUntil(until func() bool)

func MIMEGlobRuleCheck

func MIMEGlobRuleCheck(target string, rule string) bool

func MapGetBool

func MapGetBool(m map[string]interface{}, key string) bool

func MapGetBoolOr

func MapGetBoolOr(m map[string]interface{}, key string, value bool) bool

func MapGetFirstRaw

func MapGetFirstRaw(m map[string]interface{}, key ...string) interface{}

func MapGetFloat32

func MapGetFloat32(m map[string]interface{}, key string) float32

func MapGetFloat32Or

func MapGetFloat32Or(m map[string]interface{}, key string, value float32) float32

func MapGetFloat64

func MapGetFloat64(m map[string]interface{}, key string) float64

func MapGetFloat64Or

func MapGetFloat64Or(m map[string]interface{}, key string, value float64) float64

func MapGetInt

func MapGetInt(m map[string]interface{}, key string) int

func MapGetInt64

func MapGetInt64(m map[string]interface{}, key string) int64

func MapGetInt64Or

func MapGetInt64Or(m map[string]interface{}, key string, value int64) int64

func MapGetIntEx

func MapGetIntEx(m map[string]interface{}, key ...string) int

func MapGetIntOr

func MapGetIntOr(m map[string]interface{}, key string, value int) int

func MapGetMapRaw

func MapGetMapRaw(m map[string]interface{}, key string) map[string]interface{}

func MapGetMapRawOr

func MapGetMapRawOr(m map[string]interface{}, key string, value map[string]interface{}) map[string]interface{}

func MapGetRaw

func MapGetRaw(m map[string]interface{}, key string) interface{}

func MapGetRawOr

func MapGetRawOr(m map[string]interface{}, key string, value interface{}) interface{}

func MapGetString

func MapGetString(m map[string]interface{}, key string) string

func MapGetString2

func MapGetString2(m map[string]string, key string) string

func MapGetStringByManyFields

func MapGetStringByManyFields(m map[string]interface{}, key ...string) string

func MapGetStringOr

func MapGetStringOr(m map[string]interface{}, key string, value string) string

func MapGetStringOr2

func MapGetStringOr2(m map[string]string, key string, value string) string

func MapGetStringSlice

func MapGetStringSlice(m map[string]interface{}, key string) []string

func MapQueryToString

func MapQueryToString(values map[string][]string) string

map[string][]string to query

func MapStringGet

func MapStringGet(m map[string]string, key string) string

func MapStringGetOr

func MapStringGetOr(m map[string]string, key string, value string) string

func MapToStruct

func MapToStruct(input map[string]interface{}, output interface{}) error

func MarshalHTTPRequest

func MarshalHTTPRequest(req *http.Request) ([]byte, error)

func MarshalIdempotent

func MarshalIdempotent(v interface{}) ([]byte, error)

func MatchAllOfGlob

func MatchAllOfGlob(
	i interface{}, re ...string) bool

MatchAllOfGlob 尝试将 i 转换为字符串,然后使用 glob 匹配模式匹配,如果所有的glob模式都匹配成功,则返回 true,否则返回 false Example: ``` str.MatchAllOfGlob("abc", "a*", "?b?", "[a-z]?c") // true ```

func MatchAllOfRegexp

func MatchAllOfRegexp(
	i interface{},
	re ...string) bool

MatchAllOfRegexp 尝试将 i 转换为字符串,然后使用正则表达式匹配,如果所有的正则表达式都匹配成功,则返回 true,否则返回 false Example: ``` str.MatchAllOfRegexp("abc", "a.+", ".?b.?", "\\w{2}c") // true ```

func MatchAllOfSubString

func MatchAllOfSubString(i interface{}, subStr ...string) bool

MatchAllOfSubString 尝试将 i 转换为字符串,然后判断所有子串 subStr 是否都存在于 i 中,如果都存在则返回 true,否则返回 false,此函数忽略大小写 Example: ``` str.MatchAllOfSubString("abc", "a", "b", "c") // true ```

func MatchAnyOfGlob

func MatchAnyOfGlob(
	i interface{}, re ...string) bool

MatchAnyOfGlob 尝试将 i 转换为字符串,然后使用 glob 匹配模式匹配,如果任意一个glob模式匹配成功,则返回 true,否则返回 false Example: ``` str.MatchAnyOfGlob("abc", "a*", "??b", "[^a-z]?c") // true ```

func MatchAnyOfRegexp

func MatchAnyOfRegexp(
	i interface{},
	re ...string) bool

MatchAnyOfRegexp 尝试将 i 转换为字符串,然后使用正则表达式匹配,如果任意一个正则表达式匹配成功,则返回 true,否则返回 false Example: ``` str.MatchAnyOfRegexp("abc", "a.+", "Ab.?", ".?bC") // true ```

func MatchAnyOfSubString

func MatchAnyOfSubString(i interface{}, subStr ...string) bool

MatchAnyOfSubString 尝试将 i 转换为字符串,然后判断是否有任意子串 subStr 存在于 i 中,如果有其中一个子串存在于 i 中则返回 true,否则返回 false,此函数忽略大小写 Example: ``` str.MatchAnyOfSubString("abc", "a", "z", "x") // true ```

func Max

func Max(x, y int) int

func MaxByte

func MaxByte(x, y byte) byte

func MaxInt64

func MaxInt64(x, y int64) int64

func MergeGeneralMap

func MergeGeneralMap(ms ...map[string]any) map[string]any

func MergeStringMap

func MergeStringMap(ms ...map[string]string) map[string]string

func MergeToMap

func MergeToMap[K comparable, V any](m map[K]V, ms ...map[K]V)

func Min

func Min(x, y int) int

func MinByte

func MinByte(x, y byte) byte

func MinInt64

func MinInt64(x, y int64) int64

func Mmh3Hash32

func Mmh3Hash32(raw []byte) string

func MustUnmarshalJson

func MustUnmarshalJson[T any](raw []byte) *T

func NeedsURLEncoding

func NeedsURLEncoding(s string) bool

func NetworkByteOrderBytesToUint16

func NetworkByteOrderBytesToUint16(r []byte) uint16

func NetworkByteOrderUint16ToBytes

func NetworkByteOrderUint16ToBytes(i any) []byte

func NetworkByteOrderUint32ToBytes

func NetworkByteOrderUint32ToBytes(i any) []byte

func NetworkByteOrderUint64ToBytes

func NetworkByteOrderUint64ToBytes(i any) []byte

func NetworkByteOrderUint8ToBytes

func NetworkByteOrderUint8ToBytes(i any) []byte

func NewBlockParser

func NewBlockParser(reader io.Reader) *blockParser

func NewBufPipe

func NewBufPipe(buf []byte) (*PipeReader, *PipeWriter)

NewBufPipe creates a synchronous pipe using buf as its initial contents. It can be used to connect code expecting an io.Reader with code expecting an io.Writer.

Unlike io.Pipe, writes never block because the internal buffer has variable size. Reads block only when the buffer is empty.

It is safe to call Read and Write in parallel with each other or with Close. Parallel calls to Read and parallel calls to Write are also safe: the individual calls will be gated sequentially.

The new pipe takes ownership of buf, and the caller should not use buf after this call. New is intended to prepare a PipeReader to read existing data. It can also be used to set the initial size of the internal buffer for writing. To do that, buf should have the desired capacity but a length of zero.

func NewDefaultGMTLSConfig

func NewDefaultGMTLSConfig() *gmtls.Config

func NewDefaultHTTPClient

func NewDefaultHTTPClient() *http.Client

func NewDefaultHTTPClientWithProxy

func NewDefaultHTTPClientWithProxy(proxy string) *http.Client

func NewDefaultTLSClient

func NewDefaultTLSClient(conn net.Conn) *tls.Conn

func NewDefaultTLSConfig

func NewDefaultTLSConfig() *tls.Config

func NewDialer

func NewDialer()

func NewFileLineWriter

func NewFileLineWriter(file string, flag int, perm fs.FileMode) (*fileLineWriter, error)

func NewNetConnFromReadWriter

func NewNetConnFromReadWriter()

func NewSignalChannel

func NewSignalChannel(targetSignal ...os.Signal) chan os.Signal

func NewThrottle

func NewThrottle(wait float64) func(f func())

func OpenTempFile

func OpenTempFile(s string) (*os.File, error)

func ParseAppTag

func ParseAppTag(tag string) map[string]string

func ParseAppTagToOptions

func ParseAppTagToOptions(template any, ext ...map[string]string) (configInfo []*ypb.ThirdPartyAppConfigItemTemplate, err error)

func ParseCStyleBinaryRawToBytes

func ParseCStyleBinaryRawToBytes(raw []byte) []byte

func ParseHTTPRequestLine

func ParseHTTPRequestLine(line string) (method, requestURI, proto string, ok bool)

ParseHTTPRequestLine parses "GET /foo HTTP/1.1" into its three parts.

func ParseHTTPResponseLine

func ParseHTTPResponseLine(line string) (string, int, string, bool)

ParseHTTPResponseLine parses `HTTP/1.1 200 OK` into its ports

func ParseHostToAddrString

func ParseHostToAddrString(host string) string

func ParseIPNetToRange

func ParseIPNetToRange(n *net.IPNet) (int64, int64, error)

func ParseLines

func ParseLines(raw string) chan string

func ParsePortToProtoPort

func ParsePortToProtoPort(port int) (string, int)

func ParseStringToGeneralMap

func ParseStringToGeneralMap(i any) map[string]any

func ParseStringToHostPort

func ParseStringToHostPort(raw string) (host string, port int, err error)

ParseStringToHostPort 尝试从字符串中解析出host和port,并与错误一起返回 Example: ``` host, port, err = str.ParseStringToHostPort("127.0.0.1:8888") // host = "127.0.0.1", port = 8888, err = nil host, port, err = str.ParseStringToHostPort("https://example.com") // host = "example.com", port = 443, err = nil host, port, err = str.ParseStringToHostPort("Hello Yak") // host = "", port = 0, err = error("unknown port for [Hello Yak]") ```

func ParseStringToHosts

func ParseStringToHosts(raw string) []string

ParseStringToHosts 将字符串解析成 Host 列表, Host 可以以逗号、换行分隔,并且会解析 CIDR 网段 Example: ``` str.ParseStringToHosts("192.168.0.1/32,127.0.0.1") // ["192.168.0.1", "127.0.0.1"] ```

func ParseStringToHostsWithCallback

func ParseStringToHostsWithCallback(raw string, callback func(string) bool)

func ParseStringToHttpsAndHostname

func ParseStringToHttpsAndHostname(res string) (bool, string)

func ParseStringToLines

func ParseStringToLines(raw string) []string

ParseStringToLines 将字符串按换行符(\n)分割成字符串数组,并去除BOM头和空行 Example: ``` str.ParseStringToLines("Hello World\nHello Yak") // ["Hello World", "Hello Yak"] ```

func ParseStringToPorts

func ParseStringToPorts(ports string) []int

ParseStringToPorts 将字符串解析成 Port 列表, Port 可以以逗号分隔,并且会解析-分隔的范围 Example: ``` str.ParseStringToPorts("10086-10088,23333") // [10086, 10087, 10088, 23333] ```

func ParseStringToRawLines

func ParseStringToRawLines(raw string) []string

func ParseStringToUrl

func ParseStringToUrl(s string) *url.URL

func ParseStringToUrlParams

func ParseStringToUrlParams(i interface{}) string

func ParseStringToUrls

func ParseStringToUrls(targets ...string) []string

ParseStringToUrls 尝试从给定的字符串(ip,域名)中解析出 URL 列表,补全协议和端口 Example: ``` str.ParseStringToUrls("yaklang.com:443", "https://yaklang.io") // [https://yaklang.com, https://yaklang.io] ```

func ParseStringToUrlsWith3W

func ParseStringToUrlsWith3W(sub ...string) []string

ParseStringToUrlsWith3W 尝试从给定的字符串(ip,域名)中解析出 URL 列表,补全协议和端口,还会补全域名前的 www 前缀 Example: ``` str.ParseStringToUrlsWith3W("yaklang.com:443", "https://yaklang.io") // [https://yaklang.com, https://www.yaklang.com, https://yaklang.io, https://www.yaklang.io] ```

func ParseStringToVisible

func ParseStringToVisible(raw interface{}) string

func ParseStringUrlToUrlInstance

func ParseStringUrlToUrlInstance(s string) (*url.URL, error)

ParseStringUrlToUrlInstance 将字符串 url 解析为 URL 结构体并返回错误 Example: ``` str.ParseStringUrlToUrlInstance("https://yaklang.com/abc?a=1") ```

func ParseStringUrlToWebsiteRootPath

func ParseStringUrlToWebsiteRootPath(url string) (newURL string)

ParseStringUrlToWebsiteRootPath 将字符串 url 解析为其根路径的URL Example: ``` str.ParseStringUrlToWebsiteRootPath("https://yaklang.com/abc?a=1") // https://yaklang.com/ ```

func PathExists

func PathExists(path string) (bool, error)

func PrettifyJoin

func PrettifyJoin(sep string, s ...string) string

func PrettifyListFromStringSplitEx

func PrettifyListFromStringSplitEx(Raw string, sep ...string) (targets []string)

PrettifyListFromStringSplitEx split string using given sep if no sep given sep = []string{",", "|"}

func PrettifyListFromStringSplited

func PrettifyListFromStringSplited(Raw string, sep string) (targets []string)

SplitAndTrim 将字符串s按照sep分割成字符串切片,并且去除每个字符串的前后空白字符 Example: ``` str.SplitAndTrim(" hello yak ", " ") // ["hello", "yak"] ```

func PrettifyShrinkJoin

func PrettifyShrinkJoin(sep string, s ...string) string

func PrintCurrentGoroutineRuntimeStack

func PrintCurrentGoroutineRuntimeStack()

func ProtoHostPort

func ProtoHostPort(proto string, host string, port int) string

func QuoteCSV

func QuoteCSV(s string) string

func RandAlphaNumStringBytes

func RandAlphaNumStringBytes(n int) string

func RandBytes

func RandBytes(n int) []byte

func RandChoice

func RandChoice(a ...string) string

func RandNumberStringBytes

func RandNumberStringBytes(n int) string

func RandSample

func RandSample(n int, material ...string) string

func RandSampleInRange

func RandSampleInRange(minLen, maxLen int, material ...string) string

func RandSecret

func RandSecret(n int) string

RandSecret 返回在所有可见ascii字符表中随机挑选 n 个字符组成的密码字符串,这个密码经过str.IsStrongPassword验证,即为强密码 Example: ``` str.RandSecret(10) ```

func RandStringBytes

func RandStringBytes(n int) string

RandStringBytes 返回在大小写字母表中随机挑选 n 个字符组成的字符串 Example: ``` str.RandStr(10) ```

func ReadConnUntil

func ReadConnUntil(conn net.Conn, timeout time.Duration, sep ...byte) ([]byte, error)

func ReadConnWithTimeout

func ReadConnWithTimeout(r net.Conn, timeout time.Duration) ([]byte, error)

func ReadDirsRecursivelyCallback

func ReadDirsRecursivelyCallback(p string, i func(info *FileInfo) bool) error

func ReadHTTPRequestFromBufioReader

func ReadHTTPRequestFromBufioReader(reader *bufio.Reader) (*http.Request, error)

func ReadHTTPRequestFromBufioReaderOnFirstLine

func ReadHTTPRequestFromBufioReaderOnFirstLine(reader *bufio.Reader, h func(string)) (*http.Request, error)

func ReadHTTPRequestFromBytes

func ReadHTTPRequestFromBytes(raw []byte) (*http.Request, error)

func ReadHTTPResponseFromBufioReader

func ReadHTTPResponseFromBufioReader(reader io.Reader, req *http.Request) (*http.Response, error)

func ReadHTTPResponseFromBufioReaderConn

func ReadHTTPResponseFromBufioReaderConn(reader io.Reader, conn net.Conn, req *http.Request) (*http.Response, error)

func ReadHTTPResponseFromBytes

func ReadHTTPResponseFromBytes(raw []byte, req *http.Request) (*http.Response, error)

func ReadLine

func ReadLine(reader io.Reader) ([]byte, error)

func ReadLineEx

func ReadLineEx(reader io.Reader) (string, int64, error)

func ReadN

func ReadN(reader io.Reader, n int) ([]byte, error)

func ReadUntilStable

func ReadUntilStable(reader io.Reader, conn net.Conn, timeout time.Duration, stableTimeout time.Duration, sep ...byte) ([]byte, error)

ReadUntilStable is a stable reader check interval(stableTimeout) safe for conn is empty

func ReadUntilStableEx

func ReadUntilStableEx(reader io.Reader, noTimeout bool, conn net.Conn, timeout time.Duration, stableTimeout time.Duration, sep ...byte) ([]byte, error)

ReadUntilStableEx allow skip timeout, read until stop word or timeout

func ReadWithContextTickCallback

func ReadWithContextTickCallback(ctx context.Context, rc io.Reader, callback func([]byte) bool, interval time.Duration)

func ReadWithLen

func ReadWithLen(r io.Reader, length int) ([]byte, int)

func RealTimeCopy

func RealTimeCopy(dst io.Writer, src io.Reader) (int64, error)

func Regexp2Compile

func Regexp2Compile(rawRule string, opts ...int) (string, regexp2.RegexOptions, *regexp2.Regexp, error)

func RegisterDefaultTLSConfigGenerator

func RegisterDefaultTLSConfigGenerator(h func() (*tls.Config, *gmtls.Config, *gmtls.Config, *tls.Config, *gmtls.Config, []byte, []byte))

func RegisterTempFileOpener

func RegisterTempFileOpener(dialer FileOpenerType)

func RemoveBOM

func RemoveBOM(raw []byte) []byte

func RemoveBOMForString

func RemoveBOMForString(raw string) string

func RemoveRepeatStringSlice

func RemoveRepeatStringSlice(slc []string) []string

RemoveRepeat 移除字符串切片slc中的重复元素 Example: ``` str.RemoveRepeat(["hello", "yak", "hello"]) // ["hello", "yak"] ```

func RemoveRepeatStringSliceByLoop

func RemoveRepeatStringSliceByLoop(slc []string) []string

func RemoveRepeatStringSliceByMap

func RemoveRepeatStringSliceByMap(slc []string) []string

func RemoveRepeatUintSlice

func RemoveRepeatUintSlice(slc []uint) []uint

元素去重

func RemoveRepeatUintSliceByLoop

func RemoveRepeatUintSliceByLoop(slc []uint) []uint

func RemoveRepeatUintSliceByMap

func RemoveRepeatUintSliceByMap(slc []uint) []uint

func RemoveRepeatedWithStringSlice

func RemoveRepeatedWithStringSlice(slice []string) []string

func RemoveSliceItem

func RemoveSliceItem[T comparable](slice []T, s T) []T

func RemoveUnprintableChars

func RemoveUnprintableChars(raw string) string

func RemoveUnprintableCharsWithReplace

func RemoveUnprintableCharsWithReplace(raw string, handle func(i byte) string) string

func RemoveUnprintableCharsWithReplaceItem

func RemoveUnprintableCharsWithReplaceItem(raw string) string

func ReplaceLastSubString

func ReplaceLastSubString(s, sub, new string) string

func ReplaceSliceItem

func ReplaceSliceItem[T comparable](s []T, t T, to T) []T

func Retry

func Retry(times int, f func() error) error

func Retry2

func Retry2(i int, handler func() bool)

retry 对第二个参数作为函数的情况,重试N次,如果第二个参数返回值是 true,则重试,否则就结束,如果遇到错误,停止重试 Example: ``` count = 0

retry(100, () => {
   defer recover()

   count++
   if count > 3 {
       die(111)
   }
   return true
})

assert count == 4, f`${count}`

count = 0

retry(100, () => {
   defer recover()

   count++
   if count > 3 {
       return false
   }
   return true
})

assert count == 4, f`${count}`

count = 0

retry(100, () => {
   count++
})

assert count == 1, f`${count}`

count = 0

retry(100, () => {
   count++
   return true
})

assert count == 100, f`${count}` ```

func RetryWithExpBackOff

func RetryWithExpBackOff(f func() error) error

func RetryWithExpBackOffEx

func RetryWithExpBackOffEx(times int, begin int, f func() error) error

func SSDeepHash

func SSDeepHash(raw []byte) string

CalcSSDeep 计算并返回一段文本的模糊哈希值 Example: ``` str.CalcSSDeep("hello") ```

func SafeReflectStructField

func SafeReflectStructField(refV reflect.Value, field reflect.Value) reflect.Value

func SafeReflectValue

func SafeReflectValue(refV reflect.Value) reflect.Value

func SaveFile

func SaveFile(raw interface{}, filePath string) error

func SaveTempFile

func SaveTempFile(content interface{}, pattern string) (string, error)

func SetCurrentAbsPath

func SetCurrentAbsPath(path ...string)

SetCurrentAbsPath set absolute path as current project path, ff you pass a string parameter, use this string as the absolute path of the project

func SetSkipBottomFrameNum

func SetSkipBottomFrameNum(skip int)

SetSkipBottomFrameNum set the number of frames to skip from bottom, default is 2

func SetSkipFrameNum

func SetSkipFrameNum(skip int)

SetSkipFrameNum set the number of frames to skip, default is 3

func SetUnexportedField

func SetUnexportedField(field reflect.Value, value interface{})

func ShouldRemoveZeroContentLengthHeader

func ShouldRemoveZeroContentLengthHeader(s string) bool

func ShuffleInt

func ShuffleInt(slice []int)

func ShuffleString

func ShuffleString(slice []string)

func SimHash

func SimHash(raw []byte) uint64

CalcSimHash 计算并返回一段文本的 SimHash 值 Example: ``` str.CalcSimHash("hello") ```

func SimilarStr

func SimilarStr(str1 []rune, str2 []rune) (int, int, int)

return the len of longest string both in str1 and str2 and the positions in str1 and str2

func SimplifyUtf8

func SimplifyUtf8(raw []byte) ([]byte, error)

SimplifyUtf8 simplify utf8 bytes to utf8 bytes

func SliceGroup

func SliceGroup(origin []string, groupSize int) [][]string

func SnakeString

func SnakeString(s string) string

func SocketTypeUint32ToString

func SocketTypeUint32ToString(i uint32) string

func Spinlock

func Spinlock(t float64, h func() bool) error

func SplitHostsToPrivateAndPublic

func SplitHostsToPrivateAndPublic(hosts ...string) (privs, pub []string)

SplitHostsToPrivateAndPublic 将 hosts 按照私有 IP 和公有 IP 分开 Example: ``` str.SplitHostsToPrivateAndPublic("127.0.0.1", "8.8.8.8", "10.0.0.1") // ["127.0.0.1", "10.0.0.1"], ["8.8.8.8"] ```

func StableReader

func StableReader(conn io.Reader, timeout time.Duration, maxSize int) []byte

func StableReaderEx

func StableReaderEx(conn net.Conn, timeout time.Duration, maxSize int) []byte

func StandBase64

func StandBase64(braw []byte) []byte

func StarAsWildcardToRegexp

func StarAsWildcardToRegexp(prefix string, target string) (*regexp.Regexp, error)

func StartCacheLog

func StartCacheLog(ctx context.Context, n int)

func StringAfter

func StringAfter(value string, a string) string

func StringArrayContains

func StringArrayContains(array []string, element string) bool

func StringArrayFilterEmpty

func StringArrayFilterEmpty(array []string) []string

func StringArrayIndex

func StringArrayIndex(array []string, element string) int

func StringArrayMerge

func StringArrayMerge(t ...[]string) []string

func StringAsFileParams

func StringAsFileParams(target interface{}) []byte

func StringBefore

func StringBefore(value string, a string) string

func StringContainsAllOfSubString

func StringContainsAllOfSubString(s string, subs []string) bool

func StringContainsAnyOfSubString

func StringContainsAnyOfSubString(s string, subs []string) bool

StringContainsAnyOfSubString 判断字符串s中是否包含subs中的任意一个子串 Example: ``` str.StringContainsAnyOfSubString("hello yak", ["yak", "world"]) // true ```

func StringGlobArrayContains

func StringGlobArrayContains(array []string, element string, seps ...rune) bool

func StringGlobContains

func StringGlobContains(pattern string, element string, seps ...rune) bool

func StringHasPrefix

func StringHasPrefix(s string, prefix []string) bool

func StringLiteralToAny

func StringLiteralToAny(s string) any

by json unmarshal

func StringLowerAndTrimSpace

func StringLowerAndTrimSpace(raw string) string

LowerAndTrimSpace 将字符串raw转换为小写并去除前后空白字符 Example: ``` str.LowerAndTrimSpace(" Hello ") // "hello" ```

func StringOr

func StringOr(s ...string) string

func StringReverse

func StringReverse(s string) string

Reverse the string

func StringSliceContain

func StringSliceContain(s interface{}, raw string) (result bool)

StringSliceContains 判断字符串切片s中是否包含raw,对于非字符串的切片,会尝试将其元素转换为字符串再判断是否包含 Example: ``` str.StringSliceContains(["hello", "yak"], "yak") // true str.StringSliceContains([1, 2, 3], "4") // false ```

func StringSliceContainsAll

func StringSliceContainsAll(s []string, elements ...string) bool

StringSliceContainsAll 判断字符串切片s中是否完全包含elements中的所有元素,对于非字符串的切片,会尝试将其元素转换为字符串再判断是否包含 Example: ``` str.StringSliceContainsAll(["hello", "yak"], "hello", "yak") // true str.StringSliceContainsAll(["hello", "yak"], "hello", "yak", "world") // false ```

func StringSplitAndStrip

func StringSplitAndStrip(raw string, sep string) []string

func StringSubStringArrayContains

func StringSubStringArrayContains(array []string, element string) bool

func StringToAsciiBytes

func StringToAsciiBytes(s string) []byte

func TCPNoDelay

func TCPNoDelay(i net.Conn)

func TLSConfigSetCheckServerName

func TLSConfigSetCheckServerName(tlsConfig *tls.Config, host string) *tls.Config

func Tick1sWithTimeout

func Tick1sWithTimeout(timeout time.Duration, falseToBreak func() bool) (exitedByCondition bool)

func TickEvery1s

func TickEvery1s(falseToBreak func() bool)

func TickWithTimeout

func TickWithTimeout(timeout, interval time.Duration, falseToBreak func() bool) (exitedByCondition bool)

func TickWithTimeoutContext

func TickWithTimeoutContext(ctx context.Context, timeout, interval time.Duration, falseToBreak func() bool) (exitedByCondition bool)

func TimeoutContext

func TimeoutContext(d time.Duration) context.Context

func TimeoutContextSeconds

func TimeoutContextSeconds(d float64) context.Context

func TimestampMs

func TimestampMs() int64

func TimestampNano

func TimestampNano() int64

func TimestampSecond

func TimestampSecond() int64

func ToBytes

func ToBytes(s string) (uint64, error)

ToBytes parses a string formatted by ByteSize as bytes. Note binary-prefixed and SI prefixed units both mean a base-2 units KB = K = KiB = 1024 MB = M = MiB = 1024 * K GB = G = GiB = 1024 * M TB = T = TiB = 1024 * G PB = P = PiB = 1024 * T EB = E = EiB = 1024 * P

func ToLowerAndStrip

func ToLowerAndStrip(s string) string

func ToMapParams

func ToMapParams(params any) (map[string]any, error)

func ToMegabytes

func ToMegabytes(s string) (uint64, error)

ToMegabytes parses a string formatted by ByteSize as megabytes.

func ToNsServer

func ToNsServer(server string) string

func TrimFileNameExt

func TrimFileNameExt(raw string) string

func TryCloseChannel

func TryCloseChannel(i any)

func TryWriteChannel

func TryWriteChannel[T any](c chan T, data T) (ret bool)

func Uint32ToIPv4

func Uint32ToIPv4(ip uint32) net.IP

func UnquoteANSIC

func UnquoteANSIC(s string) (string, error)

UnquoteANSIC 解码ANSI-C风格的引号字符串

func UnquoteANSICWithQuote

func UnquoteANSICWithQuote(s string, quote rune) (string, error)

func UnquoteCSV

func UnquoteCSV(s string) string

func UnsafeBytesToString

func UnsafeBytesToString(b []byte) string

func UnsafeStringToBytes

func UnsafeStringToBytes(s string) []byte

func UrlJoin

func UrlJoin(origin string, paths ...string) (newURL string, err error)

UrlJoin 将 字符串 origin 和 字符串数组 paths 拼接成一个新的 URL 字符串,并返回错误 Example: ``` newURL, err = str.UrlJoin("https://yaklang.com", "asd", "qwe") // newURL = "https://yaklang.com/asd/qwe", err = nil newURL, err = str.UrlJoin("https://yaklang.com/zxc", "/asd", "qwe") // newURL = "https://yaklang.com/asd/qwe", err = nil ```

func UrlJoinParams

func UrlJoinParams(i string, params ...interface{}) string

func Utf8EncodeBySpecificLength

func Utf8EncodeBySpecificLength(str []byte, l int) []byte

Utf8EncodeBySpecificLength force encode unicode bytes to utf8 bytes by specific encode length

func VersionClean

func VersionClean(v string) string

func VersionCompare

func VersionCompare(v1, v2 string) (int, error)

VersionCompare 泛用形的版本比较,传入(p1,p2 string), p1>p2返回1,nil, p1<p2返回-1,nil, p1==p2返回0,nil, 比较失败返回 -2,err

func VersionEqual

func VersionEqual(v1, v2 string) bool

VersionEqual 使用版本比较算法比较版本 v1 与版本 v2,如果 v1 等于 v2 返回 true,否则返回 false Example: ``` str.VersionEqual("3.0", "3.0") // true str.VersionEqual("3.0", "3.0a") // false ```

func VersionGreater

func VersionGreater(v1, v2 string) bool

VersionGreater 使用版本比较算法比较版本 v1 与版本 v2,如果 v1 大于 v2 返回 true,否则返回 false Example: ``` str.VersionGreater("1.0.0", "0.9.9") // true str.VersionGreater("3.0", "2.8.8alpha") // true ```

func VersionGreaterEqual

func VersionGreaterEqual(v1, v2 string) bool

VersionGreaterEqual 使用版本比较算法比较版本 v1 与版本 v2,如果 v1 大于等于 v2 返回 true,否则返回 false Example: ``` str.VersionGreaterEqual("1.0.0", "0.9.9") // true str.VersionGreaterEqual("3.0", "3.0") // true str.VersionGreaterEqual("3.0", "3.0a") // false ```

func VersionLess

func VersionLess(v1, v2 string) bool

VersionLess 使用版本比较算法比较版本 v1 与版本 v2,如果 v1 小于 v2 返回 true,否则返回 false Example: ``` str.VersionLess("0.9.9", "1.0.0") // true str.VersionLess("3.0", "3.0a") // true ```

func VersionLessEqual

func VersionLessEqual(v1, v2 string) bool

VersionLessEqual 使用版本比较算法比较版本 v1 与版本 v2,如果 v1 小于等于 v2 返回 true,否则返回 false Example: ``` str.VersionLessEqual("0.9.9", "1.0.0") // true str.VersionLessEqual("3.0", "3.0") // true str.VersionLessEqual("3.0a", "3.0") // false ```

func WaitConnect

func WaitConnect(addr string, timeout float64) error

func WaitRoutinesFromSlice

func WaitRoutinesFromSlice[T any](arg []T, job func(T))

func WithCacheCapacity

func WithCacheCapacity(capacity uint64) cacheExOption

func WithCacheTTL

func WithCacheTTL(ttl ...time.Duration) cacheExOption

func Wrap

func Wrap(err error, msg string) error

func Wrapf

func Wrapf(err error, format string, args ...interface{}) error

func ZlibCompress

func ZlibCompress(i interface{}) ([]byte, error)

func ZlibDeCompress

func ZlibDeCompress(ret []byte) ([]byte, error)

Types

type AssertTestingT

type AssertTestingT func(msg string, args ...any)

func (AssertTestingT) Errorf

func (a AssertTestingT) Errorf(format string, args ...interface{})

type AtomicBool

type AtomicBool int32

AtomicBool is an atomic Boolean Its methods are all atomic, thus safe to be called by multiple goroutines simultaneously Note: When embedding into a struct, one should always use *AtomicBool to avoid copy

Example
cond := NewAtomicBool() // default to false
cond.Set()              // set to true
cond.IsSet()            // returns true
cond.UnSet()            // set to false
cond.SetTo(true)        // set to whatever you want

func NewAtomicBool

func NewAtomicBool() *AtomicBool

New creates an AtomicBool with default to false

func NewBool

func NewBool(ok bool) *AtomicBool

NewBool creates an AtomicBool with given default value

func (*AtomicBool) IsSet

func (ab *AtomicBool) IsSet() bool

IsSet returns whether the Boolean is true

func (*AtomicBool) Set

func (ab *AtomicBool) Set()

Set sets the Boolean to true

func (*AtomicBool) SetTo

func (ab *AtomicBool) SetTo(yes bool)

SetTo sets the boolean with given Boolean

func (*AtomicBool) SetToIf

func (ab *AtomicBool) SetToIf(old, new bool) (set bool)

SetToIf sets the Boolean to new only if the Boolean matches the old Returns whether the set was done

func (*AtomicBool) UnSet

func (ab *AtomicBool) UnSet()

UnSet sets the Boolean to false

type BruteDictParser

type BruteDictParser struct {
	UserDictFile, PassDictFile *os.File
	UserDict, PassDict         *bufio.Scanner
	// contains filtered or unexported fields
}

func NewBruteDictParser

func NewBruteDictParser(userDict, passDict string) (*BruteDictParser, error)

func (*BruteDictParser) Next

func (b *BruteDictParser) Next() (*UserPassPair, error)

type BufferedPeekableConn

type BufferedPeekableConn struct {
	net.Conn
	// contains filtered or unexported fields
}

func NewPeekableNetConn

func NewPeekableNetConn(r net.Conn) *BufferedPeekableConn

func (*BufferedPeekableConn) GetBuf

func (b *BufferedPeekableConn) GetBuf() []byte

func (*BufferedPeekableConn) GetOriginConn

func (b *BufferedPeekableConn) GetOriginConn() net.Conn

func (*BufferedPeekableConn) GetReader

func (b *BufferedPeekableConn) GetReader() io.Reader

func (*BufferedPeekableConn) Peek

func (b *BufferedPeekableConn) Peek(i int) ([]byte, error)

func (*BufferedPeekableConn) PeekByte

func (b *BufferedPeekableConn) PeekByte() (byte, error)

func (*BufferedPeekableConn) PeekUint16

func (b *BufferedPeekableConn) PeekUint16() uint16

func (*BufferedPeekableConn) Read

func (b *BufferedPeekableConn) Read(buf []byte) (int, error)

func (*BufferedPeekableConn) SetBuf

func (b *BufferedPeekableConn) SetBuf(buf []byte)

type BufferedPeekableReader

type BufferedPeekableReader struct {
	io.Reader
	// contains filtered or unexported fields
}

func NewPeekableReader

func NewPeekableReader(r io.Reader) *BufferedPeekableReader

func (*BufferedPeekableReader) GetBuf

func (b *BufferedPeekableReader) GetBuf() []byte

func (*BufferedPeekableReader) GetReader

func (b *BufferedPeekableReader) GetReader() io.Reader

func (*BufferedPeekableReader) Peek

func (b *BufferedPeekableReader) Peek(i int) ([]byte, error)

func (*BufferedPeekableReader) Read

func (b *BufferedPeekableReader) Read(buf []byte) (int, error)

func (*BufferedPeekableReader) SetBuf

func (b *BufferedPeekableReader) SetBuf(buf []byte)

type BufferedPeekableReaderWriter

type BufferedPeekableReaderWriter struct {
	io.ReadWriter
	// contains filtered or unexported fields
}

func NewPeekableReaderWriter

func NewPeekableReaderWriter(r io.ReadWriter) *BufferedPeekableReaderWriter

func (*BufferedPeekableReaderWriter) GetBuf

func (b *BufferedPeekableReaderWriter) GetBuf() []byte

func (*BufferedPeekableReaderWriter) GetReader

func (b *BufferedPeekableReaderWriter) GetReader() io.Reader

func (*BufferedPeekableReaderWriter) Peek

func (b *BufferedPeekableReaderWriter) Peek(i int) ([]byte, error)

func (*BufferedPeekableReaderWriter) Read

func (b *BufferedPeekableReaderWriter) Read(buf []byte) (int, error)

func (*BufferedPeekableReaderWriter) SetBuf

func (b *BufferedPeekableReaderWriter) SetBuf(buf []byte)

type Cache

type Cache[T any] struct {
	*CacheWithKey[string, T]
}

func NewLRUCache

func NewLRUCache[T any](capacity uint64) *Cache[T]

func NewTTLCache

func NewTTLCache[T any](ttls ...time.Duration) *Cache[T]

NewTTLCache is a helper to create instance of the Cache struct

type CacheEx

type CacheEx[T any] struct {
	*CacheExWithKey[string, T]
}

func NewCacheEx

func NewCacheEx[T any](opt ...cacheExOption) *CacheEx[T]

type CacheExWithKey

type CacheExWithKey[U comparable, T any] struct {
	*ttlcache.Cache[U, T]
	// contains filtered or unexported fields
}

CacheExWithKey is a synchronized map of items that can auto-expire once stale

func NewCacheExWithKey

func NewCacheExWithKey[U comparable, T any](opt ...cacheExOption) *CacheExWithKey[U, T]

func (*CacheExWithKey[U, T]) Close

func (cache *CacheExWithKey[U, T]) Close()

Can only close once

func (*CacheExWithKey[U, T]) Count

func (cache *CacheExWithKey[U, T]) Count() int

Count returns the number of items in the cache

func (*CacheExWithKey[U, T]) ForEach

func (cache *CacheExWithKey[U, T]) ForEach(handler func(U, T))

func (*CacheExWithKey[U, T]) Get

func (cache *CacheExWithKey[U, T]) Get(key U) (value T, exists bool)

Get is a thread-safe way to lookup items Every lookup, also touches the item, hence extending it's life

func (*CacheExWithKey[U, T]) GetAll

func (cache *CacheExWithKey[U, T]) GetAll() map[U]T

func (*CacheExWithKey[U, T]) Purge

func (cache *CacheExWithKey[U, T]) Purge()

Purge will remove all entries

func (*CacheExWithKey[U, T]) Remove

func (cache *CacheExWithKey[U, T]) Remove(key U) bool

func (*CacheExWithKey[U, T]) Set

func (cache *CacheExWithKey[U, T]) Set(key U, value T)

Set is a thread-safe way to add new items to the map

func (*CacheExWithKey[U, T]) SetExpirationCallback

func (cache *CacheExWithKey[U, T]) SetExpirationCallback(callback expireCallback[U, T])

SetExpirationCallback sets a callback that will be called when an item expires

func (*CacheExWithKey[U, T]) SetNewItemCallback

func (cache *CacheExWithKey[U, T]) SetNewItemCallback(callback itemCallback[U, T])

SetNewItemCallback sets a callback that will be called when a new item is added to the cache

func (*CacheExWithKey[U, T]) SetTTL

func (cache *CacheExWithKey[U, T]) SetTTL(ttl time.Duration)

func (*CacheExWithKey[U, T]) SetWithTTL

func (cache *CacheExWithKey[U, T]) SetWithTTL(key U, value T, ttl time.Duration)

SetWithTTL is a thread-safe way to add new items to the map with individual ttl

func (*CacheExWithKey[U, T]) SkipTtlExtensionOnHit

func (cache *CacheExWithKey[U, T]) SkipTtlExtensionOnHit(value bool)

SkipTtlExtensionOnHit allows the user to change the cache behaviour. When this flag is set to true it will no longer extend TTL of items when they are retrieved using Get, or when their expiration condition is evaluated using SetCheckExpirationCallback.

type CacheWithKey

type CacheWithKey[U comparable, T any] struct {
	*CacheExWithKey[U, T]
	// contains filtered or unexported fields
}

func NewLRUCacheWithKey

func NewLRUCacheWithKey[U comparable, T any](capacity uint64) *CacheWithKey[U, T]

func NewTTLCacheWithKey

func NewTTLCacheWithKey[U comparable, T any](ttls ...time.Duration) *CacheWithKey[U, T]

NewTTLCacheWithKey is a helper to create instance of the CacheWithKey struct, allow set Key and Value

func (*CacheWithKey[U, T]) SetExpirationCallback

func (cache *CacheWithKey[U, T]) SetExpirationCallback(callback expireCallbackWithoutReason[U, T])

SetExpirationCallback sets a callback that will be called when an item expires

type CircularQueue

type CircularQueue struct {
	// contains filtered or unexported fields
}

func NewCircularQueue

func NewCircularQueue(capacity int) *CircularQueue

func (*CircularQueue) GetElements

func (q *CircularQueue) GetElements() []interface{}

func (*CircularQueue) Push

func (q *CircularQueue) Push(x interface{})

type Complex

type Complex interface {
	~complex64 | ~complex128
}

Complex is a constraint that permits any complex numeric type. If future releases of Go add new predeclared complex numeric types, this constraint will be modified to include them.

type CoolDown

type CoolDown struct {
	// contains filtered or unexported fields
}

func NewCoolDown

func NewCoolDown(d time.Duration) *CoolDown

func NewCoolDownContext

func NewCoolDownContext(d time.Duration, ctx context.Context) *CoolDown

func (*CoolDown) Do

func (c *CoolDown) Do(f func())

func (*CoolDown) DoOr

func (c *CoolDown) DoOr(f func(), fallback func())

func (*CoolDown) Reset

func (c *CoolDown) Reset(d time.Duration)

type CoolDownFetcher

type CoolDownFetcher struct {
	// contains filtered or unexported fields
}

func NewCoolDownFetcher

func NewCoolDownFetcher(timeoutDuration time.Duration) *CoolDownFetcher

func (*CoolDownFetcher) Fetch

func (c *CoolDownFetcher) Fetch(handler func() (any, error)) (any, error)

type CountingReadWriter

type CountingReadWriter struct {
	// contains filtered or unexported fields
}

CountingReadWriter 是一个包装了 io.Writer 的结构体,用于统计写入的字符数

func NewCountingReadWriter

func NewCountingReadWriter(w io.ReadWriter) *CountingReadWriter

NewCountingReadWriter 返回一个新的 CountingWriter,它包装了给定的 io.Writer

func (*CountingReadWriter) Count

func (cw *CountingReadWriter) Count() int

Count 返回到目前为止写入的字符数

func (*CountingReadWriter) Read

func (cr *CountingReadWriter) Read(p []byte) (n int, err error)

Read 实现了 io.Reader 接口,读取数据的同时统计字符数

func (*CountingReadWriter) Write

func (cw *CountingReadWriter) Write(p []byte) (n int, err error)

Write 实现了 io.Writer 接口,写入数据的同时统计字符数

type CountingReader

type CountingReader struct {
	// contains filtered or unexported fields
}

CountingReader 是一个包装了 io.Reader 的结构体,用于统计读取的字符数

func NewCountingReader

func NewCountingReader(r io.Reader) *CountingReader

NewCountingReader 返回一个新的 CountingReader,它包装了给定的 io.Reader

func (*CountingReader) Count

func (cr *CountingReader) Count() int

Count 返回到目前为止读取的字符数

func (*CountingReader) Read

func (cr *CountingReader) Read(p []byte) (n int, err error)

Read 实现了 io.Reader 接口,读取数据的同时统计字符数

type CountingWriter

type CountingWriter struct {
	// contains filtered or unexported fields
}

CountingWriter 是一个包装了 io.Writer 的结构体,用于统计写入的字符数

func NewCountingWriter

func NewCountingWriter(w io.Writer) *CountingWriter

NewCountingWriter 返回一个新的 CountingWriter,它包装了给定的 io.Writer

func (*CountingWriter) Count

func (cw *CountingWriter) Count() int

Count 返回到目前为止写入的字符数

func (*CountingWriter) Write

func (cw *CountingWriter) Write(p []byte) (n int, err error)

Write 实现了 io.Writer 接口,写入数据的同时统计字符数

type CustomWriter

type CustomWriter struct {
	// contains filtered or unexported fields
}

func NewWriter

func NewWriter(f func(p []byte) (n int, err error)) *CustomWriter

func (*CustomWriter) Write

func (c *CustomWriter) Write(p []byte) (n int, err error)

type DataBaseCacheWithKey

type DataBaseCacheWithKey[K comparable, T any] struct {
	// contains filtered or unexported fields
}

func NewDatabaseCacheWithKey

func NewDatabaseCacheWithKey[K comparable, T any](
	ttl time.Duration,
	save SaveDatabase[K, T],
	load LoadFromDatabase[K, T],
) *DataBaseCacheWithKey[K, T]

param: cache : ttl/lru cache save: save to database, function should be blocking, return true is success load: load from database, function should be blocking, return data and error

func (*DataBaseCacheWithKey[K, T]) Close

func (c *DataBaseCacheWithKey[K, T]) Close()

func (*DataBaseCacheWithKey[K, T]) Count

func (c *DataBaseCacheWithKey[K, T]) Count() int

func (*DataBaseCacheWithKey[K, T]) Delete

func (c *DataBaseCacheWithKey[K, T]) Delete(key K)

func (*DataBaseCacheWithKey[K, T]) ForEach

func (c *DataBaseCacheWithKey[K, T]) ForEach(f func(K, T) bool)

func (*DataBaseCacheWithKey[K, T]) Get

func (c *DataBaseCacheWithKey[K, T]) Get(key K) (T, bool)

func (*DataBaseCacheWithKey[K, T]) GetAll

func (c *DataBaseCacheWithKey[K, T]) GetAll() map[K]T

func (*DataBaseCacheWithKey[K, T]) GetPure

func (c *DataBaseCacheWithKey[K, T]) GetPure(key K) (T, bool)

func (*DataBaseCacheWithKey[K, T]) IsClose

func (c *DataBaseCacheWithKey[K, T]) IsClose() bool

func (*DataBaseCacheWithKey[K, T]) Set

func (c *DataBaseCacheWithKey[K, T]) Set(key K, memValue T)

type DelayWaiter

type DelayWaiter struct {
	// contains filtered or unexported fields
}

delay with range

func NewDelayWaiter

func NewDelayWaiter(min int32, max int32) (*DelayWaiter, error)

func (*DelayWaiter) Wait

func (d *DelayWaiter) Wait()

func (*DelayWaiter) WaitWithProbabilityPercent

func (d *DelayWaiter) WaitWithProbabilityPercent(raw float64)

type EvictionReason

type EvictionReason int

EvictionReason is used to specify why a certain item was evicted/deleted.

const (
	EvictionReasonDeleted EvictionReason = iota + 1
	EvictionReasonCapacityReached
	EvictionReasonExpired
)

Available eviction reasons.

type FileInfo

type FileInfo struct {
	BuildIn os.FileInfo
	Path    string
	Name    string
	IsDir   bool
}

func ReadDir

func ReadDir(p string) ([]*FileInfo, error)

func ReadDirWithLimit

func ReadDirWithLimit(p string, limit int) ([]*FileInfo, error)

func ReadDirsRecursively

func ReadDirsRecursively(p string) ([]*FileInfo, error)

func ReadFilesRecursively

func ReadFilesRecursively(p string) ([]*FileInfo, error)

func ReadFilesRecursivelyWithLimit

func ReadFilesRecursivelyWithLimit(p string, limit int) ([]*FileInfo, error)

type FileOpenerType

type FileOpenerType func(s string) (*os.File, error)

type Float

type Float interface {
	~float32 | ~float64
}

Float is a constraint that permits any floating-point type. If future releases of Go add new predeclared floating-point types, this constraint will be modified to include them.

type FloatSecondsDelayWaiter

type FloatSecondsDelayWaiter struct {
	// contains filtered or unexported fields
}

delay with range

func NewFloatSecondsDelayWaiter

func NewFloatSecondsDelayWaiter(min, max float64) (*FloatSecondsDelayWaiter, error)

func NewFloatSecondsDelayWaiterSingle

func NewFloatSecondsDelayWaiterSingle(min float64) (*FloatSecondsDelayWaiter, error)

func (*FloatSecondsDelayWaiter) Wait

func (d *FloatSecondsDelayWaiter) Wait()

func (*FloatSecondsDelayWaiter) WaitWithProbabilityPercent

func (d *FloatSecondsDelayWaiter) WaitWithProbabilityPercent(raw float64)

type Frame

type Frame uintptr

Frame represents a program counter inside a stack frame. For historical reasons if Frame is interpreted as a uintptr its value represents the program counter + 1.

func (Frame) Format

func (f Frame) Format(s fmt.State, verb rune)

Format formats the frame according to the fmt.Formatter interface.

%s    source file
%d    source line
%n    function name
%v    equivalent to %s:%d

Format accepts flags that alter the printing of some verbs, as follows:

%+s   function name and path of source file relative to the compile time
      GOPATH separated by \n\t (<funcname>\n\t<path>)
%+v   equivalent to %+s:%d

func (Frame) MarshalText

func (f Frame) MarshalText() ([]byte, error)

MarshalText formats a stacktrace Frame as a text string. The output is the same as that of fmt.Sprintf("%+v", f), but without newlines or tabs.

type GlobFilter

type GlobFilter struct {
	// contains filtered or unexported fields
}

func NewGlobFilter

func NewGlobFilter(separator rune, exclude ...string) *GlobFilter

func (*GlobFilter) Add

func (f *GlobFilter) Add(block ...string)

func (*GlobFilter) Contains

func (f *GlobFilter) Contains(target string) bool

type HTTPPacketFilter

type HTTPPacketFilter struct {
	// contains filtered or unexported fields
}

func NewHTTPPacketFilter

func NewHTTPPacketFilter() *HTTPPacketFilter

func (*HTTPPacketFilter) Conditions

func (j *HTTPPacketFilter) Conditions() []string

func (*HTTPPacketFilter) Hash

func (h *HTTPPacketFilter) Hash() string

func (*HTTPPacketFilter) IsAllowed

func (h *HTTPPacketFilter) IsAllowed(req *http.Request, rsp *http.Response) bool

func (*HTTPPacketFilter) Remove

func (i *HTTPPacketFilter) Remove(name string)

func (*HTTPPacketFilter) SetAllowForRequestHeader

func (j *HTTPPacketFilter) SetAllowForRequestHeader(header, regexp string)

func (*HTTPPacketFilter) SetAllowForRequestPath

func (j *HTTPPacketFilter) SetAllowForRequestPath(regexp string)

func (*HTTPPacketFilter) SetAllowForRequestRaw

func (j *HTTPPacketFilter) SetAllowForRequestRaw(regexp string)

func (*HTTPPacketFilter) SetAllowForResponseHeader

func (j *HTTPPacketFilter) SetAllowForResponseHeader(header, regexp string)

func (*HTTPPacketFilter) SetAllowForResponseRaw

func (j *HTTPPacketFilter) SetAllowForResponseRaw(regexp string)

func (*HTTPPacketFilter) SetRejectForRequestHeader

func (j *HTTPPacketFilter) SetRejectForRequestHeader(header, regexp string)

func (*HTTPPacketFilter) SetRejectForRequestPath

func (j *HTTPPacketFilter) SetRejectForRequestPath(regexp string)

func (*HTTPPacketFilter) SetRejectForRequestRaw

func (j *HTTPPacketFilter) SetRejectForRequestRaw(regexp string)

func (*HTTPPacketFilter) SetRejectForResponseHeader

func (j *HTTPPacketFilter) SetRejectForResponseHeader(header, regexp string)

func (*HTTPPacketFilter) SetRejectForResponseRaw

func (j *HTTPPacketFilter) SetRejectForResponseRaw(regexp string)

type HostPortClassifier

type HostPortClassifier struct {
	// contains filtered or unexported fields
}

func NewHostPortClassifier

func NewHostPortClassifier() *HostPortClassifier

func (*HostPortClassifier) AddHostPort

func (h *HostPortClassifier) AddHostPort(tag string, hosts []string, ports []string, ttl time.Duration) error

func (*HostPortClassifier) FilterTagByHostPort

func (h *HostPortClassifier) FilterTagByHostPort(host string, port int) []string

type HostsFilter

type HostsFilter struct {
	// contains filtered or unexported fields
}

func NewHostsFilter

func NewHostsFilter(excludeHosts ...string) *HostsFilter

func (*HostsFilter) Add

func (f *HostsFilter) Add(block ...string)

func (*HostsFilter) Contains

func (f *HostsFilter) Contains(target string) bool

type IntHeap

type IntHeap struct {
	// contains filtered or unexported fields
}

func NewIntHeap

func NewIntHeap(init ...[]int) *IntHeap

func (*IntHeap) Index

func (h *IntHeap) Index(i int) int

func (*IntHeap) Len

func (h *IntHeap) Len() int

func (*IntHeap) Pop

func (h *IntHeap) Pop() interface{}

func (*IntHeap) Push

func (h *IntHeap) Push(x interface{})

type Integer

type Integer interface {
	Signed | Unsigned
}

Integer is a constraint that permits any integer type. If future releases of Go add new predeclared integer types, this constraint will be modified to include them.

type LimitRate

type LimitRate struct {
	// contains filtered or unexported fields
}

func NewLimitRate

func NewLimitRate(d time.Duration) *LimitRate

func (*LimitRate) WaitUntilNextAsync

func (l *LimitRate) WaitUntilNextAsync()

func (*LimitRate) WaitUntilNextAsyncWithFallback

func (l *LimitRate) WaitUntilNextAsyncWithFallback(f func())

func (*LimitRate) WaitUntilNextSync

func (l *LimitRate) WaitUntilNextSync()

type LoadFromDatabase

type LoadFromDatabase[K comparable, T any] func(K) (T, error)

load data from database by key attention: this function should be blocking

type MatchedRule

type MatchedRule struct {
	Matched *regexp.Regexp
}

func ParseNmapServiceMatchedRule

func ParseNmapServiceMatchedRule(raw []byte) []*MatchedRule

type Ordered

type Ordered interface {
	Integer | Float | ~string
}

Ordered is a constraint that permits any ordered type: any type that supports the operators < <= >= >. If future releases of Go add new ordered types, this constraint will be modified to include them.

type PathForest

type PathForest struct {
	// contains filtered or unexported fields
}

func GeneratePathTrees

func GeneratePathTrees(l ...string) (*PathForest, error)

func (*PathForest) AddPath

func (p *PathForest) AddPath(path string, f any) error

func (*PathForest) Get

func (p *PathForest) Get(path string) (*PathNode, error)

func (*PathForest) Output

func (p *PathForest) Output() []*PathNode

func (*PathForest) ReadOnly

func (w *PathForest) ReadOnly()

func (*PathForest) Recursive

func (p *PathForest) Recursive(f func(node2 *PathNode))

type PathNode

type PathNode struct {
	Parent        *PathNode `json:"-"`
	Path          string    `json:"path"`
	RelativePaths []string  `json:"relative_paths"`
	Name          string    `json:"name"`

	Children []*PathNode `json:"children"`
	Depth    int         `json:"depth"`
	Value    any         `json:"-"`
	ReadOnly bool        `json:"-"`
	// contains filtered or unexported fields
}

func (*PathNode) AllChildren

func (p *PathNode) AllChildren() []*PathNode

func (*PathNode) Existed

func (p *PathNode) Existed(i string) bool

func (*PathNode) GetDepth

func (n *PathNode) GetDepth() int

type PathNodes

type PathNodes []*PathNode

type PerHandlerWriter

type PerHandlerWriter struct {
	// contains filtered or unexported fields
}

func NewPerHandlerWriter

func NewPerHandlerWriter(w io.Writer, handler func([]byte) ([]byte, bool)) *PerHandlerWriter

func (*PerHandlerWriter) Write

func (w *PerHandlerWriter) Write(p []byte) (n int, err error)

type PipeReader

type PipeReader struct {
	// contains filtered or unexported fields
}

A PipeReader is the read half of a pipe.

func (*PipeReader) BytesBuffer

func (p *PipeReader) BytesBuffer() *bytes.Buffer

func (*PipeReader) Close

func (r *PipeReader) Close() error

Close closes the reader; subsequent writes from the write half of the pipe will return error ErrClosedPipe.

func (*PipeReader) CloseWithError

func (r *PipeReader) CloseWithError(err error) error

CloseWithError closes the reader; subsequent writes to the write half of the pipe will return the error err.

func (*PipeReader) Count

func (p *PipeReader) Count() int

func (*PipeReader) Read

func (r *PipeReader) Read(data []byte) (int, error)

Read implements the standard Read interface: it reads data from the pipe, reading from the internal buffer, otherwise blocking until a writer arrives or the write end is closed. If the write end is closed with an error, that error is returned as err; otherwise err is io.EOF.

type PipeWriter

type PipeWriter struct {
	// contains filtered or unexported fields
}

A PipeWriter is the write half of a pipe.

func (*PipeWriter) BytesBuffer

func (p *PipeWriter) BytesBuffer() *bytes.Buffer

func (*PipeWriter) Close

func (w *PipeWriter) Close() error

Close closes the writer; subsequent reads from the read half of the pipe will return io.EOF once the internal buffer get empty.

func (*PipeWriter) CloseWithError

func (w *PipeWriter) CloseWithError(err error) error

CloseWithError closes the writer; subsequent reads from the read half of the pipe will return err once the internal buffer get empty.

func (*PipeWriter) Count

func (p *PipeWriter) Count() int

func (*PipeWriter) Write

func (w *PipeWriter) Write(data []byte) (int, error)

Write implements the standard Write interface: it writes data to the internal buffer. If the read end is closed with an error, that err is returned as err; otherwise err is ErrClosedPipe.

type PortScanTarget

type PortScanTarget struct {
	Targets []string
	TCPPort string
	UDPPort string
}

func SplitHostsAndPorts

func SplitHostsAndPorts(hosts, ports string, portGroupSize int, proto string) []PortScanTarget

func (*PortScanTarget) String

func (t *PortScanTarget) String() string

type PortsFilter

type PortsFilter struct {
	// contains filtered or unexported fields
}

func NewPortsFilter

func NewPortsFilter(blocks ...string) *PortsFilter

func (*PortsFilter) Add

func (f *PortsFilter) Add(block ...string)

func (*PortsFilter) Contains

func (f *PortsFilter) Contains(port int) bool

type ProbeRule

type ProbeRule struct {
	Type    ProtoType
	Payload []byte
	Matched []*MatchedRule
}

func ParseNmapServiceProbeRule

func ParseNmapServiceProbeRule(raw []byte) []*ProbeRule

type ProtoType

type ProtoType string
var (
	TCPProbe ProtoType = "tcp"
	UDPProbe ProtoType = "udp"
)

type RequireTestingT

type RequireTestingT struct {
	AssertTestingT
	FalNow func()
}

func NewRequireTestT

func NewRequireTestT(a AssertTestingT, f func()) *RequireTestingT

func (*RequireTestingT) FailNow

func (r *RequireTestingT) FailNow()

type SSHClient

type SSHClient struct {
	// contains filtered or unexported fields
}

func SSHDial

func SSHDial(network, addr string, config *ssh.ClientConfig) (*SSHClient, error)

SSHDial starts a client connection to the given SSH server. This is wrap the ssh.SSHDial

func SSHDialWithKey

func SSHDialWithKey(addr, user, keyfile string) (*SSHClient, error)

SSHDialWithKey starts a client connection to the given SSH server with key authmethod.

func SSHDialWithKeyWithPassphrase

func SSHDialWithKeyWithPassphrase(addr, user, keyfile string, passphrase string) (*SSHClient, error)

SSHDialWithKeyWithPassphrase same as SSHDialWithKey but with a passphrase to decrypt the private key

func SSHDialWithPasswd

func SSHDialWithPasswd(addr, user, passwd string) (*SSHClient, error)

SSHDialWithPasswd starts a client connection to the given SSH server with passwd authmethod.

func (*SSHClient) Close

func (c *SSHClient) Close() error

func (*SSHClient) Cmd

func (c *SSHClient) Cmd(cmd string) *SSHRemoteScript

Cmd create a command on client

func (*SSHClient) CopyLocalFileToRemote

func (c *SSHClient) CopyLocalFileToRemote(srcFilePath string, dstFilePath string) error

Copy local file to remote

func (*SSHClient) CopyRemoteFileToLocal

func (c *SSHClient) CopyRemoteFileToLocal(dstFilePath string, srcFilePath string) error

Copy remote file to local

func (*SSHClient) Script

func (c *SSHClient) Script(script string) *SSHRemoteScript

Script

func (*SSHClient) ScriptFile

func (c *SSHClient) ScriptFile(fname string) *SSHRemoteScript

ScriptFile

func (*SSHClient) Shell

func (c *SSHClient) Shell() *SSHRemoteShell

Shell create a noninteractive shell on client.

func (*SSHClient) Terminal

func (c *SSHClient) Terminal(config *TerminalConfig) *SSHRemoteShell

Terminal create a interactive shell on client.

type SSHRemoteScript

type SSHRemoteScript struct {
	// contains filtered or unexported fields
}

func (*SSHRemoteScript) Cmd

func (rs *SSHRemoteScript) Cmd(cmd string) *SSHRemoteScript

func (*SSHRemoteScript) Output

func (rs *SSHRemoteScript) Output() ([]byte, error)

func (*SSHRemoteScript) Run

func (rs *SSHRemoteScript) Run() error

Run

func (*SSHRemoteScript) SetStdio

func (rs *SSHRemoteScript) SetStdio(stdout, stderr io.Writer) *SSHRemoteScript

func (*SSHRemoteScript) SmartOutput

func (rs *SSHRemoteScript) SmartOutput() ([]byte, error)

type SSHRemoteScriptType

type SSHRemoteScriptType byte

type SSHRemoteShell

type SSHRemoteShell struct {
	// contains filtered or unexported fields
}

func (*SSHRemoteShell) SetStdio

func (rs *SSHRemoteShell) SetStdio(stdin io.Reader, stdout, stderr io.Writer) *SSHRemoteShell

func (*SSHRemoteShell) Start

func (rs *SSHRemoteShell) Start() error

Start start a remote shell on client

type SSHRemoteShellType

type SSHRemoteShellType byte

type SafeMap

type SafeMap[V any] struct {
	*SafeMapWithKey[string, V]
}

func NewSafeMap

func NewSafeMap[V any]() *SafeMap[V]

type SafeMapWithKey

type SafeMapWithKey[K comparable, V any] struct {
	// contains filtered or unexported fields
}

func NewSafeMapWithKey

func NewSafeMapWithKey[K comparable, V any]() *SafeMapWithKey[K, V]

func (*SafeMapWithKey[K, V]) Count

func (sm *SafeMapWithKey[K, V]) Count() int

func (*SafeMapWithKey[K, V]) Delete

func (sm *SafeMapWithKey[K, V]) Delete(key K)

func (*SafeMapWithKey[K, V]) ForEach

func (sm *SafeMapWithKey[K, V]) ForEach(f func(key K, value V) bool)

func (*SafeMapWithKey[K, V]) Get

func (sm *SafeMapWithKey[K, V]) Get(key K) (V, bool)

func (*SafeMapWithKey[K, V]) Have

func (sm *SafeMapWithKey[K, V]) Have(key K) bool

func (*SafeMapWithKey[K, V]) Set

func (sm *SafeMapWithKey[K, V]) Set(key K, value V)

type SaveDatabase

type SaveDatabase[K comparable, T any] func(K, T, EvictionReason) bool

save to database attention: this function should be blocking

type Set

type Set[T comparable] struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

func NewSet

func NewSet[T comparable](list ...[]T) *Set[T]

func (*Set[T]) Add

func (s *Set[T]) Add(item T)

Add add

func (*Set[T]) AddList

func (s *Set[T]) AddList(items []T)

func (*Set[T]) And

func (s *Set[T]) And(other *Set[T]) *Set[T]

func (*Set[T]) Clear

func (s *Set[T]) Clear()

Clear removes all items from the set

func (*Set[T]) Diff

func (s *Set[T]) Diff(other *Set[T]) *Set[T]

func (*Set[T]) ForEach

func (s *Set[T]) ForEach(h func(T))

func (*Set[T]) Has

func (s *Set[T]) Has(item T) bool

Has looks for the existence of an item

func (*Set[T]) IsEmpty

func (s *Set[T]) IsEmpty() bool

IsEmpty checks for emptiness

func (*Set[T]) Len

func (s *Set[T]) Len() int

Len returns the number of items in a set.

func (*Set[T]) List

func (s *Set[T]) List() []T

Set returns a slice of all items

func (*Set[T]) Or

func (s *Set[T]) Or(other *Set[T]) *Set[T]

func (*Set[T]) Remove

func (s *Set[T]) Remove(item T)

Remove deletes the specified item from the map

type Signed

type Signed interface {
	~int | ~int8 | ~int16 | ~int32 | ~int64
}

Signed is a constraint that permits any signed integer type. If future releases of Go add new predeclared signed integer types, this constraint will be modified to include them.

type SizedWaitGroup

type SizedWaitGroup struct {
	Size              int
	WaitingEventCount atomic.Int64
	// contains filtered or unexported fields
}

SizedWaitGroup has the same role and close to the same API as the Golang sync.WaitGroup but adds a limit of the amount of goroutines started concurrently.

func NewSizedWaitGroup

func NewSizedWaitGroup(limit int, ctxs ...context.Context) *SizedWaitGroup

New creates a SizedWaitGroup. The limit parameter is the maximum amount of goroutines which can be started concurrently.

func (*SizedWaitGroup) Add

func (s *SizedWaitGroup) Add(delta ...int)

Add increments the internal WaitGroup counter. It can be blocking if the limit of spawned goroutines has been reached. It will stop blocking when Done is been called.

See sync.WaitGroup documentation for more information.

func (*SizedWaitGroup) AddWithContext

func (s *SizedWaitGroup) AddWithContext(ctx context.Context, delta ...int) error

AddWithContext increments the internal WaitGroup counter. It can be blocking if the limit of spawned goroutines has been reached. It will stop blocking when Done is been called, or when the context is canceled. Returns nil on success or an error if the context is canceled before the lock is acquired.

See sync.WaitGroup documentation for more information.

func (*SizedWaitGroup) Done

func (s *SizedWaitGroup) Done()

Done decrements the SizedWaitGroup counter. See sync.WaitGroup documentation for more information.

func (*SizedWaitGroup) SetContext

func (s *SizedWaitGroup) SetContext(ctx context.Context)

SetContext sets the context for the SizedWaitGroup. ! If Call twice or more, any of the previous context Done will cause the WaitGroup to be SetZero.

func (*SizedWaitGroup) SetZero

func (s *SizedWaitGroup) SetZero()

func (*SizedWaitGroup) Wait

func (s *SizedWaitGroup) Wait()

Wait blocks until the SizedWaitGroup counter is zero. See sync.WaitGroup documentation for more information.

type Stack

type Stack[T any] struct {
	// contains filtered or unexported fields
}

func NewStack

func NewStack[T any]() *Stack[T]

Create a new stack

func (*Stack[T]) CreateShadowStack

func (this *Stack[T]) CreateShadowStack() func()

CreateShadowStack creates a shadow stack, which can be used to restore the stack to its current state. dont pop the top item of the stack.

func (*Stack[T]) HaveLastStackValue

func (this *Stack[T]) HaveLastStackValue() bool

func (*Stack[T]) IsEmpty

func (this *Stack[T]) IsEmpty() bool

func (*Stack[T]) LastStackValue

func (this *Stack[T]) LastStackValue() T

func (*Stack[T]) Len

func (this *Stack[T]) Len() int

Return the number of items in the stack

func (*Stack[T]) Peek

func (this *Stack[T]) Peek() T

View the top item on the stack

func (*Stack[T]) PeekN

func (this *Stack[T]) PeekN(n int) T

View the top n item on the stack

func (*Stack[T]) Pop

func (this *Stack[T]) Pop() T

Pop the top item of the stack and return it

func (*Stack[T]) PopN

func (this *Stack[T]) PopN(n int) []T

PopN the top item of the stack and return it

func (*Stack[T]) Push

func (this *Stack[T]) Push(value T)

Push a value onto the top of the stack

func (*Stack[T]) Size

func (this *Stack[T]) Size() int

type StackTrace

type StackTrace []Frame

StackTrace is stack of Frames from innermost (newest) to outermost (oldest).

func (StackTrace) Format

func (st StackTrace) Format(s fmt.State, verb rune)

Format formats the stack of Frames according to the fmt.Formatter interface.

%s	lists source files for each Frame in the stack
%v	lists the source file and line number for each Frame in the stack

Format accepts flags that alter the printing of some verbs, as follows:

%+v   Prints filename, function, and line number for each Frame in the stack.

type StringRoundRobinSelector

type StringRoundRobinSelector struct {
	// contains filtered or unexported fields
}

func NewStringRoundRobinSelector

func NewStringRoundRobinSelector(l ...string) *StringRoundRobinSelector

func (*StringRoundRobinSelector) Add

func (s *StringRoundRobinSelector) Add(raw ...string)

func (*StringRoundRobinSelector) Len

func (s *StringRoundRobinSelector) Len() int

func (*StringRoundRobinSelector) List

func (s *StringRoundRobinSelector) List() []string

func (*StringRoundRobinSelector) Next

func (s *StringRoundRobinSelector) Next() string

type Switch

type Switch struct {
	*sync.Cond
	// contains filtered or unexported fields
}

func NewSwitch

func NewSwitch(b ...bool) *Switch

func (*Switch) Condition

func (c *Switch) Condition() bool

func (*Switch) Switch

func (c *Switch) Switch()

func (*Switch) SwitchTo

func (c *Switch) SwitchTo(b bool)

func (*Switch) WaitUntilOpen

func (c *Switch) WaitUntilOpen()

type TerminalConfig

type TerminalConfig struct {
	Term   string
	Height int
	Weight int
	Modes  ssh.TerminalModes
}

type TriggerWriter

type TriggerWriter struct {
	// contains filtered or unexported fields
}

func NewTriggerWriter

func NewTriggerWriter(trigger uint64, h func(buffer io.ReadCloser)) *TriggerWriter

func (*TriggerWriter) Close

func (f *TriggerWriter) Close() error

func (*TriggerWriter) GetCount

func (f *TriggerWriter) GetCount() int64

func (*TriggerWriter) Write

func (f *TriggerWriter) Write(p []byte) (n int, err error)

type TrimLeftReader

type TrimLeftReader struct {
	// contains filtered or unexported fields
}

TrimLeftReader wraps an io.Reader and trims leading white space from the input.

func NewTrimLeftReader

func NewTrimLeftReader(r io.Reader) *TrimLeftReader

func (*TrimLeftReader) Read

func (t *TrimLeftReader) Read(p []byte) (int, error)

Read implements the io.Reader interface for TrimLeftReader.

type Unsigned

type Unsigned interface {
	~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr
}

Unsigned is a constraint that permits any unsigned integer type. If future releases of Go add new predeclared unsigned integer types, this constraint will be modified to include them.

type UserPassPair

type UserPassPair struct {
	Username, Password     string
	UserOffset, PassOffset int64
}

type WebHookServer

type WebHookServer struct {
	// contains filtered or unexported fields
}

func NewWebHookServer

func NewWebHookServer(port int, cb func(data interface{})) *WebHookServer

func (*WebHookServer) Addr

func (w *WebHookServer) Addr() string

func (*WebHookServer) Shutdown

func (w *WebHookServer) Shutdown()

func (*WebHookServer) Start

func (w *WebHookServer) Start()

type YakError

type YakError struct {
	// contains filtered or unexported fields
}

func (*YakError) Cause

func (err *YakError) Cause() []error

func (*YakError) Error

func (err *YakError) Error() string

func (*YakError) ErrorWithStack

func (e *YakError) ErrorWithStack() string

func (*YakError) Format

func (err *YakError) Format(s fmt.State, verb rune)

func (*YakError) Is

func (e *YakError) Is(rerr error) bool

func (YakError) StackTrace

func (s YakError) StackTrace() StackTrace

func (*YakError) Unwrap

func (err *YakError) Unwrap() []error

Directories

Path Synopsis
rfb.go
Package dateparse parses date-strings without knowing the format in advance, using a fast lex based approach to eliminate shotgun attempts.
Package dateparse parses date-strings without knowing the format in advance, using a fast lex based approach to eliminate shotgun attempts.
Origin: https://github.com/lithammer/fuzzysearch Fuzzy searching allows for flexibly matching a string with partial input, useful for filtering data very quickly based on lightweight user input.
Origin: https://github.com/lithammer/fuzzysearch Fuzzy searching allows for flexibly matching a string with partial input, useful for filtering data very quickly based on lightweight user input.
cmd command
Package htmlquery provides extract data from HTML documents using XPath expression.
Package htmlquery provides extract data from HTML documents using XPath expression.
cmd command
Ref: https://github.com/gobwas/ws
Ref: https://github.com/gobwas/ws
poc
rewrite multipart reader for compatibility with invalid boundary
rewrite multipart reader for compatibility with invalid boundary
cmd command
netroute
Originally found in https://github.com/gopacket/gopacket/blob/master/routing/routing.go
Originally found in https://github.com/gopacket/gopacket/blob/master/routing/routing.go
Package pop3 is a simple POP3 e-mail client library.
Package pop3 is a simple POP3 e-mail client library.
Package pprofutils provides utilities for runtime profiling of Go applications.
Package pprofutils provides utilities for runtime profiling of Go applications.
Reference: https://github.com/MetaCubeX/mihomo
Reference: https://github.com/MetaCubeX/mihomo
Reference: https://github.com/astaxie/goredis
Reference: https://github.com/astaxie/goredis
Package shlex implements a simple lexer which splits input in to tokens using shell-style rules for quoting and commenting.
Package shlex implements a simple lexer which splits input in to tokens using shell-style rules for quoting and commenting.
Reference: https://github.com/stacktitan/smb
Reference: https://github.com/stacktitan/smb
go-shodan
Package shodan is an interface for the Shodan API
Package shodan is an interface for the Shodan API
go-pkcs12
Package pkcs12 implements some of PKCS#12 (also known as P12 or PFX).
Package pkcs12 implements some of PKCS#12 (also known as P12 or PFX).
go-pkcs12/rc2
Package rc2 implements the RC2 cipher
Package rc2 implements the RC2 cipher
Package xml implements a simple XML 1.0 parser that understands XML name spaces.
Package xml implements a simple XML 1.0 parser that understands XML name spaces.

Jump to

Keyboard shortcuts

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