utils

package
v0.0.0-...-bf71a7b Latest Latest
Warning

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

Go to latest
Published: Dec 12, 2024 License: Apache-2.0 Imports: 45 Imported by: 11

Documentation

Index

Constants

View Source
const (
	DefTaskPoolCount = 200
	TaskSize         = 1024
	DefReadTimeOut   = 360             // in seconds
	WriteTimeOut     = 60              // in seconds
	HandshakeTimeOut = 5               // in seconds
	MessageBeatLen   = 4 * 1024 * 1024 // in bytes

	PpMinTier = 0
	PpMaxTier = 3
)
View Source
const (
	SIZE_OF_INT8   = 1
	SIZE_OF_UINT8  = 1
	SIZE_OF_INT16  = 2 // in byte
	SIZE_OF_UINT16 = 2 // in byte
	SIZE_OF_INT32  = 4 // in byte
	SIZE_OF_UINT32 = 4 // in byte
	SIZE_OF_INT64  = 8 // in byte
	SIZE_OF_UINT64 = 8 // in byte
)
View Source
const (
	BufferPoolRefillInterval = 3 // in second
)
View Source
const (
	NodeIdBits = uint(8) // node id bits size

)

Variables

View Source
var (
	ErrNotFoundCallBack = errors.New("not found callBack function")
	ErrServerClosed     = errors.New("server has been closed")
	ErrWouldBlock       = errors.New("would block")
)

Functions

func Absolute

func Absolute(path string) (string, error)

func AddRpcLogger

func AddRpcLogger(w io.Writer, id string)

func ByteToString

func ByteToString(p []byte) string

func BytesToInt16

func BytesToInt16(b []byte) int16

func BytesToInt64

func BytesToInt64(b []byte) int64

func BytesToUInt32

func BytesToUInt32(b []byte) uint32

func BytesToUInt64

func BytesToUInt64(b []byte) uint64

func BytesToUint16

func BytesToUint16(b []byte) uint16

func Camel2Snake

func Camel2Snake(s string) string

Camel2Snake eg. HelloWorld => hello_world

func CheckError

func CheckError(err error) bool

CheckError TODO This is a bad way to call error log, as you cannot know where this method is called in your error log This give log line like this : [ERROR]2021/04/13 22:39:11 log.go:150: Fatal error: address 127.0.0.1: missing port in address it always refer to this file and this line If time allows, a better logging tool like "zerolog" can be used to replace these methods.

func ConvertCoronaryUtf8

func ConvertCoronaryUtf8(in string) string

func Crc32IEEE

func Crc32IEEE(data []byte) uint32

func DebugLog

func DebugLog(v ...interface{})

DebugLog calls default logger and output debug log

func DebugLogf

func DebugLogf(template string, v ...interface{})

DebugLog calls default logger and output debug log

func DebugLogfWithCalldepth

func DebugLogfWithCalldepth(calldepth int, template string, v ...interface{})

DebugLog calls default logger and output debug log

func DetailLog

func DetailLog(v ...interface{})

DetailLog calls default logger and output detail log

func DetailLogf

func DetailLogf(template string, v ...interface{})

DetailLog calls default logger and output detail log

func DisableRpcLogger

func DisableRpcLogger(id string)

func DumpTraffic

func DumpTraffic(v ...interface{})

DumpTraffic Log calls default logger and output info log

func ECCSign

func ECCSign(text []byte, prk *ecdsa.PrivateKey) ([]byte, error)

ECCSign signs the given text

func ECCSignBytes

func ECCSignBytes(text, privateKey []byte) ([]byte, error)

ECCSignBytes converts the private key bytes to an ecdsa.PrivateKey and then signs the given text

func ECCVerify

func ECCVerify(text []byte, signature []byte, key *ecdsa.PublicKey) bool

ECCVerify verifies the given signature

func ECCVerifyBytes

func ECCVerifyBytes(text, signature, publicKey []byte) bool

ECCVerifyBytes converts the public key bytes to an ecdsa.PublicKey and then verifies the given signature

func ErrorLog

func ErrorLog(v ...interface{})

ErrorLog call default logger and output error log

func ErrorLogf

func ErrorLogf(template string, v ...interface{})

ErrorLogf call default logger and output error log

func FatalLogfAndExit

func FatalLogfAndExit(exitCode int, template string, v ...interface{})

func FatalLogfAndTerminate

func FatalLogfAndTerminate(template string, v ...interface{})

func FormatError

func FormatError(err error) string

func GenerateRandomNumber

func GenerateRandomNumber(start int, end int, count int) []int

GenerateRandomNumber generate (count) random numbers without repetition in the interval [start, end)

func Get16MD5

func Get16MD5(data string) string

func Get8BitUUID

func Get8BitUUID() string

func GetDiskUsage

func GetDiskUsage(path string) (*disk.UsageStat, error)

func GetLastLinesFromTrafficLog

func GetLastLinesFromTrafficLog(path string, n uint64) []string

func GetMD5

func GetMD5(data string) string

func GetRandomString

func GetRandomString(length int) string

GetRandomString between [0-9a-zA-Z]

func GetSequenceNumberString

func GetSequenceNumberString(number uint64) string

func ImageCommpress

func ImageCommpress(pathStr string) (string, error)

func InitBufferPool

func InitBufferPool(bufferSize, poolSize int)

func InitIdWorker

func InitIdWorker(nodeid uint8) error

func Int16ToBytes

func Int16ToBytes(n int16) []byte

func Int64ToByte

func Int64ToByte(n int64) []byte

func IntToString

func IntToString(i int) string

func IsPoolFull

func IsPoolFull() bool

func LcFirst

func LcFirst(str string) string

LcFirst first letter lower case

func LoadTomlConfig

func LoadTomlConfig(s interface{}, path string) error

func LoadYamlConfig

func LoadYamlConfig(s interface{}, path string) error

func Log

func Log(v ...interface{})

Log calls default logger and output info log

func Logf

func Logf(template string, v ...interface{})

func MergeByte

func MergeByte(b ...[]byte) []byte

func MergeBytes

func MergeBytes(a, b []byte) []byte

func NextSnowFlakeId

func NextSnowFlakeId() (int64, error)

func ParseTomlValue

func ParseTomlValue(data string) (interface{}, error)

func RandFromSeed

func RandFromSeed(seed string) *rand.Rand

func RegisterReqToLogger

func RegisterReqToLogger(reqId int64, terminalId string) bool

func RegisterReqToParentReq

func RegisterReqToParentReq(reqId, parentId int64) bool

func ReleaseBuffer

func ReleaseBuffer(buffer []byte)

func RequestBuffer

func RequestBuffer() []byte

func Snake2Camel

func Snake2Camel(s string) string

Snake2Camel eg. hello_world => HelloWorld

func SplitHostPort

func SplitHostPort(addr string) (net.IP, string, error)

func StrInSlices

func StrInSlices(slices []string, key string) bool

func StringToInt

func StringToInt(s string) (int, error)

func Struct2Map

func Struct2Map(obj interface{}) map[string]interface{}

func UcFirst

func UcFirst(str string) string

UcFirst first letter upper case

func Uint16ToBytes

func Uint16ToBytes(n uint16) []byte

func Uint32ToBytes

func Uint32ToBytes(n uint32) []byte

func Uint64ToBytes

func Uint64ToBytes(n uint64) []byte

func Uint8ToBytes

func Uint8ToBytes(n uint8) []byte

func WarnLog

func WarnLog(v ...interface{})

func WriteTomlConfig

func WriteTomlConfig(data interface{}, filePath string) error

func ZeroId

func ZeroId() int64

Types

type Action

type Action func(ctx context.Context)

type AtomicInt32

type AtomicInt32 int32

AtomicInt32

func CreateAtomicInt32

func CreateAtomicInt32(initialValue int32) *AtomicInt32

CreateAtomicInt32

func (*AtomicInt32) AddAndGetNew

func (a *AtomicInt32) AddAndGetNew(delta int32) int32

AddAndGetNew

func (*AtomicInt32) CompareAndSet

func (a *AtomicInt32) CompareAndSet(expect, update int32) bool

CompareAndSet

func (*AtomicInt32) DecrementAndGetNew

func (a *AtomicInt32) DecrementAndGetNew() int32

DecrementAndGetNew

func (*AtomicInt32) GetAndSetAtomic

func (a *AtomicInt32) GetAndSetAtomic(newValue int32) int32

GetAndSetAtomic

func (*AtomicInt32) GetAtomic

func (a *AtomicInt32) GetAtomic() int32

GetAtomic

func (*AtomicInt32) GetOldAndAdd

func (a *AtomicInt32) GetOldAndAdd(delta int32) int32

GetOldAndAdd

func (*AtomicInt32) GetOldAndDecrement

func (a *AtomicInt32) GetOldAndDecrement() int32

GetOldAndDecrement

func (*AtomicInt32) GetOldAndIncrement

func (a *AtomicInt32) GetOldAndIncrement() int32

GetOldAndIncrement

func (*AtomicInt32) IncrementAndGetNew

func (a *AtomicInt32) IncrementAndGetNew() int32

IncrementAndGetNew

func (*AtomicInt32) SetAtomic

func (a *AtomicInt32) SetAtomic(newValue int32)

SetAtomic

func (*AtomicInt32) String

func (a *AtomicInt32) String() string

type AtomicInt64

type AtomicInt64 int64

AtomicInt64

func CreateAtomicInt64

func CreateAtomicInt64(initialValue int64) *AtomicInt64

CreateAtomicInt64 with initial value

func (*AtomicInt64) AddAndGetNew

func (a *AtomicInt64) AddAndGetNew(delta int64) int64

AddAndGetNew

func (*AtomicInt64) CompareAndSet

func (a *AtomicInt64) CompareAndSet(expect, update int64) bool

CompareAndSet

func (*AtomicInt64) DecrementAndGetNew

func (a *AtomicInt64) DecrementAndGetNew() int64

DecrementAndGetNew

func (*AtomicInt64) GetAndSetAtomic

func (a *AtomicInt64) GetAndSetAtomic(newValue int64) int64

GetAndSetAtomic return current and set new

func (*AtomicInt64) GetAtomic

func (a *AtomicInt64) GetAtomic() int64

GetAtomic

func (*AtomicInt64) GetNewAndSetAtomic

func (a *AtomicInt64) GetNewAndSetAtomic(newValue int64) int64

GetNewAndSetAtomic set new and return new

func (*AtomicInt64) GetOldAndAdd

func (a *AtomicInt64) GetOldAndAdd(delta int64) int64

GetOldAndAdd return current and add delta to atomic

func (*AtomicInt64) GetOldAndDecrement

func (a *AtomicInt64) GetOldAndDecrement() int64

GetOldAndDecrement return current and minus 1 to atomic

func (*AtomicInt64) GetOldAndIncrement

func (a *AtomicInt64) GetOldAndIncrement() int64

GetOldAndIncrement return current and add 1 to atomic

func (*AtomicInt64) IncrementAndGetNew

func (a *AtomicInt64) IncrementAndGetNew() int64

IncrementAndGetNew

func (*AtomicInt64) SetAtomic

func (a *AtomicInt64) SetAtomic(newValue int64)

SetAtomic

func (*AtomicInt64) String

func (a *AtomicInt64) String() string

type AutoCleanMap

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

func NewAutoCleanMap

func NewAutoCleanMap(delay time.Duration) *AutoCleanMap

func (*AutoCleanMap) Delete

func (m *AutoCleanMap) Delete(key interface{})

func (*AutoCleanMap) HashKey

func (m *AutoCleanMap) HashKey(key interface{}) bool

func (*AutoCleanMap) Load

func (m *AutoCleanMap) Load(key interface{}) (interface{}, bool)

func (*AutoCleanMap) LoadWithoutPushDelete

func (m *AutoCleanMap) LoadWithoutPushDelete(key interface{}) (interface{}, bool)

func (*AutoCleanMap) Store

func (m *AutoCleanMap) Store(key, value interface{})

type AutoCleanUnsafeMap

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

func NewAutoCleanUnsafeMap

func NewAutoCleanUnsafeMap(delay time.Duration) *AutoCleanUnsafeMap

func (*AutoCleanUnsafeMap) Delete

func (m *AutoCleanUnsafeMap) Delete(key interface{})

func (*AutoCleanUnsafeMap) HashKey

func (m *AutoCleanUnsafeMap) HashKey(key interface{}) bool

func (*AutoCleanUnsafeMap) Len

func (m *AutoCleanUnsafeMap) Len() int

func (*AutoCleanUnsafeMap) Load

func (m *AutoCleanUnsafeMap) Load(key interface{}) (interface{}, bool)

func (*AutoCleanUnsafeMap) Store

func (m *AutoCleanUnsafeMap) Store(key, value interface{})

type CombinedLogger

type CombinedLogger struct {
	// contains filtered or unexported fields
}
var MyLogger *CombinedLogger
var TrafficLogger *CombinedLogger

func NewDefaultLogger

func NewDefaultLogger(filepath string, enableStd, enableFile bool) *CombinedLogger

func NewLogger

func NewLogger(filepath string, enableStd, enableFile bool) *CombinedLogger

func NewTrafficLogger

func NewTrafficLogger(filePath string, enableStd, enableFile bool) *CombinedLogger

func (*CombinedLogger) ErrorLog

func (l *CombinedLogger) ErrorLog(v ...interface{})

func (*CombinedLogger) Log

func (l *CombinedLogger) Log(level LogLevel, v ...interface{})

func (*CombinedLogger) LogDepth

func (l *CombinedLogger) LogDepth(level LogLevel, calldepth int, v ...interface{})

func (*CombinedLogger) SetEnablefile

func (l *CombinedLogger) SetEnablefile(b bool)

func (*CombinedLogger) SetEnablestd

func (l *CombinedLogger) SetEnablestd(b bool)

func (*CombinedLogger) SetLogLevel

func (l *CombinedLogger) SetLogLevel(lv LogLevel)

SetLogLevel

type ErrUndefined

type ErrUndefined int32

ErrUndefined

func (ErrUndefined) Error

func (e ErrUndefined) Error() string

type Event

type Event struct {
	Id   uint64
	Name string
}

type Fsm

type Fsm struct {
	StateTransTable [][]TransitionItem
	// contains filtered or unexported fields
}

func (*Fsm) GetState

func (fsm *Fsm) GetState() State

func (*Fsm) InitFsm

func (fsm *Fsm) InitFsm(stateList []State, eventList []Event, f func(f *Fsm), initStateId uint64) error

func (*Fsm) RunFsm

func (fsm *Fsm) RunFsm(ctx context.Context, e uint64)

type IdWorker

type IdWorker struct {
	// contains filtered or unexported fields
}
var MyIdWorker *IdWorker

func NewIdWorker

func NewIdWorker(NodeId int64) (*IdWorker, error)

NewIdWorker new a snowflake id generator object.

func (*IdWorker) NextId

func (id *IdWorker) NextId() (int64, error)

NextId get a snowflake id.

func (*IdWorker) NextIds

func (id *IdWorker) NextIds(num int) ([]int64, error)

NextIds get snowflake ids.

type LimitRate

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

func (*LimitRate) GetRate

func (l *LimitRate) GetRate() uint64

func (*LimitRate) Limit

func (l *LimitRate) Limit() bool

func (*LimitRate) SetRate

func (l *LimitRate) SetRate(r uint64)

type LogLevel

type LogLevel int
const (
	Detail LogLevel = 1
	Debug  LogLevel = 10
	Info   LogLevel = 20
	Warn   LogLevel = 30
	Error  LogLevel = 40
	Fatal  LogLevel = 50
)

log level

type LogMsg

type LogMsg struct {
	Msg string `json:"msg"`
}

type Logger

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

func GetRpcLoggerByReqId

func GetRpcLoggerByReqId(id int64) *Logger

func GetRpcLoggerByTerminalId

func GetRpcLoggerByTerminalId(id string) *Logger

func (*Logger) GetLevelString

func (l *Logger) GetLevelString(lv LogLevel) string

GetLevelString

func (*Logger) Log

func (l *Logger) Log(level LogLevel, v ...interface{})

func (*Logger) LogDepth

func (l *Logger) LogDepth(level LogLevel, calldepth int, v ...interface{})

func (*Logger) SetEnabled

func (l *Logger) SetEnabled(b bool)

func (*Logger) SetLogLevel

func (l *Logger) SetLogLevel(lv LogLevel)

SetLogLevel

type MyUnsafeValue

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

type MyValue

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

type State

type State struct {
	Id   uint64
	Name string
}

type SysInfo

type SysInfo struct {
	DiskSize   uint64
	FreeDisk   uint64
	MemorySize uint64
	OSInfo     string
	CPUInfo    string
	MacAddress string
}

SysInfo

func GetSysInfo

func GetSysInfo(diskPath string) *SysInfo

GetSysInfo

type TransitionItem

type TransitionItem struct {
	NewState uint64
	Action   Action
}

type Url

type Url struct {
	Scheme   string
	Host     string
	Port     string
	Path     string
	RawQuery string
}

func ParseUrl

func ParseUrl(url string) (*Url, error)

func (*Url) String

func (url *Url) String(withScheme, withPort, withPath, withRawQuery bool) string

type WeightedItem

type WeightedItem interface {
	Weight() float64
}

func WeightedRandomSelect

func WeightedRandomSelect(items []WeightedItem, seed string) (int, WeightedItem)

WeightedRandomSelect selects a random item from the list (with probability proportional to item weight). If the seed is empty, it will use a cryptographically secure random seed

func WeightedRandomSelectMultiple

func WeightedRandomSelectMultiple(items []WeightedItem, count int, seed string) ([]int, []WeightedItem)

WeightedRandomSelectMultiple selects random items from the list (with probability proportional to item weight). If the seed is empty, it will use a cryptographically secure random seed

Directories

Path Synopsis
sql

Jump to

Keyboard shortcuts

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