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 ¶
- Constants
- Variables
- func AddressFamilyUint32ToString(i uint32) string
- func AppendDefaultPort(raw string, port int) string
- func AppendSliceItemWhenNotExists[T comparable](s []T, t T) []T
- func AsDebugString(i interface{}, raws ...bool) string
- func AsciiBytesToRegexpMatchedRunes(in []byte) []rune
- func AsciiBytesToRegexpMatchedString(in []byte) string
- func AsciiEqualFold(s, t string) bool
- func AsciiToLower(s string) (lower string, ok bool)
- func AttemptWithDelay(maxIteration int, delay time.Duration, f func() error) error
- func AttemptWithDelayFast(f func() error) error
- func BKDRHash(str []byte) uint32
- func BufioReadLine(reader *bufio.Reader) ([]byte, error)
- func BufioReadLineString(reader *bufio.Reader) (string, error)
- func ByteCountBinary(b int64) string
- func ByteCountDecimal(b int64) string
- func ByteSize(bytes uint64) string
- func BytesClone(raw []byte) (newBytes []byte)
- func CacheFunc[T any](duration time.Duration, f func() (T, error)) func() (T, error)
- func CalcMd5(items ...interface{}) string
- func CalcSSDeepStability(req ...[]byte) (float64, error)
- func CalcSha1(items ...interface{}) string
- func CalcSha1WithSuffix(items []interface{}, suffix string) string
- func CalcSha256(items ...interface{}) string
- func CalcSimHashStability(req ...[]byte) (float64, error)
- func CalcSimilarity(raw ...[]byte) float64
- func CalcTextSubStringStability(raw ...[]byte) (float64, error)
- func CallGeneralClose(closer any)
- func CallWithCtx(ctx context.Context, cb func()) error
- func CallWithTimeout(timeout float64, cb func()) error
- func ChanStringToSlice(c chan string) (result []string)
- func CloseConnSafe(conn net.Conn)
- func CloseWrite(i any)
- func ConcatPorts(ports []int) string
- func ConcurrentCopyDirectory(source string, destination string, threads int, isMove bool) error
- func ConnExpect(c net.Conn, timeout time.Duration, callback func([]byte) bool) (bool, error)
- func ContainsAll[T comparable](s []T, vals ...T) bool
- func ContainsAny[T comparable](s []T, vals ...T) bool
- func ContainsJSON(raw string) (string, bool)
- func ConvertTextFileToYakFuzztagByPath(file_bin_path string) (string, error)
- func ConvertToStringSlice(raw ...interface{}) (r []string)
- func CopyBytes(rsp []byte) []byte
- func CopyDirectory(source string, destination string, isMove bool) error
- func CopyDirectoryEx(source string, destination string, isMove bool, fs fi.FileSystem) error
- func CopyFile(source, destination string) error
- func CopyFileEx(source string, destination string, fs fi.FileSystem) error
- func CopyMapInterface(i map[string]interface{}) map[string]interface{}
- func CopyMapShallow[K comparable, V any](originalMap map[K]V) map[K]V
- func CopySlice[T any](i []T) []T
- func CreateTempTestDatabaseInMemory() (*gorm.DB, error)
- func CreateUTF8StreamMirror(r io.Reader, cb ...func(reader io.Reader)) io.Reader
- func CutBytesPrefixFunc(raw []byte, handle func(rune) bool) ([]byte, []byte, bool)
- func DataVerbose(i interface{}) string
- func DatePretty() string
- func DatetimePretty() string
- func DatetimePretty2() string
- func Debug(f func())
- func DebugMockEchoWs(point string) (string, int)
- func DebugMockEchoWss(point string) (string, int)
- func DebugMockGMHTTP(ctx context.Context, handler func(req []byte) []byte) (string, int)
- func DebugMockHTTP(rsp []byte) (string, int)
- func DebugMockHTTP2(ctx context.Context, handler func(req []byte) []byte) (string, int)
- func DebugMockHTTP2HandlerFuncContext(ctx context.Context, handlerFunc http.HandlerFunc) (string, int)
- func DebugMockHTTPEx(handle func(req []byte) []byte) (string, int)
- func DebugMockHTTPExContext(ctx context.Context, handle func(req []byte) []byte) (string, int)
- func DebugMockHTTPHandlerFunc(handlerFunc http.HandlerFunc) (string, int)
- func DebugMockHTTPHandlerFuncContext(ctx context.Context, handlerFunc http.HandlerFunc) (string, int)
- func DebugMockHTTPKeepAliveEx(handle func(req []byte) []byte) (string, int)
- func DebugMockHTTPS(rsp []byte) (string, int)
- func DebugMockHTTPSEx(handle func(req []byte) []byte) (string, int)
- func DebugMockHTTPSKeepAliveEx(handle func(req []byte) []byte) (string, int)
- func DebugMockHTTPServerWithContext(ctx context.Context, https, h2, gmtlsFlag, onlyGmtls, keepAlive bool, ...) (string, int)
- func DebugMockHTTPServerWithContextWithAddress(ctx context.Context, addr string, ...) (string, int)
- func DebugMockHTTPWithTimeout(du time.Duration, rsp []byte) (string, int)
- func DebugMockOnlyGMHTTP(ctx context.Context, handler func(req []byte) []byte) (string, int)
- func DebugMockTCP(rsp []byte) (string, int)
- func DebugMockTCPEx(handleFunc handleTCPFunc) (string, int)
- func DebugMockTCPHandlerFuncContext(ctx context.Context, handlerFunc handleTCPFunc) (string, int)
- func DebugMockWs(handler func(conn *websocket.Conn)) (string, int)
- func DomainToURLFilter(domain string) (*regexp.Regexp, error)
- func DownloadFile(ctx context.Context, client *http.Client, u string, localFile string, ...) error
- func DumpFileWithTextAndFiles(raw string, divider string, files ...string) (string, error)
- func DumpHTTPRequest(req *http.Request, loadBody bool) ([]byte, error)
- func DumpHTTPResponse(rsp *http.Response, loadBody bool, wr ...io.Writer) ([]byte, error)
- func DumpHostFileWithTextAndFiles(raw string, divider string, files ...string) (string, error)
- func EnableDebug()
- func Error(i interface{}) error
- func ErrorStack(origin any) (err error)
- func Errorf(format string, args ...interface{}) error
- func EscapeInvalidUTF8Byte(s []byte) string
- func ExportAppConfigToMap(ins any) (map[string]string, error)
- func ExtractFaviconURL(siteURL string, content []byte) (string, error)
- func ExtractHost(raw string) string
- func ExtractHostPort(raw string) string
- func ExtractMapValueBool(m any, key string) bool
- func ExtractMapValueGeneralMap(m any, key string) map[string]any
- func ExtractMapValueInt(m any, key string) int
- func ExtractMapValueRaw(m any, key string) any
- func ExtractMapValueString(m any, key string) string
- func ExtractRawPath(target string) string
- func ExtractStrContextByKeyword(raw string, res []string) []string
- func ExtractTitleFromHTMLTitle(s string, defaultValue string) string
- func FileExists(filename string) bool
- func FileLineReader(file string) (chan []byte, error)
- func FileLineReaderWithContext(file string, ctx context.Context) (chan []byte, error)
- func FilterInterface[T any](i []any) []T
- func FindNearestAvailablePortWithTimeout(host string, originalPort int, timeout time.Duration) int
- func FirstWriter(onFirstWrite func([]byte)) io.Writer
- func FixForParseIP(host string) string
- func FixHTTPRequestForGolangNativeHTTPClient(req *http.Request)
- func FixHTTPRequestForHTTPDo(r *http.Request) (*http.Request, error)
- func FixHTTPRequestForHTTPDoWithHttps(r *http.Request, isHttps bool) (*http.Request, error)
- func FixHTTPResponseForGolangNativeHTTPClient(ins *http.Response)
- func FixJsonRawBytes(rawBytes []byte) []byte
- func FloatSecondDuration(f float64) time.Duration
- func FlushWriter(writer io.Writer)
- func Format(raw string, data map[string]string) string
- func GetAllFiles(path string) (fileNames []string, err error)
- func GetCClassByIPv4(s string) (network string, err error)
- func GetCachedLog() (res []string)
- func GetConnectedToHostPortFromHTTPRequest(t *http.Request) (string, error)
- func GetContextKeyBool(ctx context.Context, key string) bool
- func GetContextKeyString(ctx context.Context, key string) string
- func GetCurrentDate() (time.Time, error)
- func GetCurrentWeekMonday() (time.Time, error)
- func GetDate(t time.Time) (time.Time, error)
- func GetDefaultGMTLSConfig(i float64) *gmtls.Config
- func GetDefaultOnlyGMTLSConfig(i float64) *gmtls.Config
- func GetDefaultTLSConfig(i float64) *tls.Config
- func GetExecutableFromEnv(cmd string) (string, error)
- func GetFileAbsDir(filePath string) (string, error)
- func GetFileAbsPath(filePath string) (string, error)
- func GetFileMd5(filepath string) string
- func GetFileModTime(path string) int64
- func GetFileSha256(filepath string) string
- func GetFirstExcludedHighPort(excluded ...string) int
- func GetFirstExistedExecutablePath(paths ...string) string
- func GetFirstExistedFile(paths ...string) string
- func GetFirstExistedFileE(paths ...string) (string, error)
- func GetFirstExistedPath(paths ...string) string
- func GetFirstExistedPathE(paths ...string) (string, error)
- func GetHTTPHeader(headers http.Header, key string) string
- func GetHomeDir() (string, error)
- func GetHomeDirDefault(d string) string
- func GetLastElement[T any](list []T) T
- func GetLatestFile(dir, suffix string) (filename string, err error)
- func GetLocalIPAddress() string
- func GetLocalIPAddressViaIface() string
- func GetMachineCode() string
- func GetNExcludeExcludeHighPort(n int, excluded ...string) []int
- func GetRandomAvailableTCPPort() int
- func GetRandomAvailableTCPPortWithCtx(ctx context.Context, host string) int
- func GetRandomAvailableUDPPort() int
- func GetRandomIPAddress() string
- func GetRandomLocalAddr() string
- func GetRangeAvailableTCPPort(startPort, endPort, maxRetries int) (int, error)
- func GetSameSubStrings(raw ...string) []string
- func GetSameSubStringsRunes(text1, text2 []rune) [][]rune
- func GetSimpleUri(u *url.URL) string
- func GetSortedMapKeys[K Ordered, V any](m map[K]V) []K
- func GetSystemDnsServers() ([]string, error)
- func GetSystemMachineCode() (_ string, err error)
- func GetSystemNameServerList() ([]string, error)
- func GetUnexportedField(field reflect.Value) interface{}
- func GetWeekStartMonday(t time.Time) (time.Time, error)
- func GetWeekStartSunday() (time.Time, error)
- func GormTransaction(db *gorm.DB, callback func(tx *gorm.DB) error) (err error)
- func GormTransactionReturnDb(db *gorm.DB, callback func(tx *gorm.DB)) (tx *gorm.DB)
- func GzipCompress(i interface{}) ([]byte, error)
- func GzipDeCompress(ret []byte) ([]byte, error)
- func HTTPFrameParser(raw io.Reader) ([][2]string, [][2]string, io.Reader, error)
- func HTTPPacketIsLargerThanMaxContentLength(res interface{}, maxLength int) bool
- func HandleStdout(ctx context.Context, handle func(string)) error
- func HandleStdoutBackgroundForTest(handle func(string)) (func(), func(), error)
- func HostContains(rule string, target string) bool
- func HostPort(host string, port interface{}) string
- func HttpDumpWithBody(i interface{}, body bool) ([]byte, error)
- func HttpShow(i interface{}) []byte
- func IContains(s, sub string) bool
- func IHasPrefix(s, sub string) bool
- func IOCopy(dst io.Writer, src io.Reader, buf []byte) (written int64, err error)
- func IPv4ToCClassNetwork(s string) (string, error)
- func IPv4ToUint32(ip net.IP) (uint32, error)
- func IPv4ToUint64(ip string) (int64, error)
- func IStringContainsAnyOfSubString(s string, subs []string) bool
- func ImportAppConfigToStruct(template any, data map[string]string) (err error)
- func InDebugMode() bool
- func InGithubActions() bool
- func InTestcase() bool
- func IncludeExcludeChecker(includes, excludes []string, target string) (passed bool)
- func IndexAllSubstrings(s string, patterns ...string) (result [][2]int)
- func InetAtoN(ip net.IP) int64
- func InetNtoA(ip int64) net.IP
- func InitialCapitalizationEachWords(str string) string
- func InsertSliceItem[T comparable](slices []T, e T, index int) []T
- func Int64SliceToIntSlice(i []int64) []int
- func IntArrayContains(array []int, element int) bool
- func IntLargerZeroOr(s ...int) int
- func IntSliceToInt64Slice(i []int) []int64
- func InterfaceToBoolean(i any) bool
- func InterfaceToBytes(i interface{}) (result []byte)
- func InterfaceToBytesSlice(i interface{}) [][]byte
- func InterfaceToFloat64(i any) float64
- func InterfaceToGeneralMap(params interface{}) (finalResult map[string]interface{})
- func InterfaceToInt(i any) int
- func InterfaceToJsonString(i interface{}) string
- func InterfaceToMap(i interface{}) map[string][]string
- func InterfaceToMapInterface(i interface{}) map[string]interface{}
- func InterfaceToMapInterfaceE(i interface{}) (map[string]interface{}, error)
- func InterfaceToQuotedString(i interface{}) string
- func InterfaceToSliceInterface(i interface{}) []any
- func InterfaceToSliceInterfaceE(i interface{}) ([]any, error)
- func InterfaceToString(i interface{}) string
- func InterfaceToStringSlice(i interface{}) (result []string)
- func IsASCIIPrint(s string) bool
- func IsAudio(filePath string) (bool, error)
- func IsBase64(s string) bool
- func IsCommonHTTPRequestMethod(i any) bool
- func IsConnectResetError(err error) bool
- func IsDir(path string) bool
- func IsErrorNetOpTimeout(err error) bool
- func IsFile(path string) bool
- func IsFloat(v interface{}) bool
- func IsGenericTextFile(filePath string) (bool, error)
- func IsGenericTextType(fileType *mimetype.MIME) bool
- func IsGzip(raw []byte) bool
- func IsGzipBytes(i interface{}) bool
- func IsHttpOrHttpsUrl(raw string) bool
- func IsIPv4(raw string) bool
- func IsIPv6(raw string) bool
- func IsImage(i []byte) bool
- func IsInt(v interface{}) bool
- func IsJSON(raw string) (string, bool)
- func IsLinux() bool
- func IsLoopback(t string) bool
- func IsMac() bool
- func IsMap(input any) bool
- func IsMedia(filePath string) (bool, error)
- func IsNil(input any) bool
- func IsPlainText(raw []byte) bool
- func IsPortAvailable(host string, p int) bool
- func IsPortAvailableWithTimeout(host string, port int, timeout time.Duration) bool
- func IsPortAvailableWithUDP(host string, p int) bool
- func IsPrivateIP(ip net.IP) bool
- func IsProtobuf(raw []byte) bool
- func IsStrongPassword(s string) bool
- func IsSubPath(sub, parent string) bool
- func IsTCPPortAvailable(p int) bool
- func IsTCPPortAvailableWithLoopback(p int) bool
- func IsTCPPortOpen(host string, p int) bool
- func IsUDPPortAvailable(p int) bool
- func IsUDPPortAvailableWithLoopback(p int) bool
- func IsValidBool(raw string) bool
- func IsValidCIDR(raw string) bool
- func IsValidDomain(raw string) bool
- func IsValidFloat(raw string) bool
- func IsValidHost(raw string) bool
- func IsValidHostsRange(raw string) bool
- func IsValidInteger(raw string) bool
- func IsValidPortsRange(ports string) bool
- func IsVideo(filePath string) (bool, error)
- func IsWebsocketUrl(raw string) bool
- func IsWindows() bool
- func JSONStringReader(reader io.Reader) io.Reader
- func JavaTimeFormatter(t time.Time, formatter string) string
- func JitterBackoff(min, max time.Duration, attempt int) time.Duration
- func JoinErrors(errs ...error) error
- func Jsonify(i interface{}) []byte
- func LastLine(s []byte) []byte
- func LoopEvery1sBreakUntil(until func() bool)
- func MIMEGlobRuleCheck(target string, rule string) bool
- func MapGet[T any](m map[string]any, key string) T
- func MapGetBool(m map[string]interface{}, key string) bool
- func MapGetBoolOr(m map[string]interface{}, key string, value bool) bool
- func MapGetFirstRaw(m map[string]interface{}, key ...string) interface{}
- func MapGetFloat32(m map[string]interface{}, key string) float32
- func MapGetFloat32Or(m map[string]interface{}, key string, value float32) float32
- func MapGetFloat64(m map[string]interface{}, key string) float64
- func MapGetFloat64Or(m map[string]interface{}, key string, value float64) float64
- func MapGetInt(m map[string]interface{}, key string) int
- func MapGetInt64(m map[string]interface{}, key string) int64
- func MapGetInt64Or(m map[string]interface{}, key string, value int64) int64
- func MapGetInt64Slice(m map[string]interface{}, key string) []int64
- func MapGetIntEx(m map[string]interface{}, key ...string) int
- func MapGetIntOr(m map[string]interface{}, key string, value int) int
- func MapGetMapRaw(m map[string]interface{}, key string) map[string]interface{}
- func MapGetMapRawOr(m map[string]interface{}, key string, value map[string]interface{}) map[string]interface{}
- func MapGetMapStringInt64(m map[string]interface{}, key string) map[string]int64
- func MapGetOr[T any](m map[string]any, key string, value T) T
- func MapGetRaw(m map[string]interface{}, key string) interface{}
- func MapGetRawOr(m map[string]interface{}, key string, value interface{}) interface{}
- func MapGetString(m map[string]interface{}, key string) string
- func MapGetString2(m map[string]string, key string) string
- func MapGetStringByManyFields(m map[string]interface{}, key ...string) string
- func MapGetStringOr(m map[string]interface{}, key string, value string) string
- func MapGetStringOr2(m map[string]string, key string, value string) string
- func MapGetStringSlice(m map[string]interface{}, key string) []string
- func MapQueryToString(values map[string][]string) string
- func MapStringGet(m map[string]string, key string) string
- func MapStringGetOr(m map[string]string, key string, value string) string
- func MapToStruct(input map[string]interface{}, output interface{}) error
- func MarshalHTTPRequest(req *http.Request) ([]byte, error)
- func MarshalIdempotent(v interface{}) ([]byte, error)
- func MatchAllOfGlob(i interface{}, re ...string) bool
- func MatchAllOfRegexp(i interface{}, re ...string) bool
- func MatchAllOfSubString(i interface{}, subStr ...string) bool
- func MatchAnyOfGlob(i interface{}, re ...string) bool
- func MatchAnyOfRegexp(i interface{}, re ...string) bool
- func MatchAnyOfSubString(i interface{}, subStr ...string) bool
- func Max(x, y int) int
- func MaxByte(x, y byte) byte
- func MaxInt64(x, y int64) int64
- func MergeGeneralMap(ms ...map[string]any) map[string]any
- func MergeStringMap(ms ...map[string]string) map[string]string
- func MergeToMap[K comparable, V any](m map[K]V, ms ...map[K]V)
- func Min(x, y int) int
- func MinByte(x, y byte) byte
- func MinInt64(x, y int64) int64
- func Mmh3Hash32(raw []byte) string
- func MustRenderTemplate(templateStr string, data any) string
- func MustUnmarshalJson[T any](raw []byte) *T
- func NeedsURLEncoding(s string) bool
- func NestedSavepointTransaction(st *SavepointTransaction, callback func(*gorm.DB) error) error
- func NetworkByteOrderBytesToUint16(r []byte) uint16
- func NetworkByteOrderUint16ToBytes(i any) []byte
- func NetworkByteOrderUint32ToBytes(i any) []byte
- func NetworkByteOrderUint64ToBytes(i any) []byte
- func NetworkByteOrderUint8ToBytes(i any) []byte
- func NewBlockParser(reader io.Reader) *blockParser
- func NewDebounce(wait float64) func(f func())
- func NewDebounceEx(wait float64, lead bool, tail bool) func(f func())
- func NewDefaultGMTLSConfig() *gmtls.Config
- func NewDefaultHTTPClient() *http.Client
- func NewDefaultHTTPClientWithProxy(proxy string) *http.Client
- func NewDefaultTLSClient(conn net.Conn) *tls.Conn
- func NewDefaultTLSConfig() *tls.Config
- func NewDialer()
- func NewFileLineWriter(file string, flag int, perm fs.FileMode) (*fileLineWriter, error)
- func NewMirrorPipe(count int) ([]*bufpipe.PipeReader, *bufpipe.PipeWriter)
- func NewNetConnFromReadWriter()
- func NewSignalChannel(targetSignal ...os.Signal) chan os.Signal
- func NewThrottle(wait float64) func(f func())
- func NewThrottleEx(wait float64, lead bool, tail bool) func(f func())
- func NotSpaceRune(r rune) bool
- func OpenTempFile(s string) (*os.File, error)
- func OrderedParallelProcess[I any, O any](ctx context.Context, inputCh <-chan I, processFunc func(I) (O, error), ...) <-chan Result[O]
- func OrderedParallelProcessSkipError[I any, O any](ctx context.Context, inputCh <-chan I, processFunc func(I) (O, error), ...) <-chan O
- func ParseAppTag(tag string) map[string]string
- func ParseAppTagToOptions(template any, ext ...map[string]string) (configInfo []*ypb.ThirdPartyAppConfigItemTemplate, err error)
- func ParseCStyleBinaryRawToBytes(raw []byte) []byte
- func ParseHTTPRequestLine(line string) (method, requestURI, proto string, ok bool)
- func ParseHTTPResponseLine(line string) (string, int, string, bool)
- func ParseHostToAddrString(host string) string
- func ParseIPNetToRange(n *net.IPNet) (int64, int64, error)
- func ParseLines(raw string) chan string
- func ParsePortToProtoPort(port int) (string, int)
- func ParseStringToGeneralMap(i any) map[string]any
- func ParseStringToHostPort(raw string) (host string, port int, err error)
- func ParseStringToHosts(raw string) []string
- func ParseStringToHostsWithCallback(raw string, callback func(string) bool)
- func ParseStringToHttpsAndHostname(res string) (bool, string)
- func ParseStringToLines(raw string) []string
- func ParseStringToPorts(ports string) []int
- func ParseStringToRawLines(raw string) []string
- func ParseStringToUrl(s string) *url.URL
- func ParseStringToUrlParams(i interface{}) string
- func ParseStringToUrls(targets ...string) []string
- func ParseStringToUrlsWith3W(sub ...string) []string
- func ParseStringToVisible(raw interface{}) string
- func ParseStringUrlToUrlInstance(s string) (*url.URL, error)
- func ParseStringUrlToWebsiteRootPath(url string) (newURL string)
- func PathExists(path string) (bool, error)
- func PrefixLines(input interface{}, prefix string) string
- func PrefixLinesReader(input io.Reader, prefix string) io.Reader
- func PrefixLinesReaderSimple(input io.Reader, prefix string) io.Reader
- func PrefixLinesWithLineNumbers(input interface{}) string
- func PrefixLinesWithLineNumbersReader(input io.Reader) io.Reader
- func PrettifyJoin(sep string, s ...string) string
- func PrettifyListFromStringSplitEx(Raw string, sep ...string) (targets []string)
- func PrettifyListFromStringSplited(Raw string, sep string) (targets []string)
- func PrettifyShrinkJoin(sep string, s ...string) string
- func PrintCurrentGoroutineRuntimeStack()
- func ProtoHostPort(proto string, host string, port int) string
- func QuoteCSV(s string) string
- func RRFRank[T RRFScoredData](scoredDataList []T, k int) []T
- func RRFRankWithDefaultK[T RRFScoredData](scoredDataList []T) []T
- func RandAlphaNumStringBytes(n int) string
- func RandBytes(n int) []byte
- func RandChoice(a ...string) string
- func RandFloat64() float64
- func RandNumberStringBytes(n int) string
- func RandSample(n int, material ...string) string
- func RandSampleInRange(minLen, maxLen int, material ...string) string
- func RandSecret(n int) string
- func RandStringBytes(n int) string
- func ReadConnUntil(conn net.Conn, timeout time.Duration, sep ...byte) ([]byte, error)
- func ReadConnWithTimeout(r net.Conn, timeout time.Duration) ([]byte, error)
- func ReadDirsRecursivelyCallback(p string, i func(info *FileInfo) bool) error
- func ReadHTTPRequestFromBufioReader(reader *bufio.Reader) (*http.Request, error)
- func ReadHTTPRequestFromBufioReaderOnFirstLine(reader *bufio.Reader, h func(string)) (*http.Request, error)
- func ReadHTTPRequestFromBytes(raw []byte) (*http.Request, error)
- func ReadHTTPResponseFromBufioReader(reader io.Reader, req *http.Request) (*http.Response, error)
- func ReadHTTPResponseFromBufioReaderConn(reader io.Reader, conn net.Conn, req *http.Request) (*http.Response, error)
- func ReadHTTPResponseFromBytes(raw []byte, req *http.Request) (*http.Response, error)
- func ReadLine(reader io.Reader) ([]byte, error)
- func ReadLineEx(reader io.Reader) (string, int64, error)
- func ReadN(reader io.Reader, n int) ([]byte, error)
- func ReadTimeout(r io.Reader, timeout time.Duration) ([]byte, error)
- func ReadUntilStable(reader io.Reader, conn net.Conn, timeout time.Duration, ...) ([]byte, error)
- func ReadUntilStableEx(reader io.Reader, noTimeout bool, conn net.Conn, timeout time.Duration, ...) ([]byte, error)
- func ReadWithContextTickCallback(ctx context.Context, rc io.Reader, callback func([]byte) bool, ...)
- func ReadWithLen(r io.Reader, length int) ([]byte, int)
- func ReaderOnFirstByte(origin io.Reader, onFirstByte func()) io.Reader
- func RealTimeCopy(dst io.Writer, src io.Reader) (int64, error)
- func Regexp2Compile(rawRule string, opts ...int) (string, regexp2.RegexOptions, *regexp2.Regexp, error)
- func RegisterDefaultTLSConfigGenerator(...)
- func RegisterTempFileOpener(dialer FileOpenerType)
- func RemoveBOM(raw []byte) []byte
- func RemoveBOMForString(raw string) string
- func RemoveRepeatIntSlice(slc []int) []int
- func RemoveRepeatIntSliceByLoop(slc []int) []int
- func RemoveRepeatIntSliceByMap(slc []int) []int
- func RemoveRepeatStringSlice(slc []string) []string
- func RemoveRepeatStringSliceByLoop(slc []string) []string
- func RemoveRepeatStringSliceByMap(slc []string) []string
- func RemoveRepeatUintSlice(slc []uint) []uint
- func RemoveRepeatUintSliceByLoop(slc []uint) []uint
- func RemoveRepeatUintSliceByMap(slc []uint) []uint
- func RemoveRepeatedWithStringSlice(slice []string) []string
- func RemoveSliceItem[T comparable](slice []T, s T) []T
- func RemoveUnprintableChars(raw string) string
- func RemoveUnprintableCharsWithReplace(raw string, handle func(i byte) string) string
- func RemoveUnprintableCharsWithReplaceItem(raw string) string
- func RenderTemplate(templateStr string, data any) (string, error)
- func ReplaceLastSubString(s, sub, new string) string
- func ReplaceSliceItem[T comparable](s []T, t T, to T) []T
- func Retry(times int, f func() error) error
- func Retry2(i int, handler func() bool)
- func RetryWithExpBackOff(f func() error) error
- func RetryWithExpBackOffEx(times int, begin int, f func() error) error
- func RuneIndex(s, sub []rune) int
- func RuneRead(r io.Reader, maxChars int) string
- func SSDeepHash(raw []byte) string
- func SafeReflectStructField(refV reflect.Value, field reflect.Value) reflect.Value
- func SafeReflectValue(refV reflect.Value) reflect.Value
- func SaveFile(raw interface{}, filePath string) error
- func SaveTempFile(content interface{}, pattern string) (string, error)
- func SavepointTransactionWithCallback(db *gorm.DB, callback func(st *SavepointTransaction) error) error
- func ScanHTTPHeader(reader io.Reader, headerCallback func(rawHeader []byte), prefix []byte, ...) error
- func ScanHTTPHeaderSimple(reader io.Reader, headerCallback func(rawHeader []byte), prefix []byte) error
- func ScanHTTPHeaderWithHeaderFolding(reader io.Reader, headerCallback func(rawHeader []byte), prefix []byte) error
- func SetContextKey(ctx context.Context, key string, value any) context.Context
- func SetCurrentAbsPath(path ...string)
- func SetSkipBottomFrameNum(skip int)
- func SetSkipFrameNum(skip int)
- func SetUnexportedField(field reflect.Value, value interface{})
- func ShouldRemoveZeroContentLengthHeader(s string) bool
- func ShuffleInt(slice []int)
- func ShuffleString(slice []string)
- func SimHash(raw []byte) uint64
- func SimilarStr(str1 []rune, str2 []rune) (int, int, int)
- func SimplifyUtf8(raw []byte) ([]byte, error)
- func SliceGroup(origin []string, groupSize int) [][]string
- func SnakeString(s string) string
- func SocketTypeUint32ToString(i uint32) string
- func Spinlock(t float64, h func() bool) error
- func SplitHostsToPrivateAndPublic(hosts ...string) (privs, pub []string)
- func StableReader(conn io.Reader, timeout time.Duration, maxSize int) []byte
- func StableReaderEx(conn net.Conn, timeout time.Duration, maxSize int) []byte
- func StandBase64(braw []byte) []byte
- func StarAsWildcardToRegexp(prefix string, target string) (*regexp.Regexp, error)
- func StartCacheLog(ctx context.Context, n int)
- func StringAfter(value string, a string) string
- func StringArrayContains(array []string, element string) bool
- func StringArrayFilterEmpty(array []string) []string
- func StringArrayIndex(array []string, element string) int
- func StringArrayMerge(t ...[]string) []string
- func StringAsFileParams(target interface{}) []byte
- func StringBefore(value string, a string) string
- func StringContainsAllOfSubString(s string, subs []string) bool
- func StringContainsAnyOfSubString(s string, subs []string) bool
- func StringGlobArrayContains(array []string, element string, seps ...rune) bool
- func StringGlobContains(pattern string, element string, seps ...rune) bool
- func StringHasPrefix(s string, prefix []string) bool
- func StringLiteralToAny(s string) any
- func StringLowerAndTrimSpace(raw string) string
- func StringOr(s ...string) string
- func StringReverse(s string) string
- func StringSliceContain(s interface{}, raw string) (result bool)
- func StringSliceContainsAll(s []string, elements ...string) bool
- func StringSplitAndStrip(raw string, sep string) []string
- func StringSubStringArrayContains(array []string, element string) bool
- func StringToAsciiBytes(s string) []byte
- func TCPNoDelay(i net.Conn)
- func TLSConfigSetCheckServerName(tlsConfig *tls.Config, host string) *tls.Config
- func Tick1sWithTimeout(timeout time.Duration, falseToBreak func() bool) (exitedByCondition bool)
- func TickEvery1s(falseToBreak func() bool)
- func TickWithTimeout(timeout, interval time.Duration, falseToBreak func() bool) (exitedByCondition bool)
- func TickWithTimeoutContext(ctx context.Context, timeout, interval time.Duration, falseToBreak func() bool) (exitedByCondition bool)
- func TimeoutContext(d time.Duration) context.Context
- func TimeoutContextSeconds(d float64) context.Context
- func TimestampMs() int64
- func TimestampNano() int64
- func TimestampSecond() int64
- func ToBytes(s string) (uint64, error)
- func ToLowerAndStrip(s string) string
- func ToMapParams(params any) (map[string]any, error)
- func ToMegabytes(s string) (uint64, error)
- func ToNsServer(server string) string
- func TrimFileNameExt(raw string) string
- func TryCloseChannel(i any)
- func TryWriteChannel[T any](c chan T, data T) (ret bool)
- func UTF8Reader(r io.Reader) io.Reader
- func Uint32ToIPv4(ip uint32) net.IP
- func UnquoteANSIC(s string) (string, error)
- func UnquoteANSICWithQuote(s string, quote rune) (string, error)
- func UnquoteCSV(s string) string
- func UnsafeBytesToString(b []byte) string
- func UnsafeStringToBytes(s string) []byte
- func Url2UnEscapeString(u *url.URL) string
- func UrlJoin(origin string, paths ...string) (newURL string, err error)
- func UrlJoinParams(i string, params ...interface{}) string
- func Utf8EncodeBySpecificLength(str []byte, l int) []byte
- func VersionClean(v string) string
- func VersionCompare(v1, v2 string) (int, error)
- func VersionEqual(v1, v2 string) bool
- func VersionGreater(v1, v2 string) bool
- func VersionGreaterEqual(v1, v2 string) bool
- func VersionLess(v1, v2 string) bool
- func VersionLessEqual(v1, v2 string) bool
- func WaitConnect(addr string, timeout float64) error
- func WaitRoutinesFromSlice[T any](arg []T, job func(T))
- func WithCacheCapacity(capacity uint64) cacheExOption
- func WithCacheTTL(ttl ...time.Duration) cacheExOption
- func Wrap(err error, msg string) error
- func Wrapf(err error, format string, args ...interface{}) error
- func ZlibCompress(i interface{}) ([]byte, error)
- func ZlibDeCompress(ret []byte) ([]byte, error)
- type AssertTestingT
- type AsyncFactory
- type AtomicBool
- type AutoFlushWriter
- type Barrier
- type BatchProcessor
- type BatchProcessorConfig
- type BatchProcessorOption
- type BruteDictParser
- type BufferedPeekableConn
- func (b *BufferedPeekableConn) GetBuf() []byte
- func (b *BufferedPeekableConn) GetOriginConn() net.Conn
- func (b *BufferedPeekableConn) GetReader() io.Reader
- func (b *BufferedPeekableConn) Peek(i int) ([]byte, error)
- func (b *BufferedPeekableConn) PeekByte() (byte, error)
- func (b *BufferedPeekableConn) PeekUint16() uint16
- func (b *BufferedPeekableConn) Read(buf []byte) (int, error)
- func (b *BufferedPeekableConn) SetBuf(buf []byte)
- type BufferedPeekableReader
- type BufferedPeekableReaderWriter
- func (b *BufferedPeekableReaderWriter) GetBuf() []byte
- func (b *BufferedPeekableReaderWriter) GetReader() io.Reader
- func (b *BufferedPeekableReaderWriter) Peek(i int) ([]byte, error)
- func (b *BufferedPeekableReaderWriter) Read(buf []byte) (int, error)
- func (b *BufferedPeekableReaderWriter) SetBuf(buf []byte)
- type CRLFtoLFReader
- type Cache
- type CacheEx
- type CacheExWithKey
- func (cache *CacheExWithKey[U, T]) Close()
- func (cache *CacheExWithKey[U, T]) Count() int
- func (cache *CacheExWithKey[U, T]) ForEach(handler func(U, T))
- func (cache *CacheExWithKey[U, T]) Get(key U) (value T, exists bool)
- func (cache *CacheExWithKey[U, T]) GetAll() map[U]T
- func (c *CacheExWithKey[U, T]) GetOrLoad(key U, dataLoader func() (T, error)) (T, error)
- func (cache *CacheExWithKey[U, T]) Purge()
- func (cache *CacheExWithKey[U, T]) Remove(key U) bool
- func (cache *CacheExWithKey[U, T]) Set(key U, value T)
- func (cache *CacheExWithKey[U, T]) SetExpirationCallback(callback expireCallback[U, T])
- func (cache *CacheExWithKey[U, T]) SetNewItemCallback(callback itemCallback[U, T])
- func (cache *CacheExWithKey[U, T]) SetTTL(ttl time.Duration)
- func (cache *CacheExWithKey[U, T]) SetWithTTL(key U, value T, ttl time.Duration)
- func (cache *CacheExWithKey[U, T]) SkipTtlExtensionOnHit(value bool)
- type CacheWithKey
- type CircularQueue
- type Complex
- type CondBarrier
- type CoolDown
- type CoolDownFetcher
- type CountingReadWriter
- type CountingReader
- type CountingWriter
- type CustomWriter
- type DelayWaiter
- type EventWatcherManager
- type EvictionReason
- type FileInfo
- type FileOpenerType
- type Float
- type FloatSecondsDelayWaiter
- type Frame
- type GlobFilter
- type GoroutineLogBuffer
- type GoroutineLogBufferOption
- type GoroutineLogCapture
- type HTTPPacketFilter
- func (j *HTTPPacketFilter) Conditions() []string
- func (h *HTTPPacketFilter) Hash() string
- func (h *HTTPPacketFilter) IsAllowed(req *http.Request, rsp *http.Response) bool
- func (i *HTTPPacketFilter) Remove(name string)
- func (j *HTTPPacketFilter) SetAllowForRequestHeader(header, regexp string)
- func (j *HTTPPacketFilter) SetAllowForRequestPath(regexp string)
- func (j *HTTPPacketFilter) SetAllowForRequestRaw(regexp string)
- func (j *HTTPPacketFilter) SetAllowForResponseHeader(header, regexp string)
- func (j *HTTPPacketFilter) SetAllowForResponseRaw(regexp string)
- func (j *HTTPPacketFilter) SetRejectForRequestHeader(header, regexp string)
- func (j *HTTPPacketFilter) SetRejectForRequestPath(regexp string)
- func (j *HTTPPacketFilter) SetRejectForRequestRaw(regexp string)
- func (j *HTTPPacketFilter) SetRejectForResponseHeader(header, regexp string)
- func (j *HTTPPacketFilter) SetRejectForResponseRaw(regexp string)
- type HostPortClassifier
- type HostsFilter
- type IntHeap
- type Integer
- type LimitRate
- type MatchedRule
- type Once
- type Ordered
- type ParallelProcessConfig
- type ParallelProcessOption
- func WithParallelProcessConcurrency(concurrency int) ParallelProcessOption
- func WithParallelProcessDeferTask(h func()) ParallelProcessOption
- func WithParallelProcessFinishCallback(callback func()) ParallelProcessOption
- func WithParallelProcessStartCallback(callback func()) ParallelProcessOption
- func WithParallelProcessStartTask(h func()) ParallelProcessOption
- type PathForest
- type PathNode
- type PathNodes
- type PortScanTarget
- type PortsFilter
- type ProbeRule
- type ProtoReader
- func (pr *ProtoReader) ReadBool() (bool, error)
- func (pr *ProtoReader) ReadBytes() ([]byte, error)
- func (pr *ProtoReader) ReadFloat32() (float32, error)
- func (pr *ProtoReader) ReadInt32() (int32, error)
- func (pr *ProtoReader) ReadInt64() (int64, error)
- func (pr *ProtoReader) ReadMagicHeader(expectedMagic string) error
- func (pr *ProtoReader) ReadString() (string, error)
- func (pr *ProtoReader) ReadUint32() (uint32, error)
- func (pr *ProtoReader) ReadVarint() (uint64, error)
- type ProtoType
- type ProtoWriter
- func (pw *ProtoWriter) WriteBool(value bool) error
- func (pw *ProtoWriter) WriteBytes(value []byte) error
- func (pw *ProtoWriter) WriteFloat32(value float32) error
- func (pw *ProtoWriter) WriteInt32(value int32) error
- func (pw *ProtoWriter) WriteInt64(value int64) error
- func (pw *ProtoWriter) WriteMagicHeader(magic string) error
- func (pw *ProtoWriter) WriteString(value string) error
- func (pw *ProtoWriter) WriteUint32(value uint32) error
- func (pw *ProtoWriter) WriteVarint(value uint64) error
- type RRFScoredData
- type RankScoredData
- type RequireTestingT
- type Result
- type SSHClient
- func SSHDial(network, addr string, config *ssh.ClientConfig) (*SSHClient, error)
- func SSHDialWithKey(addr, user, keyfile string) (*SSHClient, error)
- func SSHDialWithKeyWithPassphrase(addr, user, keyfile string, passphrase string) (*SSHClient, error)
- func SSHDialWithPasswd(addr, user, passwd string) (*SSHClient, error)
- func (c *SSHClient) Close() error
- func (c *SSHClient) Cmd(cmd string) *SSHRemoteScript
- func (c *SSHClient) CopyLocalFileToRemote(srcFilePath string, dstFilePath string) error
- func (c *SSHClient) CopyRemoteFileToLocal(dstFilePath string, srcFilePath string) error
- func (c *SSHClient) Script(script string) *SSHRemoteScript
- func (c *SSHClient) ScriptFile(fname string) *SSHRemoteScript
- func (c *SSHClient) Shell() *SSHRemoteShell
- func (c *SSHClient) Terminal(config *TerminalConfig) *SSHRemoteShell
- type SSHRemoteScript
- type SSHRemoteScriptType
- type SSHRemoteShell
- type SSHRemoteShellType
- type SafeMap
- type SafeMapWithKey
- func (sm *SafeMapWithKey[K, V]) Clear()
- func (sm *SafeMapWithKey[K, V]) Count() int
- func (sm *SafeMapWithKey[K, V]) Delete(key K)
- func (sm *SafeMapWithKey[K, V]) ForEach(f func(key K, value V) bool)
- func (sm *SafeMapWithKey[K, V]) Get(key K) (V, bool)
- func (sm *SafeMapWithKey[K, V]) GetAll() map[K]V
- func (sm *SafeMapWithKey[K, V]) GetOrLoad(key K, f func() V) V
- func (sm *SafeMapWithKey[K, V]) Have(key K) bool
- func (sm *SafeMapWithKey[K, V]) Set(key K, value V)
- func (sm *SafeMapWithKey[K, V]) Values() []V
- type SavepointTransaction
- func (st *SavepointTransaction) Begin() (*gorm.DB, error)
- func (st *SavepointTransaction) Commit() error
- func (st *SavepointTransaction) GetDB() *gorm.DB
- func (st *SavepointTransaction) GetLevel() int
- func (st *SavepointTransaction) IsInTransaction() bool
- func (st *SavepointTransaction) Rollback() error
- type Set
- func (s *Set[T]) Add(item T)
- func (s *Set[T]) AddList(items []T)
- func (s *Set[T]) And(other *Set[T]) *Set[T]
- func (s *Set[T]) Clear()
- func (s *Set[T]) Diff(other *Set[T]) *Set[T]
- func (s *Set[T]) ForEach(h func(T))
- func (s *Set[T]) Has(item T) bool
- func (s *Set[T]) IsEmpty() bool
- func (s *Set[T]) Len() int
- func (s *Set[T]) List() []T
- func (s *Set[T]) Or(other *Set[T]) *Set[T]
- func (s *Set[T]) Remove(item T)
- type Signed
- type SizedWaitGroup
- type Stack
- func (this *Stack[T]) CreateShadowStack() func()
- func (this *Stack[T]) ForeachStack(f func(T) bool)
- func (this *Stack[T]) Free()
- func (this *Stack[T]) HaveLastStackValue() bool
- func (this *Stack[T]) IsEmpty() bool
- func (this *Stack[T]) LastStackValue() T
- func (this *Stack[T]) Len() int
- func (this *Stack[T]) Peek() T
- func (this *Stack[T]) PeekN(n int) T
- func (this *Stack[T]) Pop() T
- func (this *Stack[T]) PopN(n int) []T
- func (this *Stack[T]) Push(value T)
- func (this *Stack[T]) Size() int
- func (this *Stack[T]) Values(sizes ...int) []T
- type StackTrace
- type StringRoundRobinSelector
- type Switch
- type TerminalConfig
- type TextSplitter
- type TriggerWriter
- type TrimLeftReader
- type Unsigned
- type UserPassPair
- type WebHookServer
- type YakError
Examples ¶
Constants ¶
const ( BYTE = 1 << (10 * iota) KILOBYTE MEGABYTE GIGABYTE TERABYTE PETABYTE EXABYTE )
const ( CommonHeaderStat string = "common-header" HeaderCheckStat = "header-Check" )
const ( AllSepcialChars = ",./<>?;':\"[]{}`~!@#$%^&*()_+-=\\|" LittleChar = "abcdefghijklmnopqrstuvwxyz" BigChar = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" NumberChar = "1234567890" LetterChar = LittleChar + BigChar AlphaNumChar = LittleChar + BigChar + NumberChar PasswordChar = passwordSepcialChars + LittleChar + BigChar + NumberChar )
const CRLF = "\r\n"
const DefaultDateFormat = "2006-01-02"
const DefaultTimeFormat = "2006_01_02-15_04_05"
const DefaultTimeFormat2 = "20060102_15_04_05"
const DefaultTimeFormat3 = "2006/01/02 15:04:05"
Variables ¶
var ( GbkToUtf8 = codec.GbkToUtf8 Utf8ToGbk = codec.Utf8ToGbk )
var BashCompleteScriptTpl = `` /* 1147-byte string literal not displayed */
var DefaultTextSplitter = NewTextSplitter()
var ErrCoolDownSkipCache = Error("Skip cache")
var GBKSafeString = codec.GBKSafeString
var NewBufPipe = bufpipe.NewBufPipe
var NewPipe = bufpipe.NewPipe
var ParseStringToInts = ParseStringToPorts
var ShrinkString = codec.ShrinkString
var ShrinkTextBlock = codec.ShrinkTextBlock
var (
TargetIsLoopback = Errorf("loopback")
)
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 } } }
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 } } }
var ZshCompleteScriptTpl = `` /* 1072-byte string literal not displayed */
Functions ¶
func AppendDefaultPort ¶ added in v1.2.3
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 ¶ added in v1.2.9
func AsciiEqualFold ¶
AsciiEqualFold is strings.EqualFold, ASCII only. It reports whether s and t are equal, ASCII-case-insensitively.
func AsciiToLower ¶
asciiToLower returns the lowercase version of s if s is ASCII and printable, and whether or not it was.
func AttemptWithDelay ¶
func AttemptWithDelayFast ¶
func BufioReadLineString ¶ added in v1.3.0
func ByteCountBinary ¶
func ByteCountDecimal ¶
func ByteSize ¶
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 CalcSSDeepStability ¶
CalcSSDeepStability 使用模糊哈希算法计算多段文本之间的相似度,返回相似度与错误。传入的文本应该为大文本,即长度大于 30 kb。 Example: ``` p, err = str.CalcSSDeepStability(str.RandStr(100000), str.RandStr(100000)) ```
func CalcSha1WithSuffix ¶
func CalcSha256 ¶ added in v1.2.8
func CalcSha256(items ...interface{}) string
func CalcSimHashStability ¶
CalcSimHashStability 使用 SimHash 算法计算多段文本之间的相似度,返回相似度与错误。 Example: ``` p, err = str.CalcSimHashStability("hello", "hello world") // p = 0.96484375 ```
func CalcSimilarity ¶
CalcSimilarity 计算多段文本之间的相似度,根据最长的文本长度选择不同的算法 如果最长的文本长度小于等于 2000,使用文本子串匹配算法 如果最短的文本长度大于等于 30000,使用模糊哈希算法 如果上述算法出现错误,则使用 SimHash 算法 Example: ``` str.CalcSimilarity("hello", "hello world") // 0.625 ```
func CalcTextSubStringStability ¶
CalcTextMaxSubStrStability 使用文本子串匹配算法计算多段文本之间的相似度,返回相似度与错误 Example: ``` p, err = str.CalcTextMaxSubStrStability("hello", "hello world") // p = 0.625 ```
func CallGeneralClose ¶
func CallGeneralClose(closer any)
func CallWithCtx ¶ added in v1.2.9
func CallWithTimeout ¶ added in v1.2.9
func ChanStringToSlice ¶
func CloseConnSafe ¶
func CloseWrite ¶
func CloseWrite(i any)
func ConcatPorts ¶
func ConcurrentCopyDirectory ¶ added in v1.2.9
func ConnExpect ¶
func ContainsAll ¶ added in v1.3.3
func ContainsAll[T comparable](s []T, vals ...T) bool
func ContainsAny ¶ added in v1.3.3
func ContainsAny[T comparable](s []T, vals ...T) bool
func ContainsJSON ¶ added in v1.3.3
func ConvertToStringSlice ¶
func ConvertToStringSlice(raw ...interface{}) (r []string)
func CopyDirectory ¶ added in v1.2.9
func CopyDirectoryEx ¶
func CopyFileEx ¶
func CopyFileEx( source string, destination string, fs fi.FileSystem, ) error
func CopyMapInterface ¶
func CopyMapShallow ¶
func CopyMapShallow[K comparable, V any](originalMap map[K]V) map[K]V
func CreateUTF8StreamMirror ¶
func CutBytesPrefixFunc ¶
func DataVerbose ¶
func DataVerbose(i interface{}) string
func DatePretty ¶ added in v1.3.3
func DatePretty() string
func DatetimePretty ¶
func DatetimePretty() string
func DatetimePretty2 ¶
func DatetimePretty2() string
func DebugMockEchoWs ¶ added in v1.3.1
func DebugMockEchoWss ¶
func DebugMockGMHTTP ¶ added in v1.2.3
func DebugMockHTTP ¶
func DebugMockHTTP2 ¶ added in v1.2.3
func DebugMockHTTPEx ¶ added in v1.2.3
func DebugMockHTTPExContext ¶ added in v1.2.3
func DebugMockHTTPHandlerFunc ¶ added in v1.2.4
func DebugMockHTTPHandlerFunc(handlerFunc http.HandlerFunc) (string, int)
func DebugMockHTTPHandlerFuncContext ¶ added in v1.2.4
func DebugMockHTTPKeepAliveEx ¶ added in v1.3.1
func DebugMockHTTPS ¶ added in v1.2.9
func DebugMockHTTPSEx ¶ added in v1.2.3
func DebugMockHTTPSKeepAliveEx ¶ added in v1.2.7
func DebugMockHTTPServerWithContext ¶ added in v1.2.3
func DebugMockHTTPServerWithContextWithAddress ¶ added in v1.3.0
func DebugMockOnlyGMHTTP ¶ added in v1.3.1
func DebugMockTCP ¶ added in v1.2.7
func DebugMockTCPEx ¶ added in v1.2.7
func DebugMockTCPHandlerFuncContext ¶ added in v1.2.7
func DebugMockWs ¶ added in v1.3.1
func DownloadFile ¶
func DumpHTTPRequest ¶ added in v1.2.6
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 ¶ added in v1.2.6
DumpHTTPResponse dumps http response to bytes if loadBody is true, it will load body to memory
transfer-encoding is a special header
func EnableDebug ¶ added in v1.2.3
func EnableDebug()
func EscapeInvalidUTF8Byte ¶
func ExtractFaviconURL ¶ added in v1.3.1
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 ¶
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 ¶
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 ¶ added in v1.2.3
func ExtractMapValueGeneralMap ¶ added in v1.2.3
func ExtractMapValueInt ¶ added in v1.2.3
func ExtractMapValueRaw ¶ added in v1.2.3
func ExtractMapValueString ¶ added in v1.2.3
func ExtractRawPath ¶
func ExtractStrContextByKeyword ¶
ExtractStrContext 从字符串raw中提取一组关键字res上下文的内容,上下文的长度是512个字符确定。 Example: ``` str.ExtractStrContext("hello yak", ["hello"]) // ["hello yak"] ```
func FileExists ¶
FileExists checks if a file exists and is not a directory.
func FileLineReader ¶
func FilterInterface ¶
func FirstWriter ¶
func FixForParseIP ¶
func FixHTTPRequestForGolangNativeHTTPClient ¶ added in v1.2.6
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 FixHTTPResponseForGolangNativeHTTPClient ¶ added in v1.2.6
func FixJsonRawBytes ¶
func FloatSecondDuration ¶
func FlushWriter ¶ added in v1.2.8
func GetAllFiles ¶
func GetCClassByIPv4 ¶
IPv4ToCClassNetwork 尝试从一个 IPv4 地址中获取 C 类网络地址,并返回错误 Example: ``` network, err = str.IPv4ToCClassNetwork("192.168.0.1") // network = "192.168.0.0/24", err = nil ```
func GetCachedLog ¶ added in v1.2.2
func GetCachedLog() (res []string)
func GetConnectedToHostPortFromHTTPRequest ¶ added in v1.2.6
func GetCurrentDate ¶
func GetCurrentWeekMonday ¶
func GetDefaultGMTLSConfig ¶ added in v1.2.3
func GetDefaultOnlyGMTLSConfig ¶ added in v1.3.1
func GetDefaultTLSConfig ¶ added in v1.2.3
func GetExecutableFromEnv ¶ added in v1.2.8
func GetFileAbsDir ¶
func GetFileAbsPath ¶
func GetFileMd5 ¶
func GetFileModTime ¶
func GetFirstExistedFile ¶
func GetFirstExistedFileE ¶
func GetFirstExistedPath ¶
func GetFirstExistedPathE ¶
func GetHomeDir ¶
func GetHomeDirDefault ¶
func GetLastElement ¶ added in v1.2.8
func GetLastElement[T any](list []T) T
func GetLatestFile ¶
func GetLocalIPAddress ¶
func GetLocalIPAddress() string
func GetLocalIPAddressViaIface ¶
func GetLocalIPAddressViaIface() string
func GetMachineCode ¶
func GetMachineCode() string
func GetRandomAvailableTCPPort ¶
func GetRandomAvailableTCPPort() int
func GetRandomAvailableUDPPort ¶
func GetRandomAvailableUDPPort() int
func GetRandomIPAddress ¶
func GetRandomIPAddress() string
func GetRandomLocalAddr ¶
func GetRandomLocalAddr() string
func GetRangeAvailableTCPPort ¶ added in v1.3.0
func GetSameSubStrings ¶
func GetSameSubStringsRunes ¶
func GetSimpleUri ¶
func GetSortedMapKeys ¶ added in v1.3.1
func GetSystemDnsServers ¶ added in v1.2.3
func GetSystemMachineCode ¶
func GetSystemNameServerList ¶
func GetUnexportedField ¶
func GetWeekStartSunday ¶
func GormTransaction ¶ added in v1.3.0
func GormTransactionReturnDb ¶
func GzipCompress ¶
func GzipDeCompress ¶
func HTTPFrameParser ¶
func HandleStdoutBackgroundForTest ¶ added in v1.3.3
func HostContains ¶ added in v1.3.0
func HostPort ¶
HostPort 将 host 和 port 拼接成 host:port 的形式 Example: ``` str.HostPort("yaklang.com", 443) // yaklang.com:443 ```
func HttpDumpWithBody ¶
func IHasPrefix ¶ added in v1.2.8
func IPv4ToCClassNetwork ¶
func IPv4ToUint64 ¶
func ImportAppConfigToStruct ¶
func InDebugMode ¶
func InDebugMode() bool
func InGithubActions ¶ added in v1.3.1
func InGithubActions() bool
func InTestcase ¶ added in v1.3.1
func InTestcase() bool
func IncludeExcludeChecker ¶ added in v1.3.2
func IndexAllSubstrings ¶
IndexAllSubstrings 只遍历一次查找所有子串位置 返回值是一个二维数组,每个元素是一个[2]int类型匹配结果,其中第一个元素是规则index,第二个元素是索引位置
func InitialCapitalizationEachWords ¶
每个单词首字母大写
func InsertSliceItem ¶ added in v1.2.8
func InsertSliceItem[T comparable](slices []T, e T, index int) []T
func Int64SliceToIntSlice ¶
func IntArrayContains ¶
func IntLargerZeroOr ¶
func IntSliceToInt64Slice ¶
func InterfaceToBoolean ¶ added in v1.2.4
func InterfaceToBytes ¶
func InterfaceToBytes(i interface{}) (result []byte)
func InterfaceToBytesSlice ¶
func InterfaceToBytesSlice(i interface{}) [][]byte
func InterfaceToFloat64 ¶
func InterfaceToGeneralMap ¶
func InterfaceToGeneralMap(params interface{}) (finalResult map[string]interface{})
func InterfaceToInt ¶ added in v1.2.4
func InterfaceToJsonString ¶ added in v1.3.3
func InterfaceToJsonString(i interface{}) string
func InterfaceToMap ¶
func InterfaceToMapInterface ¶
func InterfaceToMapInterface(i interface{}) map[string]interface{}
func InterfaceToQuotedString ¶
func InterfaceToQuotedString(i interface{}) string
func InterfaceToSliceInterface ¶ added in v1.2.2
func InterfaceToSliceInterface(i interface{}) []any
func InterfaceToSliceInterfaceE ¶ added in v1.2.2
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 ¶
isASCIIPrint returns whether s is ASCII and printable according to https://tools.ietf.org/html/rfc20#section-4.2.
func IsCommonHTTPRequestMethod ¶ added in v1.2.7
func IsConnectResetError ¶
func IsErrorNetOpTimeout ¶ added in v1.2.8
func IsGenericTextFile ¶
func IsGenericTextType ¶
func IsGzipBytes ¶
func IsGzipBytes(i interface{}) bool
func IsHttpOrHttpsUrl ¶ added in v1.2.4
func IsIPv4 ¶
IsIPv4 判断字符串是否是 IPv4 地址 Example: ``` str.IsIPv4("::1") // false str.IsIPv4("127.0.0.1") // true ```
func IsIPv6 ¶
IsIPv6 判断字符串是否是 IPv6 地址 Example: ``` str.IsIPv6("::1") // true str.IsIPv6("127.0.0.1") // false ```
func IsLoopback ¶
func IsPlainText ¶
func IsPortAvailable ¶
func IsPortAvailableWithTimeout ¶
IsPortAvailableWithTimeout 使用超时检查端口是否可用
func IsPortAvailableWithUDP ¶
func IsPrivateIP ¶
func IsProtobuf ¶
func IsStrongPassword ¶
IsStrongPassword 判断字符串是否为强密码,强密码的定义为:长度大于8,同时包含特殊字符、小写字母、大写字母、数字 Example: ``` str.IsStrongPassword("12345678") // false str.IsStrongPassword("12345678a") // false str.IsStrongPassword("12345678aA") // false str.IsStrongPassword("12345678aA!") // true ```
func IsTCPPortAvailable ¶
func IsTCPPortOpen ¶
func IsUDPPortAvailable ¶
func IsValidBool ¶ added in v1.3.1
func IsValidCIDR ¶
func IsValidDomain ¶
func IsValidFloat ¶
func IsValidHost ¶ added in v1.3.0
func IsValidHostsRange ¶
func IsValidInteger ¶
func IsValidPortsRange ¶
func IsWebsocketUrl ¶ added in v1.3.0
func JSONStringReader ¶
Example (BasicUsage) ¶
// 基本使用示例
input := `"123"`
reader := JSONStringReader(strings.NewReader(input))
result, _ := io.ReadAll(reader)
fmt.Printf("输入: %s\n输出: %s\n", input, string(result))
Output: 输入: "123" 输出: 123
Example (ComplexEscapes) ¶
// 复杂转义示例
input := `"Hello\x20World\u0021\ud83d\ude0a"`
reader := JSONStringReader(strings.NewReader(input))
result, _ := io.ReadAll(reader)
fmt.Printf("输入: %s\n输出: %s\n", input, string(result))
Output: 输入: "Hello\x20World\u0021\ud83d\ude0a" 输出: Hello World!😊
Example (EscapeSequences) ¶
// 转义序列示例
input := `"abc\n123"`
reader := JSONStringReader(strings.NewReader(input))
result, _ := io.ReadAll(reader)
fmt.Printf("输入: %s\n输出: %s\n", input, string(result))
Output: 输入: "abc\n123" 输出: abc 123
Example (Fallback) ¶
// 回退模式示例
input := `123`
reader := JSONStringReader(strings.NewReader(input))
result, _ := io.ReadAll(reader)
fmt.Printf("输入: %s\n输出: %s\n", input, string(result))
Output: 输入: 123 输出: 123
Example (Malformed) ¶
// 畸形数据自动回退示例
input := `"hello"world"test"`
reader := JSONStringReader(strings.NewReader(input))
result, _ := io.ReadAll(reader)
fmt.Printf("输入: %s\n输出: %s\n", input, string(result))
Output: 输入: "hello"world"test" 输出: "hello"world"test"
Example (Streaming) ¶
// 流式读取示例
input := `"This is a long string that demonstrates streaming capabilities"`
reader := JSONStringReader(strings.NewReader(input))
// 使用小缓冲区分块读取
buf := make([]byte, 10)
var output strings.Builder
for {
n, err := reader.Read(buf)
if n > 0 {
output.Write(buf[:n])
}
if err == io.EOF {
break
}
}
fmt.Printf("流式读取输出: %s\n", output.String())
Output: 流式读取输出: This is a long string that demonstrates streaming capabilities
func JitterBackoff ¶ added in v1.3.2
Return capped exponential backoff with jitter http://www.awsarchitectureblog.com/2015/03/backoff.html
func JoinErrors ¶ added in v1.2.8
func LoopEvery1sBreakUntil ¶
func LoopEvery1sBreakUntil(until func() bool)
func MIMEGlobRuleCheck ¶
func MapGetBool ¶
func MapGetFirstRaw ¶
func MapGetFloat32 ¶
func MapGetFloat32Or ¶
func MapGetFloat64 ¶
func MapGetFloat64Or ¶
func MapGetInt64 ¶
func MapGetInt64Slice ¶
func MapGetIntEx ¶ added in v1.2.2
func MapGetMapRaw ¶
func MapGetMapRawOr ¶
func MapGetMapStringInt64 ¶
func MapGetRawOr ¶
func MapGetString ¶
func MapGetStringByManyFields ¶ added in v1.2.4
func MapGetStringOr ¶
func MapGetStringSlice ¶ added in v1.2.7
func MapQueryToString ¶
map[string][]string to query
func MapToStruct ¶ added in v1.2.6
func MarshalIdempotent ¶ added in v1.3.0
func MatchAllOfGlob ¶
MatchAllOfGlob 尝试将 i 转换为字符串,然后使用 glob 匹配模式匹配,如果所有的glob模式都匹配成功,则返回 true,否则返回 false Example: ``` str.MatchAllOfGlob("abc", "a*", "?b?", "[a-z]?c") // true ```
func MatchAllOfRegexp ¶
MatchAllOfRegexp 尝试将 i 转换为字符串,然后使用正则表达式匹配,如果所有的正则表达式都匹配成功,则返回 true,否则返回 false Example: ``` str.MatchAllOfRegexp("abc", "a.+", ".?b.?", "\\w{2}c") // true ```
func MatchAllOfSubString ¶
MatchAllOfSubString 尝试将 i 转换为字符串,然后判断所有子串 subStr 是否都存在于 i 中,如果都存在则返回 true,否则返回 false,此函数忽略大小写 Example: ``` str.MatchAllOfSubString("abc", "a", "b", "c") // true ```
func MatchAnyOfGlob ¶
MatchAnyOfGlob 尝试将 i 转换为字符串,然后使用 glob 匹配模式匹配,如果任意一个glob模式匹配成功,则返回 true,否则返回 false Example: ``` str.MatchAnyOfGlob("abc", "a*", "??b", "[^a-z]?c") // true ```
func MatchAnyOfRegexp ¶
MatchAnyOfRegexp 尝试将 i 转换为字符串,然后使用正则表达式匹配,如果任意一个正则表达式匹配成功,则返回 true,否则返回 false Example: ``` str.MatchAnyOfRegexp("abc", "a.+", "Ab.?", ".?bC") // true ```
func MatchAnyOfSubString ¶
MatchAnyOfSubString 尝试将 i 转换为字符串,然后判断是否有任意子串 subStr 存在于 i 中,如果有其中一个子串存在于 i 中则返回 true,否则返回 false,此函数忽略大小写 Example: ``` str.MatchAnyOfSubString("abc", "a", "z", "x") // true ```
func MergeToMap ¶
func MergeToMap[K comparable, V any](m map[K]V, ms ...map[K]V)
func Mmh3Hash32 ¶
func MustRenderTemplate ¶
func MustUnmarshalJson ¶ added in v1.2.4
func NeedsURLEncoding ¶ added in v1.3.3
func NestedSavepointTransaction ¶
func NestedSavepointTransaction(st *SavepointTransaction, callback func(*gorm.DB) error) error
NestedSavepointTransaction 嵌套SAVEPOINT事务,可以在已存在的SavepointTransaction中使用
func NetworkByteOrderBytesToUint16 ¶ added in v1.2.4
func NetworkByteOrderUint16ToBytes ¶ added in v1.2.3
func NetworkByteOrderUint32ToBytes ¶ added in v1.2.3
func NetworkByteOrderUint64ToBytes ¶ added in v1.2.3
func NetworkByteOrderUint8ToBytes ¶ added in v1.2.3
func NewBlockParser ¶
func NewDebounce ¶ added in v1.2.8
func NewDebounce(wait float64) func(f func())
func NewDebounceEx ¶
NewDebounceEx 创建一个扩展的防抖函数 wait: 防抖时间间隔 lead: 是否在第一次调用时立即执行 tail: 是否在最后一次调用后延迟执行
func NewDefaultGMTLSConfig ¶
func NewDefaultHTTPClient ¶
func NewDefaultTLSConfig ¶
func NewFileLineWriter ¶ added in v1.3.0
func NewMirrorPipe ¶
func NewMirrorPipe(count int) ([]*bufpipe.PipeReader, *bufpipe.PipeWriter)
func NewNetConnFromReadWriter ¶
func NewNetConnFromReadWriter()
func NewThrottle ¶ added in v1.2.8
func NewThrottle(wait float64) func(f func())
func NewThrottleEx ¶
NewThrottleEx 创建一个扩展的节流函数 wait: 节流时间间隔 lead: 是否在第一次调用时立即执行 tail: 是否在最后一次调用后延迟执行
func NotSpaceRune ¶
func OrderedParallelProcess ¶
func ParseAppTag ¶
func ParseAppTagToOptions ¶
func ParseHTTPRequestLine ¶ added in v1.2.6
ParseHTTPRequestLine parses "GET /foo HTTP/1.1" into its three parts.
func ParseHTTPResponseLine ¶ added in v1.2.6
ParseHTTPResponseLine parses `HTTP/1.1 200 OK` into its ports
func ParseHostToAddrString ¶
func ParseLines ¶
func ParsePortToProtoPort ¶ added in v1.2.6
func ParseStringToGeneralMap ¶ added in v1.2.3
func ParseStringToHostPort ¶
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 ¶
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 ParseStringToHttpsAndHostname ¶ added in v1.2.9
func ParseStringToLines ¶
ParseStringToLines 将字符串按换行符(\n)分割成字符串数组,并去除BOM头和空行 Example: ``` str.ParseStringToLines("Hello World\nHello Yak") // ["Hello World", "Hello Yak"] ```
func ParseStringToPorts ¶
ParseStringToPorts 将字符串解析成 Port 列表, Port 可以以逗号分隔,并且会解析-分隔的范围 Example: ``` str.ParseStringToPorts("10086-10088,23333") // [10086, 10087, 10088, 23333] ```
func ParseStringToRawLines ¶
func ParseStringToUrl ¶ added in v1.2.6
func ParseStringToUrlParams ¶
func ParseStringToUrlParams(i interface{}) string
func ParseStringToUrls ¶
ParseStringToUrls 尝试从给定的字符串(ip,域名)中解析出 URL 列表,补全协议和端口 Example: ``` str.ParseStringToUrls("yaklang.com:443", "https://yaklang.io") // [https://yaklang.com, https://yaklang.io] ```
func ParseStringToUrlsWith3W ¶
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 ¶
ParseStringUrlToUrlInstance 将字符串 url 解析为 URL 结构体并返回错误 Example: ``` str.ParseStringUrlToUrlInstance("https://yaklang.com/abc?a=1") ```
func ParseStringUrlToWebsiteRootPath ¶
ParseStringUrlToWebsiteRootPath 将字符串 url 解析为其根路径的URL Example: ``` str.ParseStringUrlToWebsiteRootPath("https://yaklang.com/abc?a=1") // https://yaklang.com/ ```
func PathExists ¶
func PrefixLines ¶
PrefixLines 为文本的每一行添加指定前缀 对所有输入(包括单行和多行)都添加前缀 Example: ``` str.PrefixLines("hello", "> ") // "> hello" str.PrefixLines("line1\nline2", "> ") // "> line1\n> line2" ```
func PrefixLinesReader ¶
PrefixLinesReader 为文本的每一行添加指定前缀,输入和输出都是 io.Reader 对所有输入(包括单行和多行)都添加前缀,适合处理大文件或流式数据 Example: ``` reader := strings.NewReader("line1\nline2") prefixedReader := str.PrefixLinesReader(reader, "> ") // 读取 prefixedReader 会得到 "> line1\n> line2" ```
func PrefixLinesReaderSimple ¶
PrefixLinesReaderSimple 简化版本的 PrefixLinesReader,总是添加前缀 适合已知是多行文本的场景,使用流式处理
func PrefixLinesWithLineNumbers ¶
func PrefixLinesWithLineNumbers(input interface{}) string
PrefixLinesWithLineNumbers 为文本的每一行添加行号前缀 对所有输入(包括单行和多行)都添加行号前缀 Example: ``` str.PrefixLinesWithLineNumbers("hello") // "1 | hello" str.PrefixLinesWithLineNumbers("line1\nline2") // "1 | line1\n2 | line2" ```
func PrefixLinesWithLineNumbersReader ¶
PrefixLinesWithLineNumbersReader 为文本的每一行添加行号前缀,输入和输出都是 io.Reader 使用流式处理,逐行读取并添加行号前缀,适合处理大文件或流式数据 Example: ``` reader := strings.NewReader("line1\nline2") numberedReader := str.PrefixLinesWithLineNumbersReader(reader) // 读取 numberedReader 会得到 "1 | line1\n2 | line2" ```
func PrettifyJoin ¶ added in v1.2.9
func PrettifyListFromStringSplitEx ¶
PrettifyListFromStringSplitEx split string using given sep if no sep given sep = []string{",", "|"}
func PrettifyListFromStringSplited ¶
SplitAndTrim 将字符串s按照sep分割成字符串切片,并且去除每个字符串的前后空白字符 Example: ``` str.SplitAndTrim(" hello yak ", " ") // ["hello", "yak"] ```
func PrettifyShrinkJoin ¶ added in v1.2.9
func PrintCurrentGoroutineRuntimeStack ¶
func PrintCurrentGoroutineRuntimeStack()
func RRFRank ¶
func RRFRank[T RRFScoredData](scoredDataList []T, k int) []T
func RRFRankWithDefaultK ¶
func RRFRankWithDefaultK[T RRFScoredData](scoredDataList []T) []T
func RandAlphaNumStringBytes ¶
func RandChoice ¶ added in v1.3.1
func RandNumberStringBytes ¶
func RandSample ¶
func RandSampleInRange ¶ added in v1.3.0
func RandSecret ¶
RandSecret 返回在所有可见ascii字符表中随机挑选 n 个字符组成的密码字符串,这个密码经过str.IsStrongPassword验证,即为强密码 Example: ``` str.RandSecret(10) ```
func RandStringBytes ¶
RandStringBytes 返回在大小写字母表中随机挑选 n 个字符组成的字符串 Example: ``` str.RandStr(10) ```
func ReadConnUntil ¶ added in v1.2.8
func ReadConnWithTimeout ¶
func ReadDirsRecursivelyCallback ¶ added in v1.2.9
func ReadHTTPRequestFromBufioReader ¶ added in v1.2.6
func ReadHTTPRequestFromBufioReaderOnFirstLine ¶ added in v1.2.8
func ReadHTTPRequestFromBytes ¶ added in v1.2.6
func ReadHTTPResponseFromBufioReader ¶ added in v1.2.6
func ReadHTTPResponseFromBufioReaderConn ¶ added in v1.2.8
func ReadHTTPResponseFromBytes ¶ added in v1.2.6
func ReadUntilStable ¶ added in v1.2.8
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 ¶ added in v1.2.8
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 Regexp2Compile ¶
func RegisterDefaultTLSConfigGenerator ¶ added in v1.2.3
func RegisterTempFileOpener ¶ added in v1.2.8
func RegisterTempFileOpener(dialer FileOpenerType)
func RemoveBOMForString ¶
func RemoveRepeatStringSlice ¶
RemoveRepeat 移除字符串切片slc中的重复元素 Example: ``` str.RemoveRepeat(["hello", "yak", "hello"]) // ["hello", "yak"] ```
func RemoveSliceItem ¶ added in v1.2.8
func RemoveSliceItem[T comparable](slice []T, s T) []T
func RemoveUnprintableChars ¶
func RenderTemplate ¶
RenderTemplate 渲染模板字符串,支持map和struct作为数据源 template: 模板字符串,使用Go模板语法 data: 数据源,可以是map[string]any或struct实例 返回渲染后的字符串和可能的错误
func ReplaceLastSubString ¶ added in v1.3.2
func ReplaceSliceItem ¶ added in v1.2.8
func ReplaceSliceItem[T comparable](s []T, t T, to T) []T
func Retry2 ¶ added in v1.3.3
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 ¶ added in v1.2.7
func RetryWithExpBackOffEx ¶ added in v1.2.7
func SSDeepHash ¶
CalcSSDeep 计算并返回一段文本的模糊哈希值 Example: ``` str.CalcSSDeep("hello") ```
func SafeReflectStructField ¶ added in v1.2.9
func SaveTempFile ¶ added in v1.3.0
func SavepointTransactionWithCallback ¶
func SavepointTransactionWithCallback(db *gorm.DB, callback func(st *SavepointTransaction) error) error
SavepointTransactionWithCallback 基于SAVEPOINT的事务回调函数
func ScanHTTPHeader ¶
func ScanHTTPHeaderSimple ¶
func SetCurrentAbsPath ¶ added in v1.2.8
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 ¶ added in v1.2.8
func SetSkipBottomFrameNum(skip int)
SetSkipBottomFrameNum set the number of frames to skip from bottom, default is 2
func SetSkipFrameNum ¶ added in v1.2.8
func SetSkipFrameNum(skip int)
SetSkipFrameNum set the number of frames to skip, default is 3
func SetUnexportedField ¶
func ShouldRemoveZeroContentLengthHeader ¶ added in v1.2.6
func ShuffleInt ¶
func ShuffleInt(slice []int)
func ShuffleString ¶
func ShuffleString(slice []string)
func SimilarStr ¶
return the len of longest string both in str1 and str2 and the positions in str1 and str2
func SimplifyUtf8 ¶
SimplifyUtf8 simplify utf8 bytes to utf8 bytes
func SliceGroup ¶
func SnakeString ¶
func SplitHostsToPrivateAndPublic ¶
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 StandBase64 ¶
func StarAsWildcardToRegexp ¶
func StartCacheLog ¶ added in v1.2.2
func StringAfter ¶
func StringArrayContains ¶
func StringArrayFilterEmpty ¶
func StringArrayIndex ¶
func StringArrayMerge ¶
func StringAsFileParams ¶
func StringAsFileParams(target interface{}) []byte
func StringBefore ¶
func StringContainsAnyOfSubString ¶
StringContainsAnyOfSubString 判断字符串s中是否包含subs中的任意一个子串 Example: ``` str.StringContainsAnyOfSubString("hello yak", ["yak", "world"]) // true ```
func StringGlobArrayContains ¶
func StringGlobContains ¶ added in v1.3.1
func StringHasPrefix ¶
func StringLowerAndTrimSpace ¶
LowerAndTrimSpace 将字符串raw转换为小写并去除前后空白字符 Example: ``` str.LowerAndTrimSpace(" Hello ") // "hello" ```
func StringSliceContain ¶
StringSliceContains 判断字符串切片s中是否包含raw,对于非字符串的切片,会尝试将其元素转换为字符串再判断是否包含 Example: ``` str.StringSliceContains(["hello", "yak"], "yak") // true str.StringSliceContains([1, 2, 3], "4") // false ```
func StringSliceContainsAll ¶
StringSliceContainsAll 判断字符串切片s中是否完全包含elements中的所有元素,对于非字符串的切片,会尝试将其元素转换为字符串再判断是否包含 Example: ``` str.StringSliceContainsAll(["hello", "yak"], "hello", "yak") // true str.StringSliceContainsAll(["hello", "yak"], "hello", "yak", "world") // false ```
func StringSplitAndStrip ¶
func StringSubStringArrayContains ¶ added in v1.2.3
func StringToAsciiBytes ¶
func TCPNoDelay ¶
func Tick1sWithTimeout ¶
func TickEvery1s ¶
func TickEvery1s(falseToBreak func() bool)
func TickWithTimeout ¶
func TickWithTimeoutContext ¶
func TimeoutContextSeconds ¶
func TimestampMs ¶
func TimestampMs() int64
func TimestampNano ¶
func TimestampNano() int64
func TimestampSecond ¶
func TimestampSecond() int64
func ToBytes ¶
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 ToMegabytes ¶
ToMegabytes parses a string formatted by ByteSize as megabytes.
func ToNsServer ¶
func TrimFileNameExt ¶
func TryCloseChannel ¶ added in v1.2.2
func TryCloseChannel(i any)
func TryWriteChannel ¶ added in v1.2.9
func UTF8Reader ¶
Example ¶
ExampleUTF8Reader 演示UTF8Reader的基本用法
// 使用io.ReadAll来确保稳定的输出,避免CI环境的性能差异
text := "Hello 世界 🌍"
reader := &mockBytewiseReader{data: []byte(text)}
// 使用UTF8Reader包装
utf8Reader := UTF8Reader(reader)
// 一次性读取所有数据以确保输出一致性
result, err := io.ReadAll(utf8Reader)
if err != nil {
panic(err)
}
fmt.Printf("Complete read: %s\n", string(result))
Output: Complete read: Hello 世界 🌍
Example (BufferSize1) ¶
ExampleUTF8Reader_bufferSize1 演示缓冲区长度为1时失效的行为
text := "测试"
reader := &mockBytewiseReader{data: []byte(text)}
utf8Reader := UTF8Reader(reader)
// 使用1字节缓冲区(UTF8Reader失效)
buf := make([]byte, 1)
fmt.Println("Buffer size 1 (UTF8Reader disabled):")
var result []byte
for {
n, err := utf8Reader.Read(buf)
if n > 0 {
result = append(result, buf[:n]...)
}
if err == io.EOF {
break
}
}
fmt.Printf("Final result: %s\n", string(result))
Output: Buffer size 1 (UTF8Reader disabled): Final result: 测试
Example (RealWorldUsage) ¶
ExampleUTF8Reader_realWorldUsage 展示实际使用场景
// 模拟网络数据流,可能会在UTF-8字符边界处中断
data := "API返回: {\"message\": \"你好,世界!🌍\"}"
// 创建一个按小块读取的reader来模拟网络传输
chunkedReader := &mockChunkedReader{
data: []byte(data),
chunkSize: 3, // 每次只读3字节,会打断UTF-8字符
}
// 使用UTF8Reader确保读取完整的UTF-8字符
utf8Reader := UTF8Reader(chunkedReader)
result, err := io.ReadAll(utf8Reader)
if err != nil {
panic(err)
}
fmt.Printf("完整读取: %s\n", string(result))
Output: 完整读取: API返回: {"message": "你好,世界!🌍"}
Example (SmallBuffer) ¶
ExampleUTF8Reader_smallBuffer 演示小缓冲区的行为
text := "你好"
reader := &mockBytewiseReader{data: []byte(text)}
utf8Reader := UTF8Reader(reader)
// 使用2字节缓冲区(小于UTF-8字符长度)
buf := make([]byte, 2)
fmt.Println("Small buffer (2 bytes) behavior:")
for {
n, err := utf8Reader.Read(buf)
if n > 0 {
// 统一使用复数形式以避免CI环境下的差异
fmt.Printf("Read %d bytes: %v\n", n, buf[:n])
}
if err == io.EOF {
break
}
}
Output: Small buffer (2 bytes) behavior: Read 1 bytes: [228] Read 1 bytes: [189] Read 1 bytes: [160] Read 1 bytes: [229] Read 1 bytes: [165] Read 1 bytes: [189]
func Uint32ToIPv4 ¶
func UnquoteCSV ¶
func UnsafeBytesToString ¶ added in v1.2.6
func UnsafeStringToBytes ¶ added in v1.2.6
func Url2UnEscapeString ¶
func UrlJoin ¶
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 Utf8EncodeBySpecificLength ¶
Utf8EncodeBySpecificLength force encode unicode bytes to utf8 bytes by specific encode length
func VersionClean ¶ added in v1.2.3
func VersionCompare ¶
VersionCompare 泛用形的版本比较,传入(p1,p2 string), p1>p2返回1,nil, p1<p2返回-1,nil, p1==p2返回0,nil, 比较失败返回 -2,err
func VersionEqual ¶
VersionEqual 使用版本比较算法比较版本 v1 与版本 v2,如果 v1 等于 v2 返回 true,否则返回 false Example: ``` str.VersionEqual("3.0", "3.0") // true str.VersionEqual("3.0", "3.0a") // false ```
func VersionGreater ¶
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 ¶
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 ¶
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 ¶
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 WaitRoutinesFromSlice ¶ added in v1.2.6
func WaitRoutinesFromSlice[T any](arg []T, job func(T))
func WithCacheCapacity ¶
func WithCacheCapacity(capacity uint64) cacheExOption
func WithCacheTTL ¶
func ZlibCompress ¶
func ZlibDeCompress ¶
Types ¶
type AssertTestingT ¶
func (AssertTestingT) Errorf ¶
func (a AssertTestingT) Errorf(format string, args ...interface{})
type AsyncFactory ¶
type AsyncFactory[T any] struct { // contains filtered or unexported fields }
func NewAsyncFactory ¶
func NewAsyncFactory[T any]( CTX context.Context, factor func() (T, error), ) *AsyncFactory[T]
func (*AsyncFactory[T]) Close ¶
func (af *AsyncFactory[T]) Close()
func (*AsyncFactory[T]) Get ¶
func (af *AsyncFactory[T]) Get() (T, error)
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) 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
type AutoFlushWriter ¶
type AutoFlushWriter struct {
// contains filtered or unexported fields
}
func WriterAutoFlush ¶
func WriterAutoFlush(writer io.Writer) *AutoFlushWriter
type Barrier ¶
type Barrier struct {
// contains filtered or unexported fields
}
Barrier 表示单个条件屏障,支持重入(类似 WaitGroup)
type BatchProcessor ¶
type BatchProcessor[T any] struct { // contains filtered or unexported fields }
func NewBatchProcessor ¶
func NewBatchProcessor[T any](ctx context.Context, dataChannel <-chan T, opts ...BatchProcessorOption[T]) *BatchProcessor[T]
func (*BatchProcessor[T]) Start ¶
func (b *BatchProcessor[T]) Start()
func (*BatchProcessor[T]) Wait ¶
func (b *BatchProcessor[T]) Wait()
type BatchProcessorConfig ¶
type BatchProcessorConfig[T any] struct { // contains filtered or unexported fields }
type BatchProcessorOption ¶
type BatchProcessorOption[T any] func(*BatchProcessorConfig[T])
func WithBatchProcessorCallBack ¶
func WithBatchProcessorCallBack[T any](cb func([]T)) BatchProcessorOption[T]
func WithBatchProcessorSize ¶
func WithBatchProcessorSize[T any](size int) BatchProcessorOption[T]
func WithBatchProcessorTimeout ¶
func WithBatchProcessorTimeout[T any](timeout int) BatchProcessorOption[T]
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 ¶
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) PeekByte ¶
func (b *BufferedPeekableConn) PeekByte() (byte, error)
func (*BufferedPeekableConn) PeekUint16 ¶
func (b *BufferedPeekableConn) PeekUint16() uint16
func (*BufferedPeekableConn) SetBuf ¶
func (b *BufferedPeekableConn) SetBuf(buf []byte)
type BufferedPeekableReader ¶
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) 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 CRLFtoLFReader ¶
type CRLFtoLFReader struct {
// contains filtered or unexported fields
}
func NewCRLFtoLFReader ¶
func NewCRLFtoLFReader(source io.Reader) *CRLFtoLFReader
NewCRLFtoLFReader 是 CRLFtoLFReader 的构造函数。
type Cache ¶ added in v1.3.1
type Cache[T any] struct { *CacheWithKey[string, T] }
func NewLRUCache ¶
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]) 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]) GetOrLoad ¶
func (c *CacheExWithKey[U, T]) GetOrLoad(key U, dataLoader func() (T, error)) (T, error)
GetOrLoad attempts to retrieve data from the cache for the given key. If the data is not present, or is currently being prepared by another goroutine, it will wait for the data to become ready. If no preparation is in progress, it initiates the data preparation using the provided dataLoader function.
This method provides single-flight behavior: for a given key, the dataLoader function is executed only once concurrently. Multiple concurrent requests for the same key will wait for the single loading operation to complete and then receive its result.
The dataLoader function should be idempotent and thread-safe if it's external, as it will be executed by only one goroutine for a given key at a time.
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 ¶ added in v1.3.2
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 ¶ added in v1.3.2
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]) GetOrLoad ¶
func (cache *CacheWithKey[U, T]) GetOrLoad(key U, dataLoader func() (T, error)) (T, error)
GetOrLoad attempts to retrieve data from the cache for the given key. If the data is not present, it will execute the dataLoader function to load it. This method provides single-flight behavior: for a given key, the dataLoader function is executed only once concurrently. Multiple concurrent requests for the same key will wait for the single loading operation to complete and then receive its result.
func (*CacheWithKey[U, T]) SetExpirationCallback ¶ added in v1.3.2
func (cache *CacheWithKey[U, T]) SetExpirationCallback(callback expireCallbackWithoutReason[U, T])
SetExpirationCallback sets a callback that will be called when an item expires
type CircularQueue ¶ added in v1.2.2
type CircularQueue struct {
// contains filtered or unexported fields
}
func NewCircularQueue ¶ added in v1.2.2
func NewCircularQueue(capacity int) *CircularQueue
func (*CircularQueue) GetElements ¶ added in v1.2.2
func (q *CircularQueue) GetElements() []interface{}
func (*CircularQueue) Push ¶ added in v1.2.2
func (q *CircularQueue) Push(x interface{})
type Complex ¶ added in v1.3.1
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 CondBarrier ¶
type CondBarrier struct {
// contains filtered or unexported fields
}
CondBarrier 条件屏障管理器
func NewCondBarrierContext ¶
func NewCondBarrierContext(ctx context.Context) *CondBarrier
NewCondBarrierContext 创建带上下文的条件屏障管理器
func (*CondBarrier) Cancel ¶
func (cb *CondBarrier) Cancel()
Cancel 取消所有等待,使所有Wait操作立即返回 调用 Cancel 后: - 所有正在等待的 Wait 操作将立即返回 nil(不返回错误) - 新创建的屏障将立即处于完成状态 - 可以安全地多次调用 Cancel
func (*CondBarrier) CreateBarrier ¶
func (cb *CondBarrier) CreateBarrier(name string) *Barrier
CreateBarrier 创建一个命名的屏障条件
func (*CondBarrier) Wait ¶
func (cb *CondBarrier) Wait(names ...string) error
Wait 等待指定的屏障条件完成 参数:
names - 要等待的屏障名称列表,如果为空则等待所有屏障
返回:
error - 只有在上下文超时/取消时才返回错误,Cancel 操作不会返回错误
特性:
- 支持等待尚未创建的屏障(会等待其被创建并完成)
- 支持同时等待多个屏障
- 空参数时等同于 WaitAll()
- 线程安全,可以并发调用
type CoolDown ¶
type CoolDown struct {
// contains filtered or unexported fields
}
func NewCoolDown ¶
type CoolDownFetcher ¶
type CoolDownFetcher struct {
// contains filtered or unexported fields
}
func NewCoolDownFetcher ¶
func NewCoolDownFetcher(timeoutDuration time.Duration) *CoolDownFetcher
type CountingReadWriter ¶ added in v1.3.2
type CountingReadWriter struct {
// contains filtered or unexported fields
}
CountingReadWriter 是一个包装了 io.Writer 的结构体,用于统计写入的字符数
func NewCountingReadWriter ¶ added in v1.3.2
func NewCountingReadWriter(w io.ReadWriter) *CountingReadWriter
NewCountingReadWriter 返回一个新的 CountingWriter,它包装了给定的 io.Writer
func (*CountingReadWriter) Count ¶ added in v1.3.2
func (cw *CountingReadWriter) Count() int
Count 返回到目前为止写入的字符数
type CountingReader ¶ added in v1.3.2
type CountingReader struct {
// contains filtered or unexported fields
}
CountingReader 是一个包装了 io.Reader 的结构体,用于统计读取的字符数
func NewCountingReader ¶ added in v1.3.2
func NewCountingReader(r io.Reader) *CountingReader
NewCountingReader 返回一个新的 CountingReader,它包装了给定的 io.Reader
func (*CountingReader) Count ¶ added in v1.3.2
func (cr *CountingReader) Count() int
Count 返回到目前为止读取的字符数
type CountingWriter ¶ added in v1.3.2
type CountingWriter struct {
// contains filtered or unexported fields
}
CountingWriter 是一个包装了 io.Writer 的结构体,用于统计写入的字符数
func NewCountingWriter ¶ added in v1.3.2
func NewCountingWriter(w io.Writer) *CountingWriter
NewCountingWriter 返回一个新的 CountingWriter,它包装了给定的 io.Writer
func (*CountingWriter) Count ¶ added in v1.3.2
func (cw *CountingWriter) Count() int
Count 返回到目前为止写入的字符数
type CustomWriter ¶ added in v1.2.8
type CustomWriter struct {
// contains filtered or unexported fields
}
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 EventWatcherManager ¶
type EventWatcherManager struct {
// contains filtered or unexported fields
}
func NewEntityWatcher ¶
func (*EventWatcherManager) StopWatch ¶
func (ew *EventWatcherManager) StopWatch(key string)
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 Float ¶ added in v1.3.1
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 ¶ added in v1.2.8
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 ¶ added in v1.2.8
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 ¶ added in v1.2.8
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 GoroutineLogBuffer ¶
type GoroutineLogBuffer struct {
// contains filtered or unexported fields
}
GoroutineLogBuffer multiplexes writes coming from different goroutines into per-goroutine buffers. Attach the current goroutine before running the work you want to capture; flush the buffer when the task completes.
Typical usage:
b := utils.NewGoroutineLogBuffer(os.Stdout)
buf, detach := b.Attach()
defer func() {
b.Flush("task name", buf)
detach()
}()
... // perform work that writes logs via b
func NewGoroutineLogBuffer ¶
func NewGoroutineLogBuffer(fallback io.Writer, opts ...GoroutineLogBufferOption) *GoroutineLogBuffer
NewGoroutineLogBuffer creates a GoroutineLogBuffer that writes to fallback when there is no active buffer for the calling goroutine. If fallback is nil, io.Discard is used.
func (*GoroutineLogBuffer) Attach ¶
func (b *GoroutineLogBuffer) Attach() (*bytes.Buffer, func())
Attach registers a new buffer for the current goroutine and returns it along with a detach function. Detach should be called after the goroutine finishes using the buffer to avoid leaks.
func (*GoroutineLogBuffer) Flush ¶
func (b *GoroutineLogBuffer) Flush(label string, buf *bytes.Buffer, failed bool)
Flush writes the collected buffer to the fallback writer with a simple header/footer so the output stands out in shared logs. When the buffer is configured to only flush failures and `failed` is false, the call is a no-op.
func (*GoroutineLogBuffer) FlushDefault ¶
func (b *GoroutineLogBuffer) FlushDefault()
FlushDefault flushes logs collected from goroutines without explicit attachments. It always flushes regardless of the failed flag.
type GoroutineLogBufferOption ¶
type GoroutineLogBufferOption func(*GoroutineLogBuffer)
func WithGoroutineLogFailedOnly ¶
func WithGoroutineLogFailedOnly(b bool) GoroutineLogBufferOption
WithGoroutineLogFailedOnly toggles the behavior to only flush buffers when the associated work failed.
type GoroutineLogCapture ¶
type GoroutineLogCapture struct {
Buffer *GoroutineLogBuffer
// contains filtered or unexported fields
}
GoroutineLogCapture wires os.Stdout/os.Stderr and the logging subsystems to a GoroutineLogBuffer, enabling per-goroutine log buffering with a single cleanup function.
func StartGoroutineLogCapture ¶
func StartGoroutineLogCapture(fallback io.Writer, opts ...GoroutineLogBufferOption) (*GoroutineLogCapture, error)
StartGoroutineLogCapture creates a new GoroutineLogBuffer (using fallback as the shared writer) and redirects stdout/stderr, the standard log package, and yaklang's common log package into that buffer. Call Stop to restore the previous state.
func (*GoroutineLogCapture) Stop ¶
func (c *GoroutineLogCapture) Stop()
Stop restores stdout/stderr and log outputs back to their original targets. It is safe to call multiple times.
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) 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 (*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 ¶ added in v1.3.3
type IntHeap struct {
// contains filtered or unexported fields
}
func NewIntHeap ¶ added in v1.3.3
type Integer ¶ added in v1.3.1
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 (*LimitRate) WaitUntilNextAsync ¶
func (l *LimitRate) WaitUntilNextAsync()
func (*LimitRate) WaitUntilNextAsyncWithFallback ¶
func (l *LimitRate) WaitUntilNextAsyncWithFallback(f func())
func (*LimitRate) WaitUntilNextSync ¶
func (l *LimitRate) WaitUntilNextSync()
type MatchedRule ¶
func ParseNmapServiceMatchedRule ¶
func ParseNmapServiceMatchedRule(raw []byte) []*MatchedRule
type Once ¶
type Once struct {
// contains filtered or unexported fields
}
Once 是一个可以确保某个操作只执行一次的结构体 相比于 sync.Once,它提供了更灵活的接口,支持 DoOr 方法
func (*Once) Do ¶
func (o *Once) Do(f func())
Do 执行函数 f,确保 f 只会被执行一次 如果已经执行过,则直接返回 如果正在执行,其他 goroutine 会阻塞等待执行完成
type Ordered ¶ added in v1.3.1
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 ParallelProcessConfig ¶
type ParallelProcessConfig struct {
Concurrency int
StartCallback func()
FinishCallback func()
StartTask func()
DeferTask func()
}
type ParallelProcessOption ¶
type ParallelProcessOption func(*ParallelProcessConfig)
func WithParallelProcessConcurrency ¶
func WithParallelProcessConcurrency(concurrency int) ParallelProcessOption
func WithParallelProcessDeferTask ¶
func WithParallelProcessDeferTask(h func()) ParallelProcessOption
func WithParallelProcessFinishCallback ¶
func WithParallelProcessFinishCallback(callback func()) ParallelProcessOption
func WithParallelProcessStartCallback ¶
func WithParallelProcessStartCallback(callback func()) ParallelProcessOption
func WithParallelProcessStartTask ¶
func WithParallelProcessStartTask(h func()) ParallelProcessOption
type PathForest ¶
type PathForest struct {
// contains filtered or unexported fields
}
func GeneratePathTrees ¶
func GeneratePathTrees(l ...string) (*PathForest, error)
func (*PathForest) Output ¶
func (p *PathForest) Output() []*PathNode
func (*PathForest) ReadOnly ¶
func (w *PathForest) ReadOnly()
func (*PathForest) Recursive ¶ added in v1.3.2
func (p *PathForest) Recursive(f func(node2 *PathNode))
type PathNode ¶ added in v1.3.2
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 ¶ added in v1.3.2
type PortScanTarget ¶
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
}
type ProtoReader ¶
type ProtoReader struct {
// contains filtered or unexported fields
}
ProtoReader 提供从 io.Reader 读取 protobuf 编码数据的方法
func NewProtoReader ¶
func NewProtoReader(reader io.Reader) *ProtoReader
NewProtoReader 创建一个新的 ProtoReader
func (*ProtoReader) ReadFloat32 ¶
func (pr *ProtoReader) ReadFloat32() (float32, error)
ReadFloat32 读取一个 float32 值
func (*ProtoReader) ReadInt32 ¶
func (pr *ProtoReader) ReadInt32() (int32, error)
ReadInt32 读取 int32 值
func (*ProtoReader) ReadInt64 ¶
func (pr *ProtoReader) ReadInt64() (int64, error)
ReadInt64 读取 int64 值
func (*ProtoReader) ReadMagicHeader ¶
func (pr *ProtoReader) ReadMagicHeader(expectedMagic string) error
ReadMagicHeader 读取并验证魔数头(固定16字节)
func (*ProtoReader) ReadString ¶
func (pr *ProtoReader) ReadString() (string, error)
ReadString 读取字符串
func (*ProtoReader) ReadUint32 ¶
func (pr *ProtoReader) ReadUint32() (uint32, error)
ReadUint32 读取一个 uint32 值
func (*ProtoReader) ReadVarint ¶
func (pr *ProtoReader) ReadVarint() (uint64, error)
ReadVarint 读取一个 varint 值
type ProtoWriter ¶
type ProtoWriter struct {
// contains filtered or unexported fields
}
ProtoWriter 提供向 io.Writer 写入 protobuf 编码数据的方法
func NewProtoWriter ¶
func NewProtoWriter(writer io.Writer) *ProtoWriter
NewProtoWriter 创建一个新的 ProtoWriter
func (*ProtoWriter) WriteBytes ¶
func (pw *ProtoWriter) WriteBytes(value []byte) error
WriteBytes 写入字节数组
func (*ProtoWriter) WriteFloat32 ¶
func (pw *ProtoWriter) WriteFloat32(value float32) error
WriteFloat32 写入 float32 值
func (*ProtoWriter) WriteInt32 ¶
func (pw *ProtoWriter) WriteInt32(value int32) error
WriteInt32 写入 int32 值
func (*ProtoWriter) WriteInt64 ¶
func (pw *ProtoWriter) WriteInt64(value int64) error
WriteInt64 写入 int64 值
func (*ProtoWriter) WriteMagicHeader ¶
func (pw *ProtoWriter) WriteMagicHeader(magic string) error
WriteMagicHeader 写入魔数头(固定16字节)
func (*ProtoWriter) WriteString ¶
func (pw *ProtoWriter) WriteString(value string) error
WriteString 写入字符串
func (*ProtoWriter) WriteUint32 ¶
func (pw *ProtoWriter) WriteUint32(value uint32) error
WriteUint32 写入 uint32 值
func (*ProtoWriter) WriteVarint ¶
func (pw *ProtoWriter) WriteVarint(value uint64) error
WriteVarint 写入一个 varint 值
type RRFScoredData ¶
type RankScoredData ¶
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 ¶
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 ¶
SSHDialWithPasswd starts a client connection to the given SSH server with passwd authmethod.
func (*SSHClient) Cmd ¶
func (c *SSHClient) Cmd(cmd string) *SSHRemoteScript
Cmd create a command on client
func (*SSHClient) CopyLocalFileToRemote ¶
Copy local file to remote
func (*SSHClient) CopyRemoteFileToLocal ¶
Copy remote file to local
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) 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 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]) Clear ¶
func (sm *SafeMapWithKey[K, V]) Clear()
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]) GetAll ¶
func (sm *SafeMapWithKey[K, V]) GetAll() map[K]V
func (*SafeMapWithKey[K, V]) GetOrLoad ¶
func (sm *SafeMapWithKey[K, V]) GetOrLoad(key K, f func() V) V
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)
func (*SafeMapWithKey[K, V]) Values ¶
func (sm *SafeMapWithKey[K, V]) Values() []V
type SavepointTransaction ¶
type SavepointTransaction struct {
// contains filtered or unexported fields
}
SavepointTransaction 基于SAVEPOINT的多层事务管理器
func NewSavepointTransaction ¶
func NewSavepointTransaction(db *gorm.DB) *SavepointTransaction
NewSavepointTransaction 创建一个新的SAVEPOINT事务管理器
func (*SavepointTransaction) Begin ¶
func (st *SavepointTransaction) Begin() (*gorm.DB, error)
Begin 开始一个新的事务层级
func (*SavepointTransaction) Commit ¶
func (st *SavepointTransaction) Commit() error
Commit 提交当前层级的事务
func (*SavepointTransaction) GetDB ¶
func (st *SavepointTransaction) GetDB() *gorm.DB
GetDB 获取当前的数据库连接
func (*SavepointTransaction) GetLevel ¶
func (st *SavepointTransaction) GetLevel() int
GetLevel 获取当前事务层级
func (*SavepointTransaction) IsInTransaction ¶
func (st *SavepointTransaction) IsInTransaction() bool
IsInTransaction 检查是否在事务中
func (*SavepointTransaction) Rollback ¶
func (st *SavepointTransaction) Rollback() error
Rollback 回滚当前层级的事务
type Set ¶
type Set[T comparable] struct { sync.RWMutex // contains filtered or unexported fields }
func NewSet ¶ added in v1.2.3
func NewSet[T comparable](list ...[]T) *Set[T]
type Signed ¶ added in v1.3.1
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 ¶ added in v1.3.2
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 ¶ added in v1.3.2
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 (*Stack[T]) CreateShadowStack ¶ added in v1.2.8
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]) ForeachStack ¶
func (*Stack[T]) HaveLastStackValue ¶ added in v1.3.0
func (*Stack[T]) LastStackValue ¶ added in v1.3.0
func (this *Stack[T]) LastStackValue() T
type StackTrace ¶ added in v1.2.8
type StackTrace []Frame
StackTrace is stack of Frames from innermost (newest) to outermost (oldest).
func (StackTrace) Format ¶ added in v1.2.8
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 ¶ added in v1.3.1
func (*Switch) WaitUntilOpen ¶ added in v1.3.1
func (c *Switch) WaitUntilOpen()
type TerminalConfig ¶
type TerminalConfig struct {
Term string
Height int
Weight int
Modes ssh.TerminalModes
}
type TextSplitter ¶
func NewTextSplitter ¶
func NewTextSplitter() *TextSplitter
func (*TextSplitter) Split ¶
func (ts *TextSplitter) Split(ctx context.Context, text string) []string
核心分割方法
func (*TextSplitter) SplitReader ¶
type TriggerWriter ¶ added in v1.2.8
type TriggerWriter struct {
// contains filtered or unexported fields
}
func NewTriggerWriter ¶ added in v1.2.8
func NewTriggerWriter(trigger uint64, h func(buffer io.ReadCloser, triggerEvent string)) *TriggerWriter
func NewTriggerWriterEx ¶
func NewTriggerWriterEx(sizeTrigger uint64, timeTrigger time.Duration, h func(buffer io.ReadCloser, triggerEvent string)) *TriggerWriter
func (*TriggerWriter) Close ¶ added in v1.2.8
func (f *TriggerWriter) Close() error
func (*TriggerWriter) GetCount ¶ added in v1.2.8
func (f *TriggerWriter) GetCount() int64
type TrimLeftReader ¶ added in v1.3.2
type TrimLeftReader struct {
// contains filtered or unexported fields
}
TrimLeftReader wraps an io.Reader and trims leading white space from the input.
func NewTrimLeftReader ¶ added in v1.3.2
func NewTrimLeftReader(r io.Reader) *TrimLeftReader
type Unsigned ¶ added in v1.3.1
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 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 ¶ added in v1.2.8
type YakError struct {
// contains filtered or unexported fields
}
func (*YakError) ErrorWithStack ¶ added in v1.3.2
func (YakError) StackTrace ¶ added in v1.2.8
func (s YakError) StackTrace() StackTrace
Source Files
¶
- any.go
- app_config.go
- arp.go
- async_factor.go
- atomic_bool.go
- auto-complete-tpl.go
- base64.go
- batchProcessor.go
- bufpipe.go
- bytes_reader.go
- bytes_utils.go
- bytesfmt.go
- cache.go
- cacheex.go
- cachefunc.go
- cd.go
- cdmap.go
- circular_queue.go
- compare.go
- cond_barrier.go
- connect.go
- counter_readwriter.go
- crawler_utils.go
- debug.go
- debugprint.go
- definitions.go
- delay-chan.go
- delayer_float64.go
- dict-utils.go
- errors.go
- errors_stack.go
- eventwatcher.go
- faviconhash.go
- filetype.go
- fileutil.go
- func_helper.go
- generic.go
- generic_utils.go
- gorm.go
- goroutine_log_buffer.go
- gzip.go
- heap_utils.go
- host_n_port_utils.go
- http2.go
- http_dumper.go
- http_request_builder.go
- http_request_frame_builder.go
- http_response_builder.go
- http_utils.go
- httpfilter.go
- is_private_net.go
- javatime.go
- jitterBackoff.go
- json-string-reader.go
- limit_rate.go
- limited_read.go
- line-reader.go
- line-writer.go
- listener.go
- map.go
- map_op.go
- matcher.go
- math_utils.go
- misc.go
- netparser_utils.go
- nmap-rule-parser.go
- once.go
- ordered_parallel_channel.go
- os_utils.go
- parse-host.go
- peekableConn.go
- protoutils.go
- read_fp.go
- redirect_stdout.go
- regexp2.go
- retry.go
- roundrobin.go
- routine.go
- rrf.go
- signal_chan_utils.go
- sized-waitgroup.go
- slice.go
- ssh_client.go
- stack.go
- str_calc.go
- str_utils.go
- string-op.go
- switch.go
- system_dns_unix.go
- templateutils.go
- text_spliter.go
- threadsafe-set.go
- time.go
- tree.go
- trimleftreader.go
- unsafe.go
- url.go
- url_fix.go
- utf8-reader.go
- utils.go
- validator.go
- version_compare.go
- webhook.go
- writer.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package bizhelper 提供业务逻辑相关的帮助函数和工具 包含表数据的导入导出、分页查询、数据处理等常用功能
|
Package bizhelper 提供业务逻辑相关的帮助函数和工具 包含表数据的导入导出、分页查询、数据处理等常用功能 |
|
grdp/protocol/rfb
rfb.go
|
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. |
|
Package auth is a middleware that authenticates incoming gRPC requests.
|
Package auth is a middleware that authenticates incoming gRPC requests. |
|
Package recovery is a middleware that recovers from panics and logs the panic message.
|
Package recovery is a middleware that recovers from panics and logs the panic message. |
|
gzip-embed
command
|
|
|
Package htmlquery provides extract data from HTML documents using XPath expression.
|
Package htmlquery provides extract data from HTML documents using XPath expression. |
|
Reference: https://github.com/simon-engledew/jsoniter
|
Reference: https://github.com/simon-engledew/jsoniter |
|
cmd
command
|
|
|
Ref: https://github.com/gobwas/ws
|
Ref: https://github.com/gobwas/ws |
|
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 |
|
routewrapper/examples
command
|
|
|
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/astaxie/goredis
|
Reference: https://github.com/astaxie/goredis |
|
Library for Simple Authentication and Security Layer (SASL) defined in RFC 4422.
|
Library for Simple Authentication and Security Layer (SASL) defined in RFC 4422. |
|
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 |
|
cmd
command
|
|
|
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. |