utils

package
v0.0.0-...-b988991 Latest Latest
Warning

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

Go to latest
Published: Apr 16, 2024 License: MIT Imports: 63 Imported by: 0

Documentation

Overview

Package utils for golang tools functions

Package utils for calmwu golang tools

Index

Constants

View Source
const (
	EPOLLIN      = unix.EPOLLIN
	EPOLLOUT     = unix.EPOLLOUT
	EPOLLRDHUP   = unix.EPOLLRDHUP
	EPOLLPRI     = unix.EPOLLPRI
	EPOLLERR     = unix.EPOLLERR
	EPOLLHUP     = unix.EPOLLHUP
	EPOLLET      = unix.EPOLLET
	EPOLLONESHOT = unix.EPOLLONESHOT
)

EpollEvents that are mapped to epoll_event.events possible values.

View Source
const DefaultConcurrency = 256 * 1024

DefaultConcurrency 默认的并发数量

View Source
const (
	HashSeed = 0x2a
)
View Source
const (
	KeyBytesSize = 32
)

https://www.cnblogs.com/si812cn/archive/2009/11/26/1611272.html g是p的原根Diffie-Hellman密钥交换算法的有效性依赖于计算离散对数的难度。简言之,可以如下定义离散对数:首先定义一个素数p的原根,为其各次幂产生从1 到p-1的所有整数根,也就是说,如果a是素数p的一个原根,那么数值 a mod p, a2 mod p, ..., ap-1 mod p 是各不相同的整数,并且以某种排列方式组成了从1到p-1的所有整数。

Variables

View Source
var (
	// ErrClosed is returned by Poller methods to indicate that instance is
	// closed and operation could not be processed.
	ErrClosed = fmt.Errorf("poller instance is closed")

	// ErrRegistered is returned by Poller Start() method to indicate that
	// connection with the same underlying file descriptor was already
	// registered within the poller instance.
	ErrRegistered = fmt.Errorf("file descriptor is already registered in poller instance")

	// ErrNotRegistered is returned by Poller Stop() and Resume() methods to
	// indicate that connection with the same underlying file descriptor was
	// not registered before within the poller instance.
	ErrNotRegistered = fmt.Errorf("file descriptor was not registered before in poller instance")
)
View Source
var (
	ErrNoSliceType = errors.New("not slice type")

	ErrNoFuncType = errors.New("no func type")

	ErrFuncSignatureInvalid = errors.New("func signature invalid")

	ErrFuncInTypeNoMatch = errors.New("func in parameter type not match with slice elem")

	ErrFuncOutTypeNoMatch = errors.New("func out parameter type not match")

	ErrSliceNotPtr = errors.New("slice not ptr")
)
View Source
var (
	ErrGSTTextSectionEmpty  = errors.New(".text section is empty")
	ErrGSTGoPCLNTabNotExist = errors.New("no .gopclntab section")
	ErrGSTGoPCLNTabEmpty    = errors.New(".gopclntab section is empty")
	ErrGSTGoSymTabNotExist  = errors.New("no .gosymtab section")
	ErrGSTGoTooOld          = errors.New("gosymtab: go sym tab too old")
	ErrGSTGoParseFailed     = errors.New("gosymtab: go sym tab parse failed")
	ErrGSTGoFailed          = errors.New("gosymtab: go sym tab failed")
	ErrGSTGoOOB             = errors.New("go table oob")
	ErrGSTGoSymbolsNotFound = errors.New("gosymtab: no go symbols found")
)
View Source
var (
	ErrProcModuleNotSupport       = errors.New("proc module not support")
	ErrProcModuleNotSymbolSection = errors.New("proc module not symbol section")
	ErrProcModuleHasNoSymbols     = errors.New("proc module has no symbols")
)
View Source
var (
	ErrRingBufEmpty       = errors.New("ringbuffer is empty")
	ErrRingBufFull        = errors.New("ringbuffer is full")
	ErrRingSpaceNotEnough = errors.New("ringbuffer space is not enough")
)
View Source
var (
	// DefaultErrCheck error判断和列出上下文
	DefaultErrCheck = errlog.NewLogger(&errlog.Config{

		PrintFunc:          Debugf,
		PrintSource:        true,
		LinesBefore:        2,
		LinesAfter:         1,
		PrintError:         true,
		PrintStack:         false,
		ExitOnDebugSuccess: false,
	})
)
View Source
var (
	ErrNoBuildIDSection = errors.New("build ID section not found")
)
View Source
var ErrNoOne = errors.New("lis.TypeRegister.Get: no one")
View Source
var ErrSemTimeout = errors.New("semaphore: acquire timeout")
View Source
var ErrTooLarge = errors.New("bytes.Buffer: too large")
View Source
var ErrWaitTimeout = errors.New("timed out waiting for the condition")
View Source
var ForeverTestTimeout = time.Second * 30
View Source
var NerverStop <-chan struct{} = make(chan struct{})
View Source
var (

	// SeededSecurely 变量
	SeededSecurely bool
)
View Source
var TypeReg = make(TypeRegister)

TypeReg shared type register

View Source
var (
	ZLog *zap.SugaredLogger
)

Functions

func Apply

func Apply(slice, function interface{}) (interface{}, error)

Apply takes a slice of type []T and a function of type func(T) T.

func ApplyInPlace

func ApplyInPlace(slice, function interface{}) error

ApplyInPlace is like Apply, not allocated slice

func ArrayToString

func ArrayToString(a []int, delim string) string

func Bytes2String

func Bytes2String(b []byte) string

Bytes2String 不要在使用 []byte(string) 或 string([]byte) 这类类型转换 http://www.flysnow.org/2017/07/06/go-in-action-unsafe-pointer.html https://studygolang.com/articles/2909 unsafe.Pointer 类似 void*

func BytesPointer

func BytesPointer(b []byte) unsafe.Pointer

BytesPointer convert byte slice to pointer

func CallStack

func CallStack(skip int) string

CallStack 获得调用堆栈

func CheckDir

func CheckDir(dirPath string) error

CheckDir 检查目录是否存在

func Choose

func Choose(slice, function interface{}) (interface{}, error)

Choose 选择function返回true的元素, 返回一个新分配的slice

func ChooseInPlace

func ChooseInPlace(slice, function interface{}) error

ChooseInPlace 选择function返回true的元素

func CmdExec

func CmdExec(args ...string) (outStr string, errStr string, err error)

CmdExec 执行命令

func CmdExecCaptureAndShow

func CmdExecCaptureAndShow(args ...string) (outStr string, errStr string, err error)

CmdExecCaptureAndShow 捕获输出

func ConvertHashToObj

func ConvertHashToObj(m interface{}, rawVal interface{}, tagName string) error

func ConvertMap2PBStruct

func ConvertMap2PBStruct(v map[string]interface{}) *st.Struct

ConvertMapToPBStruct converts a map[string]interface{} to a ptypes.Struct

func ConvertPBStruct2Map

func ConvertPBStruct2Map(s *st.Struct) (map[string]interface{}, error)

ConvertPBStruct2Map converts a ptypes.Struct to a map[string]interface{}

func ConvertSysCallNR2Str_X86_64

func ConvertSysCallNR2Str_X86_64(syscallNR int) (string, error)

Convert an x86_64 syscall number to a string

func ConvertToFloat64

func ConvertToFloat64(i interface{}, defaultValue float64) (ret float64)

func ConvertToInt

func ConvertToInt(i interface{}, defaultValue int) int

func ConvertToInt64

func ConvertToInt64(i interface{}, defaultValue int64) (ret int64)

func ConvertToString

func ConvertToString(i interface{}, defaultValue string) (ret string)

func Crc16

func Crc16(buf string) uint16

func CreateZapLog

func CreateZapLog(logFullName string, maxSize, maxAge, maxBackups int, compress bool, logLevel zapcore.LevelEnabler,
	callSkip int) *zap.SugaredLogger

CreateZapLog 创建log对象 logFullName: dir/dir/dir/test.log maxSize: megabytes, default = 100 maxAge: 多少天之后变为old file maxBackups: old file备份数量 compress: old file是否压缩tgz logLevel: zapcore.DebugLevel

func CurGoroutineID

func CurGoroutineID() uint64

CurGoroutineID 得到当前的routine id

func DPanic

func DPanic(args ...interface{})

DPanic 封装

func DPanicf

func DPanicf(template string, args ...interface{})

DPanicf 封装

func Debug

func Debug(args ...interface{})

Debug 封装

func Debugf

func Debugf(template string, args ...interface{})

Debugf 封装

func DecryptCipherText

func DecryptCipherText(cipherBlock cipher.Block, cipherText []byte) ([]byte, error)

DecryptCipherText in-place模式

func DeleteModuleSymbolTbl

func DeleteModuleSymbolTbl(buildID string)

DeleteModuleSymbolTbl deletes the module symbol table for the given build ID.

func Drop

func Drop(slice, function interface{}) (interface{}, error)

Drop 选择function返回false的元素, 返回一个新分配的slice

func DropInPlace

func DropInPlace(slice, function interface{}) error

DropInPlace 选择function返回false的元素

func DumpStacks

func DumpStacks()

DumpStacks 输出所有的goroutine的stack

func EncryptPlainText

func EncryptPlainText(cipherBlock cipher.Block, plainText []byte) ([]byte, error)

EncryptPlainText 传入明文,返回密文

func Error

func Error(args ...interface{})

Error 封装

func Errorf

func Errorf(template string, args ...interface{})

Errorf 封装

func Fatal

func Fatal(args ...interface{})

Fatal 封装

func Fatalf

func Fatalf(template string, args ...interface{})

Fatalf 封装

func FindKsym

func FindKsym(addr uint64) (name string, err error)

It uses a binary search to find the symbol name for a given address

func Forever

func Forever(f func(), period time.Duration)

按周期定时调用

func GenerateDHKey

func GenerateDHKey() (*dhkx.DHKey, error)

GenerateDHKey 算出来的ka发送给对方

func GenerateEncryptionKey

func GenerateEncryptionKey(pub []byte, privateKey *dhkx.DHKey) ([]byte, error)

GenerateEncryptionKey 根据对方返回的kb计算加密密钥

func GeneratePassword

func GeneratePassword(minLength int, maxLength int) string

func GenerateRandomID

func GenerateRandomID() string

GenerateRandomID 生成随机uuid

func GenerateRandomPrivateMacAddr

func GenerateRandomPrivateMacAddr() (string, error)

GenerateRandomPrivateMacAddr 生成mac地址

func GenerateTLSConfig

func GenerateTLSConfig() *tls.Config

GenerateTLSConfig 生成tls配置 https://blog.csdn.net/wangshubo1989/article/details/77508738 https://colobu.com/2016/06/07/simple-golang-tls-examples/ InsecureSkipVerify: true,

func GetCallStack

func GetCallStack() string

func GetClientAddrFromGin

func GetClientAddrFromGin(c *gin.Context) string

GetClientAddrFromGin 得到客户端地址

func GetDate

func GetDate() string

func GetDateByLocation

func GetDateByLocation(location *time.Location) string

func GetDateHour

func GetDateHour() string

func GetDateNum

func GetDateNum(location *time.Location) int

func GetDateNum2

func GetDateNum2(now *time.Time) int

func GetDayEndTimeLocal

func GetDayEndTimeLocal() time.Time

func GetDayEndTimeUtc

func GetDayEndTimeUtc() time.Time

func GetHostByteOrder

func GetHostByteOrder() binary.ByteOrder

getHostByteOrder returns the host's native binary.ByteOrder.

func GetIPByIfname

func GetIPByIfname(ifname string) (string, error)

GetIPByIfname 即通过接口名字获取 IP

func GetMonthName

func GetMonthName(location *time.Location) int

func GetMonthlyDayCount

func GetMonthlyDayCount(year, month int) int

GetMonthlyDayCount 计算某年某月的天数

func GetNextDayStartTimeByLocation

func GetNextDayStartTimeByLocation(location *time.Location) time.Time

func GetNextDayStartTimeLocal

func GetNextDayStartTimeLocal() time.Time

func GetNextDayStartTimeUtc

func GetNextDayStartTimeUtc() time.Time

func GetTimeByTz

func GetTimeByTz(tz string) (*time.Time, error)

func GetTimeStampMs

func GetTimeStampMs() string

func GetTimeStampSec

func GetTimeStampSec() string

func GetTypeName

func GetTypeName(obj interface{}) (name1, name2, name3 string)

func GetWeekDay

func GetWeekDay(location *time.Location) int32

func GetWeekName

func GetWeekName(location *time.Location) int

func GinLogger

func GinLogger() gin.HandlerFunc

GinLogger middleware

func GinRecovery

func GinRecovery() gin.HandlerFunc

GinRecovery middleware

func GorillaConnSocketFD

func GorillaConnSocketFD(conn *websocket.Conn) int

func HashStr2Uint32

func HashStr2Uint32(s string) uint32

func HashStr2Uint64

func HashStr2Uint64(s string) uint64

func Info

func Info(args ...interface{})

Info 封装

func Infof

func Infof(template string, args ...interface{})

Infof 封装

func InitDefaultZapLog

func InitDefaultZapLog(logFullName string, logLevel zapcore.LevelEnabler, callSkip int)

InitDefaultZapLog 初始化Zap log

func InitModuleSymbolTblMgr

func InitModuleSymbolTblMgr(capacity int) error

InitModuleSymbolTblMgr initializes the module symbol table manager with the given capacity. It creates a new LRU cache with the specified capacity and sets up the module symbol table manager to use it. If the initialization has already been performed, this function does nothing. Returns an error if there was a problem creating the LRU cache.

func InstallPProf

func InstallPProf(address string) error

InstallPProf 安装pprof

func IsInterfaceNil

func IsInterfaceNil(v interface{}) bool

IsInterfaceNil 判断接口是否为空接口

func IsLoopback

func IsLoopback(ip_str string) (bool, error)

IsLoopback check if a particular IP notation corresponds to a loopback interface.

func IsNil

func IsNil(i interface{}) bool

IsNil 检查interface是否为nil

func IsPrime

func IsPrime(n int64) bool

IsPrime validate N number is prime

func Jitter

func Jitter(duration time.Duration, maxFactor float64) time.Duration

Jitter returns a time.Duration between duration and duration + maxFactor * duration.

This allows clients to avoid converging on periodic behavior. If maxFactor is 0.0, a suggested default value will be chosen.

func JitterUntil

func JitterUntil(f func(), period time.Duration, jitterFactor float64, sliding bool, stopCh <-chan struct{})

If sliding is true, the period is computed after f runs. If it is false then period includes the runtime for f.

func JitterUntilWithContext

func JitterUntilWithContext(ctx context.Context, f func(context.Context), period time.Duration, jitterFactor float64, sliding bool)

在执行后开始计算超时

func Join

func Join(a []interface{}, sep string) string

func JumpHash

func JumpHash(key uint64, numBuckets int) int32

JumpHash Hash consistently chooses a hash bucket number in the range [0, numBuckets) for the given key. numBuckets must >= 1.

func KsymNameExists

func KsymNameExists(name string) bool

Check if a ksym name exists

func LoadKallSyms

func LoadKallSyms() error

It reads the /proc/kallsyms file and stores the symbol name and address in a map

func LocalIpAddrs

func LocalIpAddrs() ([]net.IP, error)

LocalIpAddrs finds the IP addresses of the hosts on which the shipper currently runs on.

func LocalIpAddrsAsStrings

func LocalIpAddrsAsStrings(include_loopbacks bool) ([]string, error)

LocalIpAddrs finds the IP addresses of the hosts on which the shipper currently runs on and returns them as an array of strings.

func MachineID

func MachineID() string

Summary: MachineID is a function that retrieves the machine ID by reading from a list of specified files. It iterates through the list of files and reads the content from the '/proc/1/root' directory. If a valid machine ID is found, it is processed to remove whitespace and dashes before being returned. Parameters:

None

Returns:

string: The machine ID extracted from the files, or an empty string if no valid ID is found.

func MapstructUnPackByJSONTag

func MapstructUnPackByJSONTag(m, rawVal interface{}) error

MapstructUnPackByJSONTag 使用mapstruct进行解包

func Max

func Max(x int, y int) int

func MaxListenerBacklog

func MaxListenerBacklog() int

MaxListenerBacklog 设置 Listen 队列长度

func MaxSubarraySum

func MaxSubarraySum(array []int) int

MaxSubarraySum 输出连续子数组最大合

func MeasureFunc

func MeasureFunc() func()

MeasureFunc 函数的执行耗时测量

func MemUsage

func MemUsage() string

func MergeMap

func MergeMap(a, b map[string]interface{}) map[string]interface{}

MergeMap map合并

func MkDir

func MkDir(dirPath string) error

MkDir 创建目录

func NetConnsocketFD

func NetConnsocketFD(conn net.Conn) int

NetConnsocketFD get fd from net conn

func NewBaseHttpClient

func NewBaseHttpClient(dialTimeout time.Duration, maxIdleConns, maxIdleConnsPerHost int) *http.Client

NewBaseHttpClient Clients are safe for concurrent use by multiple goroutines. https://colobu.com/2016/07/01/the-complete-guide-to-golang-net-http-timeouts/ https://stackoverflow.com/questions/36773837/best-way-to-use-http-client-in-a-concurrent-application

func NewCipherBlock

func NewCipherBlock(encryptionKey []byte) (cipher.Block, error)

func NewDefaultErrCheck

func NewDefaultErrCheck(printFunc func(format string, data ...interface{}), printStack bool)

func NewError

func NewError(args ...interface{}) error

NewError 构建错误对象

func NewSimpleLog

func NewSimpleLog(out io.Writer) *log.Logger

NewSimpleLog 简化一个logger对象

func NewTimeoutHTTPClient

func NewTimeoutHTTPClient(connectTimeout time.Duration, readWritetimeout time.Duration) *http.Client

NewTimeoutHTTPClient 构造一个dialTimeout对象

func NonSlidingUntil

func NonSlidingUntil(f func(), period time.Duration, stopCh <-chan struct{})

在执行前开始计算超时

func NonSlidingUntilWithContext

func NonSlidingUntilWithContext(ctx context.Context, f func(context.Context), period time.Duration)

在执行前开始计算超时,超时时间包括了函数执行时间

func Panic

func Panic(args ...interface{})

Panic 封装

func Panicf

func Panicf(template string, args ...interface{})

Panicf 封装

func ParseUintBytes

func ParseUintBytes(s []byte, base int, bitSize int) (n uint64, err error)

ParseUintBytes is like strconv.ParseUint, but using a []byte.

func PathExist

func PathExist(path string) error

PathExist 判断路径是否存在

func Poll

func Poll(interval, timeout time.Duration, condition ConditionFunc) error

func PollInfinite

func PollInfinite(interval time.Duration, condition ConditionFunc) error

func PostRequest

func PostRequest(url string, data []byte) ([]byte, int, error)

PostRequest post请求返回回应,返回body数据,httpcode,错误

func PrimesInRange

func PrimesInRange(min int64, max int64) (primeArr []int64)

func PrintPerformTimeConsuming

func PrintPerformTimeConsuming(funcName string, startTime time.Time)

PrintPerformTimeConsuming 打印消费时间

func RandStringBytesMaskImpr

func RandStringBytesMaskImpr(n int) string

RandStringBytesMaskImpr 根据掩码生成随机字符串

func RandomBytes

func RandomBytes(size int) ([]byte, error)

RandomBytes 随机生成字节数组

func RandomInt

func RandomInt(n int) int

RandomInt 生成随机整数

func RandomRangeIn

func RandomRangeIn(low, hi int) int

RandomRangeIn trying to generate 8 digit numbers, the range would be (10000000, 99999999)

func Reduce

func Reduce(slice, pairFunction, zero interface{}) (interface{}, error)
 Reduce ...
	func multiply(a, b int) int { return a*b }
	a := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
	factorial := Reduce(a, multiply, 1).(int)

func RegisterWebItf

func RegisterWebItf(webItfPath, httpMethodType string, handlerFunc gin.HandlerFunc, webItfMap WebItfMap)

RegisterWebItf 接口注册

func RegisterWebItfsToGin

func RegisterWebItfsToGin(router *gin.Engine, webItfMap WebItfMap)

RegisterWebItfsToGin 注册到gin

func ReverseString

func ReverseString(s string) string

ReverseString reverse string content

func ReverseWords

func ReverseWords(s string) string

func RunCommand

func RunCommand(name string, args ...string) (stdout string, stderr string, exitCode int)

RunCommand 运行命令

func SeedMathRand

func SeedMathRand()

SeedMathRand 设置随机种子

func SendResponse

func SendResponse(c *gin.Context, data []byte)

SendResponse 回应

func SendResponseToClient

func SendResponseToClient(c *gin.Context, res *ProtoResponseS)

func SetKeepAlive

func SetKeepAlive(fd, secs int) error

SetKeepAlive 设置 KeepAlive tcp_keepalive_time:间隔多久没有发送数据后,就发送一个心跳包 tcp_keepalive_intvl:发送的心跳包如果没有收到 ack,间隔多久后,重新发送 tcp_keepalive_probes:最多发送多少个心跳包没有收到回复后,认为对方挂掉了 https://mcll.top/2019/07/20/tcp-keepalive-in-go/

func SetRecvBuf

func SetRecvBuf(c *net.TCPConn, recvBufSize int) error

SetRecvBuf 设置接收缓冲区

func SetReuseAddrAndPort

func SetReuseAddrAndPort(socketFD int) error

SetReuseAddrAndPort 设置 SO_REUSEADDR 和 reusePort

func SetupSignalHandler

func SetupSignalHandler() context.Context

SetupSignalHandler registers for SIGTERM and SIGINT. A stop channel is returned which is closed on one of these signals. If a second signal is caught, the program is terminated with exit code 1.

func ShortCallerWithClassFunctionEncoder

func ShortCallerWithClassFunctionEncoder(caller zapcore.EntryCaller, enc zapcore.PrimitiveArrayEncoder)

func SockaddrToAddr

func SockaddrToAddr(sa syscall.Sockaddr) net.Addr

SockaddrToAddr 地址类型转换

func String2Bytes

func String2Bytes(s string) []byte

func StringPointer

func StringPointer(s string) unsafe.Pointer

StringPointer 将 string 转变为 Pointer

func TcpConnSocketFD

func TcpConnSocketFD(conn *net.TCPConn) int

func TcpListenerSocketFD

func TcpListenerSocketFD(listener *net.TCPListener) int

func TimeName

func TimeName(t time.Time) string

func TimeTaken

func TimeTaken(t time.Time, name string)

func ToValue

func ToValue(v interface{}) *st.Value

ToValue converts an interface{} to a ptypes.Value

func UdpConnSocketFD

func UdpConnSocketFD(conn *net.UDPConn) int

func Uname

func Uname() (string, string, error)

Summary: Uname is a function that retrieves the hostname and kernel version of the current system by switching to the system's UTS namespace and reading the Utsname struct. Parameters:

None

Returns:

string: The hostname of the current system.
string: The kernel version of the current system.
error: An error, if any, encountered during the retrieval process.

func Until

func Until(f func(), period time.Duration, stopCh <-chan struct{})

一直周期调用,直到 stop chan 被 close

func UntilWithContext

func UntilWithContext(ctx context.Context, f func(context.Context), period time.Duration)

在执行后开始计算超时,超时时间不包括函数执行时间

func WaitFor

func WaitFor(wait WaitFunc, fn ConditionFunc, done <-chan struct{}) error

func Warn

func Warn(args ...interface{})

Warn 封装

func Warnf

func Warnf(template string, args ...interface{})

Warnf 封装

func WritePidFile

func WritePidFile(path string) error

WritePidFile write current process id to file

func ZlibCompress

func ZlibCompress(data []byte, compressLevel int) ([]byte, error)

func ZlibDCompress

func ZlibDCompress(data []byte) ([]byte, error)

Types

type AtomicBool

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

An AtomicBool is an atomic bool

func (*AtomicBool) Get

func (a *AtomicBool) Get() bool

Get gets the value

func (*AtomicBool) Set

func (a *AtomicBool) Set(value bool)

Set sets the value

type BCall

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

BCall 每次请求生成的调用对象

type Backoff

type Backoff struct {
	Duration time.Duration
	Factor   float64
	Jitter   float64
	Steps    int
}

type BarrierCalls

type BarrierCalls interface {
	Do(key string, args interface{}, fn func(args interface{}) (interface{}, error)) (interface{}, bool, error)
}

BarrierCalls 并行访问的接口

func NewBarrierCalls

func NewBarrierCalls() BarrierCalls

type Buffer

type Buffer[T constraints.Unsigned] struct {
	// contains filtered or unexported fields
}

func NewBuffer

func NewBuffer[T constraints.Unsigned](size int) *Buffer[T]

func NewBufferFrom

func NewBufferFrom[T constraints.Unsigned](buf []T) *Buffer[T]

func (*Buffer[T]) Cap

func (b *Buffer[T]) Cap() int

func (*Buffer[T]) Extend

func (b *Buffer[T]) Extend(n int)

func (*Buffer[T]) Grow

func (b *Buffer[T]) Grow(n int)

扩展capacity

func (*Buffer[T]) Len

func (b *Buffer[T]) Len() int

func (*Buffer[T]) Reset

func (b *Buffer[T]) Reset()

func (*Buffer[T]) Slice

func (b *Buffer[T]) Slice() []T

type BuildID

type BuildID struct {
	Type BuildIDType
	ID   string
}

func GetBuildID

func GetBuildID(f *elf.File) (*BuildID, error)

type BuildIDType

type BuildIDType int
const (
	BuildIDTypeUnknown BuildIDType = iota
	BuildIDTypeGNU
	BuildIDTypeGO
)

type ChannelCustomName

type ChannelCustomName generic.Type

ChannelCustomName channel的名字

type ChannelCustomNameChannel

type ChannelCustomNameChannel struct {
	C chan ChannelCustomType
	// contains filtered or unexported fields
}

ChannelCustomNameChannel channel的封装对象

func NewChannelCustomNameChannel

func NewChannelCustomNameChannel(size int) *ChannelCustomNameChannel

NewChannelCustomNameChannel 创建函数

func (*ChannelCustomNameChannel) IsClosed

func (cc *ChannelCustomNameChannel) IsClosed() bool

IsClosed 判断是否被关闭

func (*ChannelCustomNameChannel) Read

func (cc *ChannelCustomNameChannel) Read(block bool) (val ChannelCustomType, ok bool)

Read 读取

func (*ChannelCustomNameChannel) SafeClose

func (cc *ChannelCustomNameChannel) SafeClose()

SafeClose 安全的关闭channel

func (*ChannelCustomNameChannel) SafeSend

func (cc *ChannelCustomNameChannel) SafeSend(value ChannelCustomType, block bool) (ok, closed bool, err error)

SafeSend 安全的发送数据

type ChannelCustomType

type ChannelCustomType generic.Type

ChannelCustomType channel的类型

type Clock

type Clock interface {
	Now() time.Time
	Sleep(time.Duration)
}

type ConditionFunc

type ConditionFunc func() (done bool, err error)

定义函数类型

type Epoll

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

func NewEpoll

func NewEpoll() (*Epoll, error)

func (*Epoll) Add

func (ep *Epoll) Add(conn, connArg interface{}) (int, error)

func (*Epoll) Close

func (ep *Epoll) Close() error

Close close epoll allocate fd and related client fd

func (*Epoll) Modify

func (ep *Epoll) Modify(socketFD int, events EpollEvent) error

Mod sets to events on fd.

func (*Epoll) Remove

func (ep *Epoll) Remove(socketFD int) error

Remove remote fd from epoll

func (*Epoll) Wait

func (ep *Epoll) Wait(milliseconds int) ([]*EpollConn, error)

type EpollConn

type EpollConn struct {
	ConnHolder    interface{}   // golang各种连接对象
	ConnArg       interface{}   // 附加参数
	ConnType      EpollConnType // 连接类型
	TriggerEvents EpollEvent    // EpollEvent返回的事件类型
	SocketFD      int
}

type EpollConnType

type EpollConnType int
const (
	EPOLLConnTypeTCPCONN EpollConnType = iota
	EPOLLConnTypeTCPLISTENER
	EPOLLConnTypeUDP
	EPOLLConnTypeWEBSOCKET
)

type EpollEvent

type EpollEvent uint32

EpollEvent represents epoll events configuration bit mask.

type FactoryReferenceCountable

type FactoryReferenceCountable func(ReferenceCounter) ReferenceCountable

type GoModuleSymbolTbl

type GoModuleSymbolTbl struct {
	ModuleSymbolTbl
	// contains filtered or unexported fields
}

func (*GoModuleSymbolTbl) Count

func (gomst *GoModuleSymbolTbl) Count() int

func (*GoModuleSymbolTbl) GenerateTbl

func (gomst *GoModuleSymbolTbl) GenerateTbl(goSymTabSec *elf.Section, elfF *elf.File) error

func (*GoModuleSymbolTbl) Resolve

func (gomst *GoModuleSymbolTbl) Resolve(addr uint64) (*ResolveSymbol, error)

func (*GoModuleSymbolTbl) Symbols

func (gomst *GoModuleSymbolTbl) Symbols() []*ModuleSymbol

type Group

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

func (*Group) Start

func (g *Group) Start(f func())

func (*Group) StartWithChannel

func (g *Group) StartWithChannel(stopCh <-chan struct{}, f func(stopCh <-chan struct{}))

func (*Group) StartWithContext

func (g *Group) StartWithContext(ctx context.Context, f func(ctx context.Context))

func (*Group) Wait

func (g *Group) Wait()

type Ksym

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

type LRUCache

type LRUCache struct {
	Capacity int
	// 存储要用二维关系,map + 链表
	CacheStorage map[string]*LRUCacheNode

	// 匿名接口
	LRUCacheFunctions
	// contains filtered or unexported fields
}

func NewLRUCache

func NewLRUCache(capacity int) (*LRUCache, error)

NewLRUCache 构建一个LRUCache对象

func (*LRUCache) Clear

func (lc *LRUCache) Clear()

func (*LRUCache) Get

func (lc *LRUCache) Get(key string) (interface{}, error)

通过key获取value,同时调整node位置

func (*LRUCache) Set

func (lc *LRUCache) Set(key string, value interface{})

type LRUCacheFunctions

type LRUCacheFunctions interface {
	Get(key string) (interface{}, error)
	Set(key string, value interface{})
	Clear()
}

type LRUCacheNode

type LRUCacheNode struct {
	Key   string
	Value interface{}
	// contains filtered or unexported fields
}

LRUCacheNode 节点

type ModuleSym

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

type ModuleSymbol

type ModuleSymbol struct {
	Name    string
	Address uint64 // readelf -s ./xxx second column
}

type ModuleSymbolTbl

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

func (*ModuleSymbolTbl) BuildID

func (mst *ModuleSymbolTbl) BuildID() string

func (*ModuleSymbolTbl) ModuleName

func (mst *ModuleSymbolTbl) ModuleName() string

type ModuleSymbolTblMgr

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

type NativeModuleSymbolTbl

type NativeModuleSymbolTbl struct {
	ModuleSymbolTbl
	// contains filtered or unexported fields
}

func (*NativeModuleSymbolTbl) Count

func (nmst *NativeModuleSymbolTbl) Count() int

func (*NativeModuleSymbolTbl) GenerateTbl

func (nmst *NativeModuleSymbolTbl) GenerateTbl(elfF *elf.File) error

func (*NativeModuleSymbolTbl) Resolve

func (nmst *NativeModuleSymbolTbl) Resolve(addr uint64) (*ResolveSymbol, error)

func (*NativeModuleSymbolTbl) Symbols

func (nmst *NativeModuleSymbolTbl) Symbols() []*ModuleSymbol

type NetErrorType

type NetErrorType int

NetErrorType 网络错类型

const (
	NETERR_TYPE_NO                  NetErrorType = iota //
	NETERR_TYPE_DNSERROR                                // *net.DNSError
	NETERR_TYPE_INVALIDADDERROR                         // *net.InvalidAddrError
	NETERR_TYPE_UNKNOWNNETWORKERROR                     // *net.UnknownNetworkError
	NETERR_TYPE_ADDERROR                                // *net.AddrError
	NETERR_TYPE_DNSCONFIGERROR                          // *net.DNSConfigError
	NETERR_TYPE_OS_SYSCALLERROR                         // *os.SyscallError--->syscall.Errno syscall.ECONNREFUSED syscall.ETIMEDOUT
)

func (NetErrorType) String

func (i NetErrorType) String() string

type NoCopy

type NoCopy struct{}

Embed this type into a struct, which mustn't be copied, so `go vet` gives a warning if this struct is copied.

See https://github.com/golang/go/issues/8005#issuecomment-190753527 for details. and also: https://stackoverflow.com/questions/52494458/nocopy-minimal-example

func (*NoCopy) Lock

func (*NoCopy) Lock()

func (*NoCopy) Unlock

func (*NoCopy) Unlock()

type ProcLangType

type ProcLangType int

module 的语言类型

const (
	NativeLangType ProcLangType = iota // c & c++
	GoLangType
	JavaLangType
	PythonLangType
)

type ProcMaps

type ProcMaps struct {
	// pid
	Pid int
	// ProcMapsModule slice
	ModuleList []*ProcMapsModule
	// inode, Determine whether to refresh
	InodeID uint64
	//
	LangType ProcLangType
}

func NewProcMaps

func NewProcMaps(pid int) (*ProcMaps, error)

func (*ProcMaps) Modules

func (pss *ProcMaps) Modules() []*ProcMapsModule

GetModules 返回进程符号表中的所有模块。

func (*ProcMaps) ResolvePC

func (pss *ProcMaps) ResolvePC(pc uint64) (string, uint32, string, error)

ResolvePC 根据程序计数器 (PC) 解析符号信息 如果 ProcMaps 中的模块为空,则返回错误 如果 PC 在模块的地址范围内,则返回符号名称、偏移量和路径名 如果模块类型为 SO,则返回符号名称、偏移量和路径名 如果模块类型为 EXEC,则返回符号名称、偏移量和路径名 如果在解析过程中出现错误,则返回错误

type ProcMapsModule

type ProcMapsModule struct {
	// StartAddr is the starting pc of current mapping.
	StartAddr uint64
	// EndAddr is the ending pc of current mapping.
	EndAddr uint64
	// Perm is the permission of current mapping.
	Perms ProcModulePermissions
	// Offset is the offset of current mapping.
	Offset uint64
	// Dev is the device of current mapping.
	Dev uint64
	// Inode is the inode of current mapping. find / -inum 101417806 or lsof -n -i 'inode=174919'
	Inode    uint64
	Pathname string            // 内存段所属的文件的路径名
	RootFS   string            //
	Type     ProcModuleELFType //
	BuildID  string            //
}

func (*ProcMapsModule) String

func (pmm *ProcMapsModule) String() string

A method of the ProcMapsModule struct. It is used to print the ProcMapsModule struct.

type ProcModuleELFType

type ProcModuleELFType int

module 的 elf 类型

const (
	UNKNOWN ProcModuleELFType = iota
	EXEC
	SO
	VDSO
)

type ProcModulePermissions

type ProcModulePermissions struct {
	// Readable is true if the mapping is readable.
	Readable bool
	// Writable is true if the mapping is writable.
	Writable bool
	// Executable is true if the mapping is executable.
	Executable bool
	// Shared is true if the mapping is shared.
	Shared bool
	// Private is true if the mapping is private.
	Private bool
}

type ProcPartition

type ProcPartition struct {
	Major   uint32
	Minor   uint32
	Dev     uint64
	Blocks  uint64
	DevName string
}

func ProcPartitions

func ProcPartitions() ([]ProcPartition, error)

ProcPartitions reads the /proc/partitions file and returns a slice of ProcPartition structs representing the partitions listed in the file.

type ProtoData

type ProtoData struct {
	InterfaceName string      `json:"InterfaceName"`
	Params        interface{} `json:"Params"`
}

type ProtoFailInfoS

type ProtoFailInfoS struct {
	FailureReason string `json:"FailureReason"`
}

type ProtoRequestHeadS

type ProtoRequestHeadS struct {
	Version    int    `json:"Version"`
	EventID    int    `json:"EventID"`
	TimeStamp  int64  `json:"TimeStamp"`
	CsrfToken  string `json:"CsrfToken"`
	ChannelUID string `json:"ChannelUID"`
	Uin        int    `json:"Uin"`
}

type ProtoRequestS

type ProtoRequestS struct {
	ProtoRequestHeadS
	ReqData ProtoData `json:"ReqData"`
}

func UnpackClientRequest

func UnpackClientRequest(c *gin.Context) (*ProtoRequestS, error)

func UnpackRequest

func UnpackRequest(c *gin.Context) *ProtoRequestS

type ProtoResponseHeadS

type ProtoResponseHeadS struct {
	Version    int             `json:"Version"`
	TimeStamp  int64           `json:"TimeStamp"`
	EventID    int             `json:"EventID"`
	ReturnCode ProtoReturnCode `json:"ReturnCode"`
}

type ProtoResponseS

type ProtoResponseS struct {
	ProtoResponseHeadS
	ResData ProtoData `json:"ResData"`
}

type ProtoReturnCode

type ProtoReturnCode int

type RateLimiter

type RateLimiter interface {
	// TryAccept return true if a token is taken immediately, it return false
	TryAccept() bool
	// Accept return once a token becomes available
	Accept()
	// QPS return QPS of this rate limiter
	QPS() float32
}

func NewTokenBucketRateLimiter

func NewTokenBucketRateLimiter(qps float32, burst int) RateLimiter

NewTokenBucketRateLimiter burst 桶的深度 qps 每秒的请求数量,也就是每秒的令牌生成数量

func NewTokenBucketRateLimiterWithClock

func NewTokenBucketRateLimiterWithClock(qps float32, burst int, c Clock) RateLimiter

type ReferenceCountable

type ReferenceCountable interface {
	SetInstance(i interface{})
	IncrementReferenceCount()
	DecrementReferenceCount()
}

type ReferenceCountedPool

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

ReferenceCountedPool 计数对象池

func NewReferenceCountedPool

func NewReferenceCountedPool(factory FactoryReferenceCountable, reset ResetReferenceCountable) *ReferenceCountedPool

NewReferenceCountedPool 生成一个计数对象池

func (*ReferenceCountedPool) Get

Get 获取对象

func (*ReferenceCountedPool) Stats

func (rcp *ReferenceCountedPool) Stats() map[string]interface{}

Stats 输出pool的统计

type ReferenceCounter

type ReferenceCounter struct {
	Count        *uint32                 `sql:"-" json:"-" yaml:"-"` // 引用计数器
	Destinantion *sync.Pool              `sql:"-" json:"-" yaml:"-"` // 对象池,用来回收用
	Released     *uint32                 `sql:"-" json:"-" yaml:"-"` // 统计累计释放对象次数
	Instance     interface{}             `sql:"-" json:"-" yaml:"-"`
	Reset        func(interface{}) error `sql:"-" json:"-" yaml:"-"` // 用来清理Instance所有成员
	ID           uint32                  `sql:"-" json:"-" yaml:"-"`
}

ReferenceCounter 计数对象类型

func (ReferenceCounter) DecrementReferenceCount

func (rc ReferenceCounter) DecrementReferenceCount()

func (ReferenceCounter) IncrementReferenceCount

func (rc ReferenceCounter) IncrementReferenceCount()

func (*ReferenceCounter) SetInstance

func (rc *ReferenceCounter) SetInstance(i interface{})

type ResetReferenceCountable

type ResetReferenceCountable func(interface{}) error

type ResolveSymbol

type ResolveSymbol struct {
	Name   string
	Offset uint32
}

type RingArrayGrowing

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

RingArrayGrowing is a growing ring array Not thread safe

func NewRingArrayGrowing

func NewRingArrayGrowing(initialSize int) *RingArrayGrowing

NewRingArrayGrowing construct a new RingArrayGrowing instance

func (*RingArrayGrowing) ReadOne

func (r *RingArrayGrowing) ReadOne() (interface{}, bool)

ReadOne consumes first item from the array if it is avaliable, otherwise return false

func (*RingArrayGrowing) WriteOne

func (r *RingArrayGrowing) WriteOne(item interface{})

WriteOne add an item to the end of the array, growing it if it is full

type RingBuffer

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

RingBuffer is a circular buffer

func NewRingBuffer

func NewRingBuffer(initialSize int) *RingBuffer

NewRingBuffer construct a new RingBuffer instance

func (*RingBuffer) Capacity

func (r *RingBuffer) Capacity() int

Capacity return size of buffer

func (*RingBuffer) Free

func (r *RingBuffer) Free() int

Free return length of available bytes to write

func (*RingBuffer) IsEmpty

func (r *RingBuffer) IsEmpty() bool

IsEmpty return this ringbuffer is empty

func (*RingBuffer) IsFull

func (r *RingBuffer) IsFull() bool

IsFull return this ringbuffer is full

func (*RingBuffer) Length

func (r *RingBuffer) Length() int

Length return the length of available read bytes

func (*RingBuffer) Read

func (r *RingBuffer) Read(p []byte) (n int, err error)

Read reads up to len(p) bytes to p

func (*RingBuffer) ReadByte

func (r *RingBuffer) ReadByte() (b byte, err error)

ReadByte read a next byte from the buf or return ErrRingBufEmpty

func (*RingBuffer) Reset

func (r *RingBuffer) Reset()

Reset set read & write pos to zero

func (*RingBuffer) Write

func (r *RingBuffer) Write(p []byte) (n int, err error)

Write write len p bytes to underlying buf

func (*RingBuffer) WriteByte

func (r *RingBuffer) WriteByte(b byte) error

func (*RingBuffer) WriteString

func (r *RingBuffer) WriteString(s string) (n int, err error)

WriteString writes the contents of the string s to buffer, which accepts a slice of bytes.

type Semaphore

type Semaphore chan struct{}

func NewSemaphore

func NewSemaphore(value int) Semaphore

func (Semaphore) Acquire

func (s Semaphore) Acquire(timeout time.Duration) error

Acquire acquires a semaphore with an optional timeout. If a timeout is specified and the semaphore cannot be acquired within the given duration, it returns an error of type `ErrSemTimeout`.

func (Semaphore) Release

func (s Semaphore) Release()

type SortedSliceName

type SortedSliceName generic.Type

SortedSliceName 被排序的slice名

type SortedSliceNameWrap

type SortedSliceNameWrap struct {
	Ssot        []*SortedSliceObjType
	CompareFunc func(left, right *SortedSliceObjType) bool
}

SortedSliceWrap

func (SortedSliceNameWrap) Len

func (ssw SortedSliceNameWrap) Len() int

Len 长度

func (SortedSliceNameWrap) Less

func (ssw SortedSliceNameWrap) Less(i, j int) bool

Less 比较

func (SortedSliceNameWrap) Sort

func (ssw SortedSliceNameWrap) Sort()

Sort 排序

func (SortedSliceNameWrap) Swap

func (ssw SortedSliceNameWrap) Swap(i, j int)

Swap 交换

type SortedSliceObjType

type SortedSliceObjType generic.Type

SortedSliceObjType 被排序的对象类型

type SymbolTable

type SymbolTable interface {
	Resolve(addr uint64) (*ResolveSymbol, error) // 解析地址
	ModuleName() string                          //
	BuildID() string                             //
	Count() int                                  //
	Symbols() []*ModuleSymbol                    //
}

type Timer

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

func NewTimer

func NewTimer() *Timer

func (*Timer) Chan

func (t *Timer) Chan() <-chan time.Time

func (*Timer) Reset

func (t *Timer) Reset(d time.Duration)

func (*Timer) Stop

func (t *Timer) Stop() bool

type TypeRegister

type TypeRegister map[string]reflect.Type

TypeRegister - type register

func (TypeRegister) Get

func (t TypeRegister) Get(name string) (interface{}, error)

Get element of type, if no one - err will be ErrNoOne

func (TypeRegister) Set

func (t TypeRegister) Set(i interface{})

Set registers new type

type WaitFunc

type WaitFunc func(done <-chan struct{}) <-chan struct{}

type WebInterfaceInfo

type WebInterfaceInfo struct {
	HTTPMethodType string
	HandlerFunc    gin.HandlerFunc
}

WebInterfaceInfo web接口方法的描述

type WebItfMap

type WebItfMap map[string]*WebInterfaceInfo

WebItfMap 接口集合

type WorkerHandler

type WorkerHandler func(interface{}) error

WorkerHandler 回调函数类型定义

type WorkerPool

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

WorkerPool 协程池对象

func StartWorkerPool

func StartWorkerPool(workerFunc WorkerHandler, maxWorkersCount int, maxIdelWorkerDuration time.Duration) (*WorkerPool, error)

StartWorkerPool 启动协程池

func (*WorkerPool) Serve

func (wp *WorkerPool) Serve(arg interface{}) bool

Serve 调用

func (*WorkerPool) Stop

func (wp *WorkerPool) Stop()

Stop 停止协程池

Directories

Path Synopsis
Package consulapi for process cousul
Package consulapi for process cousul
Package lifobuffer implements bytes buffer with LIFO order (last-in-first-out)
Package lifobuffer implements bytes buffer with LIFO order (last-in-first-out)
Package redistool for process with redis
Package redistool for process with redis
Package task 任务对象
Package task 任务对象
Package wordfilter 单词过滤
Package wordfilter 单词过滤

Jump to

Keyboard shortcuts

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