niu

package module
v1.1.18 Latest Latest
Warning

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

Go to latest
Published: Apr 22, 2025 License: MIT Imports: 39 Imported by: 0

README

niu

a go lib

Documentation

Index

Constants

View Source
const (
	HeaderAuthorization = "Authorization"
	HeaderContentType   = "Content-Type"

	ContentTypeJson      = "application/json;charset=utf-8"
	ContentTypeText      = "text/plain;charset=utf-8"
	ContentTypeEncrypted = "application/x-encrypted;charset=utf-8"
)
View Source
const (
	Day = 24 * time.Hour
)

Variables

View Source
var (
	ErrLockFailed  = errors.New("lock failed")
	ErrLockNotHeld = errors.New("lock not held")
)
View Source
var (
	ErrInvalidDistributeIdParams = errors.New("invalid distribute id params")
)

Functions

func All

func All[T any](data []T, condition func(*T) bool) bool

检查数组是否所有的项都满足指定的条件

func Any

func Any[T any](data []T, condition func(*T) bool) bool

查看数组中是否存在指定条件的项

func Base64Decode

func Base64Decode(data string) ([]byte, error)

解码base64

func Base64Encode

func Base64Encode(data []byte) string

编码为 base64 字符串

func Base64URLDecode

func Base64URLDecode(data string) ([]byte, error)

解码base64

func Base64URLEncode

func Base64URLEncode(data []byte) string

编码为 base64 字符串

func BeginOfDay

func BeginOfDay(t time.Time) time.Time

返回指定天的开始时间

func BeginOfMonth

func BeginOfMonth(t time.Time) time.Time

一个月的第一天

func BeginOfYear

func BeginOfYear(t time.Time) time.Time

一年的开始时间

func ContainsIgnoreCase

func ContainsIgnoreCase(data []string, target string) bool

查看数组中是否存在指定值

func Count

func Count[T any](arr []T, condition func(*T) bool) int

计算满足指定条件的项的数量

func Days

func Days(dur time.Duration) int64

计算指定一段时间的天数

func DaysOfMonth

func DaysOfMonth(t time.Time) int64

计算一个月的天数

func DaysOfThisMonth

func DaysOfThisMonth() int64

这个月的天数

func Deduplication

func Deduplication[T comparable](arr []T) []T

去除数组中重复的元素

func EndOfDay

func EndOfDay(t time.Time) time.Time

返回指定天的结束时间

func EndOfMonth

func EndOfMonth(t time.Time) time.Time

一个月的最后一天

func EndOfYear

func EndOfYear(t time.Time) time.Time

一年的结束时间

func Filter

func Filter[T any](data []T, filter func(*T) bool) []T

从数组中筛选出满足条件的项

func First

func First[T any](data []T, f func(*T) bool) *T

找到数组中第一个满足条件的项

func FirstOrDefault

func FirstOrDefault[T any](data []T, f func(*T) bool, defaultVal T) T

找到数组中第一个满足条件的项,如果未找到,使用默认值

func GetClientIp

func GetClientIp(ctx *gin.Context) string

获取客户端的IP地址

func GetGenTime

func GetGenTime(sid int64) string

获取创建ID时的时间字符串(精度:秒)

func GetGenTimestamp

func GetGenTimestamp(sid int64) int64

获取创建ID时的时间戳

func GetTimestamp

func GetTimestamp(sid int64) int64

获取时间戳

func GetTimestampStatus

func GetTimestampStatus() float64

获取时间戳已使用的占比:范围(0.0 - 1.0)

func GetWorkerId

func GetWorkerId(sid int64) int64

获取机器ID

func GetWxOpenId

func GetWxOpenId(code, appId, appSecret string) (string, error)

用于获取微信的OpenId

func GroupBy

func GroupBy[T any, TField comparable](data []T, fieldFilter func(*T) TField) map[TField][]T

根据指定的字段分组

func GroupByWithMap

func GroupByWithMap[S any, TOutField any, TGroupField comparable](data []S, fieldFilter func(*S) TGroupField, mapper func(*S) TOutField) map[TGroupField][]TOutField

根据指定的字段分组

func HashMd5

func HashMd5(str string) string

Md5

func HashSha256

func HashSha256(str string) string

Sha256

func HttpGet

func HttpGet(url string, options *HttpOptions) ([]byte, error)

发送 Http Get 请求

func HttpGetJson

func HttpGetJson(url string, options *HttpOptions, resp any) error

resp 必须是一个指针

func HttpPost

func HttpPost(url string, data []byte, options *HttpOptions) ([]byte, error)

发送 Http Post 请求

func HttpPostJson

func HttpPostJson(url string, data any, options *HttpOptions, resp any) error

resp 必须是一个指针

func IsCellPhone

func IsCellPhone(value string) bool

是否是有效的手机号

func IsColor

func IsColor(value string) bool

是否是有效的颜色值

func IsCountryCode

func IsCountryCode(value string) bool

是否是有效的国家代码,如中国为 86

func IsEmail

func IsEmail(value string) bool

是否是有效的邮件地址

func IsEmpty

func IsEmpty(value string) bool

指定的字符串是否为空

func IsFixedLengthInt

func IsFixedLengthInt(value string, length int) bool

是否是固定长度的整数

func IsLengthInRange

func IsLengthInRange(value string, min, max int) bool

指定的字符串的长度是否符合要求

func IsNumber

func IsNumber(value string) bool

是否是数字

func IsPlatformStringValid added in v1.1.0

func IsPlatformStringValid(pstr string) bool

func IsPlatformValid added in v1.1.0

func IsPlatformValid(p Platform) bool

func IsTelephone

func IsTelephone(value string) bool

是否是有效的座机号

func IsUrl

func IsUrl(value string, allowEmpty bool) bool

是否是链接地址

func LastMonthFirstDay

func LastMonthFirstDay() time.Time

上个月第一天

func LastMonthLastDay

func LastMonthLastDay() time.Time

上个月最后一天

func LastMonthNow

func LastMonthNow(t time.Time) time.Time

上个月此时

func Map

func Map[TIn any, TOut any](data []TIn, f func(*TIn) (TOut, bool)) []TOut

将数组中的项转换为另外一个类型的对象

func MaskPhone

func MaskPhone(phone string) string

将手机号脱敏,即中间4为变为 ****

func NewEd25519CryptorKeyPair

func NewEd25519CryptorKeyPair() (pubKey, priKey []byte, err error)

生成 Ed25519 密钥对

func NewEd25519SignerKeyPair

func NewEd25519SignerKeyPair() (pubKey, priKey []byte, err error)

初始化一个Ed25519 密钥对

func NewUUID

func NewUUID() string

生成UUID字符串

func NewUUIDWithoutDash

func NewUUIDWithoutDash() string

生成没有短横线的UUID字符串

func PadLeft

func PadLeft(val string, fixLen int, char string) string

将输入转换为字符串,且在左边填充为指定长度

func PadLeftInt

func PadLeftInt(num int, fixLen int, char string) string

将输入转换为字符串,且在左边填充为指定长度

func PadRight

func PadRight(val string, fixLen int, char string) string

将输入转换为字符串,且在右边填充为指定长度

func PadRightInt

func PadRightInt(num int, fixLen int, char string) string

将输入转换为字符串,且在右边填充为指定长度

func Random

func Random(min, max int) int

生成随机数

func RateLimitMiddleware

func RateLimitMiddleware(limitInterval time.Duration, count int) gin.HandlerFunc

func SecureBytes

func SecureBytes(keyLenInBytes int) ([]byte, error)

生成强密码

func Shuffle

func Shuffle[T any](arr []T)

打乱数组

func ShuffleCopy

func ShuffleCopy[T any](arr []T) []T

打乱数组:Slower, use `copy` function

func SplitCommaString

func SplitCommaString(str string) []string

将以逗号分隔的字符串拆分成数组

func SplitIntoBatches

func SplitIntoBatches[T any](arr []T, itemsPerBatch int) [][]T

将一个长数组拆分为多个小的批次数组

func SplitJoinedItems

func SplitJoinedItems(joinedStr string, sep ...string) []string

func ThisMonthFirstDay

func ThisMonthFirstDay() time.Time

这个月第一天

func ThisMonthRemainDays

func ThisMonthRemainDays() int64

这个月升剩余的天数

func TimeToYYYYMMDD

func TimeToYYYYMMDD(t time.Time) string

将时间格式化为 YYYYMMDD 格式的字符串

func TimeToYYYYMMDDInt

func TimeToYYYYMMDDInt(t time.Time) (int, error)

将时间格式化为 YYYYMMDD 格式的整数

func WaitSysSignal added in v0.0.9

func WaitSysSignal(cleanup func())

wait system signals.

when signal comes, do some cleanups

Types

type ByteBufferPool

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

func NewByteBufferPool

func NewByteBufferPool(size, cap int) *ByteBufferPool

func (*ByteBufferPool) Get

func (p *ByteBufferPool) Get() *bytes.Buffer

func (*ByteBufferPool) Put

func (p *ByteBufferPool) Put(b *bytes.Buffer)

type BytePool

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

func NewBytePool

func NewBytePool(size, cap int) *BytePool

func (*BytePool) Get

func (p *BytePool) Get() []byte

func (*BytePool) Put

func (p *BytePool) Put(b []byte)

type Cache

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

func NewCache

func NewCache(ctx context.Context, masterOpt, slaveOpt *redis.Options) (*Cache, error)

初始化缓存 slaveOpt 可以为空,此时slave与master共享同一实例

func NewCacheWithAddr added in v0.0.6

func NewCacheWithAddr(ctx context.Context, addr string, slaveAddr string) (*Cache, error)

func (*Cache) Batch

func (c *Cache) Batch(ctx context.Context, f func(pipe redis.Pipeliner)) (map[int]interface{}, map[int]error)

func (*Cache) Close

func (c *Cache) Close() error

func (*Cache) DecrBy

func (c *Cache) DecrBy(ctx context.Context, key string, decrement int64) (int64, error)

func (*Cache) Get

func (c *Cache) Get(ctx context.Context, key string) (string, error)

func (*Cache) GetDel

func (c *Cache) GetDel(ctx context.Context, key string) (string, error)

func (*Cache) GetExpire

func (c *Cache) GetExpire(ctx context.Context, key string, expiration time.Duration) (string, error)

func (*Cache) GetJson

func (c *Cache) GetJson(ctx context.Context, key string, out interface{}) error

func (*Cache) GetSet

func (c *Cache) GetSet(ctx context.Context, key string, value any) (string, error)

func (*Cache) HDel

func (c *Cache) HDel(ctx context.Context, key string, fields ...string) (bool, error)

func (*Cache) HExists

func (c *Cache) HExists(ctx context.Context, key, field string) (bool, error)

func (*Cache) HGet

func (c *Cache) HGet(ctx context.Context, key, field string) (string, error)

func (*Cache) HGetAll

func (c *Cache) HGetAll(ctx context.Context, key string) (map[string]string, error)

func (*Cache) HGetJson

func (c *Cache) HGetJson(ctx context.Context, key string, field string, out any) error

func (*Cache) HIncrBy

func (c *Cache) HIncrBy(ctx context.Context, key, field string, incr int64) (int64, error)

func (*Cache) HIncrByFloat

func (c *Cache) HIncrByFloat(ctx context.Context, key, field string, incr float64) (float64, error)

func (*Cache) HKeys

func (c *Cache) HKeys(ctx context.Context, key string) ([]string, error)

func (*Cache) HLen

func (c *Cache) HLen(ctx context.Context, key string) (int64, error)

func (*Cache) HMGet

func (c *Cache) HMGet(ctx context.Context, key string, fields ...string) ([]any, error)

func (*Cache) HMSet

func (c *Cache) HMSet(ctx context.Context, key string, values map[string]any) (bool, error)

func (*Cache) HMSetAndExpiry

func (c *Cache) HMSetAndExpiry(ctx context.Context, key string, values map[string]string, expiry time.Duration) (bool, error)

func (*Cache) HSet

func (c *Cache) HSet(ctx context.Context, key string, values map[string]any) (int64, error)

func (*Cache) HSetJson

func (c *Cache) HSetJson(ctx context.Context, key string, field string, val any) (int64, error)

func (*Cache) HSetNX

func (c *Cache) HSetNX(ctx context.Context, key, field string, value any) (bool, error)

func (*Cache) HVals

func (c *Cache) HVals(ctx context.Context, key string) ([]string, error)

func (*Cache) IncrBy

func (c *Cache) IncrBy(ctx context.Context, key string, decrement int64) (int64, error)

func (*Cache) IncrByFloat

func (c *Cache) IncrByFloat(ctx context.Context, key string, decrement float64) (float64, error)

func (*Cache) KeyDel

func (c *Cache) KeyDel(ctx context.Context, keys ...string) (int64, error)

func (*Cache) KeyExists

func (c *Cache) KeyExists(ctx context.Context, keys ...string) (int64, error)

func (*Cache) KeyExpire

func (c *Cache) KeyExpire(ctx context.Context, key string, expiry time.Duration) (bool, error)

func (*Cache) KeyExpireAt

func (c *Cache) KeyExpireAt(ctx context.Context, key string, expiry time.Time) (bool, error)

func (*Cache) Master

func (c *Cache) Master() *redis.Client

func (*Cache) MultiGet

func (c *Cache) MultiGet(ctx context.Context, keys ...string) ([]any, error)

func (*Cache) MultiSet

func (c *Cache) MultiSet(ctx context.Context, maps map[string]any) (string, error)

func (*Cache) MultiSetNX

func (c *Cache) MultiSetNX(ctx context.Context, maps map[string]any) (bool, error)

func (*Cache) SAdd

func (c *Cache) SAdd(ctx context.Context, key string, members ...any) (int64, error)

func (*Cache) SIsMember

func (c *Cache) SIsMember(ctx context.Context, key string, member any) (bool, error)

func (*Cache) SMembers

func (c *Cache) SMembers(ctx context.Context, key string) ([]string, error)

func (*Cache) SMultiIsMember

func (c *Cache) SMultiIsMember(ctx context.Context, key string, members ...any) ([]bool, error)

func (*Cache) SRemove

func (c *Cache) SRemove(ctx context.Context, key string, members ...any) (int64, error)

func (*Cache) Set

func (c *Cache) Set(ctx context.Context, key string, value any, expiry time.Duration) (string, error)

func (*Cache) SetJson

func (c *Cache) SetJson(ctx context.Context, key string, val any, expiry time.Duration) (string, error)

func (*Cache) SetNX

func (c *Cache) SetNX(ctx context.Context, key string, value any, expiry time.Duration) (bool, error)

func (*Cache) Slave

func (c *Cache) Slave() *redis.Client

type Collection

type Collection[T any] interface {
	Size() int
	IsEmpty() bool
	Clear()
}

type ConsumeMsgHandler

type ConsumeMsgHandler func(ctx context.Context, id string, msg map[string]any) error

id 消费者需要通过此Id来判断该消息是否已被消费

type CoroutinePool added in v1.1.8

type CoroutinePool interface {
	Submit(task func()) error
	Release()
}

type Cryptor

type Cryptor interface {
	Encrypt(rawData []byte) ([]byte, error)
	EncryptToString(rawData []byte) (string, error)
	Decrypt(ciphertext []byte) ([]byte, error)
	DecryptFromString(ciphertext string) ([]byte, error)
}

type DistributeId

type DistributeId struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

func NewDistributeId

func NewDistributeId(ctx context.Context, opt *redis.Options) (*DistributeId, error)

func (*DistributeId) Close added in v1.1.8

func (d *DistributeId) Close()

func (*DistributeId) NewGenerator added in v1.1.8

func (d *DistributeId) NewGenerator(ctx context.Context, key string, start int) (*IdGenerator, error)

type DistributeLock

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

func (*DistributeLock) Refresh

func (i *DistributeLock) Refresh(ctx context.Context, ttl time.Duration) error

func (*DistributeLock) Release

func (i *DistributeLock) Release(ctx context.Context) error

释放获取的锁

type DistributeLockOptions

type DistributeLockOptions struct {
	Resource      string
	Owner         string
	Ttl           time.Duration
	RetryStrategy RetryStrategy
}

type DistributeLocker

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

func NewDistributeLocker

func NewDistributeLocker(ctx context.Context, opt *redis.Options, ttl time.Duration, retryStrategy RetryStrategy) (*DistributeLocker, error)

func (*DistributeLocker) Close added in v1.1.8

func (l *DistributeLocker) Close()

func (*DistributeLocker) Lock

func (l *DistributeLocker) Lock(ctx context.Context, resource string, owner string) (*DistributeLock, error)

func (*DistributeLocker) LockWithOptions

func (l *DistributeLocker) LockWithOptions(ctx context.Context, opt *DistributeLockOptions) (*DistributeLock, error)

在指定资源上加锁,默认5s

type Ed25519Cryptor

type Ed25519Cryptor struct {
	SharedKey []byte // 与服务端协商的密钥
}

func NewEd25519Cryptor

func NewEd25519Cryptor(sharedKey string) (*Ed25519Cryptor, error)

初始化一个加密器

func NewEd25519CryptorByNegotiate

func NewEd25519CryptorByNegotiate(remotePublicKey, selfPrivateKey []byte) (*Ed25519Cryptor, error)

通过与对方公钥协商,获得共享密钥

func (*Ed25519Cryptor) Decrypt

func (e *Ed25519Cryptor) Decrypt(rawData []byte) ([]byte, error)

对指定输入解密,输入为: nonce + cipherData + tag

func (*Ed25519Cryptor) DecryptFromString

func (e *Ed25519Cryptor) DecryptFromString(ciphertext string) ([]byte, error)

func (*Ed25519Cryptor) Encrypt

func (e *Ed25519Cryptor) Encrypt(rawData []byte) ([]byte, error)

对指定输入加密,结果为: nonce + cipherData + tag

func (*Ed25519Cryptor) EncryptToString

func (e *Ed25519Cryptor) EncryptToString(rawData []byte) (string, error)

func (*Ed25519Cryptor) SharedKeyString

func (e *Ed25519Cryptor) SharedKeyString() string

将密钥转换为 base64 格式字符串

type Ed25519SignKey

type Ed25519SignKey struct {
	Pri string
	Pub string
	// contains filtered or unexported fields
}

Pri, Pub需要公开出去以供配置文件加载程序使用

func NewEd25519SignKey

func NewEd25519SignKey(pri, pub string) (*Ed25519SignKey, error)

func (*Ed25519SignKey) Sign

func (sk *Ed25519SignKey) Sign(message []byte) []byte

func (*Ed25519SignKey) SignString

func (sk *Ed25519SignKey) SignString(message string) string

type Ed25519Signer

type Ed25519Signer struct {
	RemotePublicKey ed25519.PublicKey  // 远端的公钥,用于验证远程发过来的数据的签名
	SelfPrivateKey  ed25519.PrivateKey // 本地的私钥,用于对发往服务器的数据进行签名
}

func NewEd25519Signer

func NewEd25519Signer(remotePublicKey []byte, selfPrivateKey []byte) *Ed25519Signer

初始化一个签名器

func NewEd25519SignerFromString

func NewEd25519SignerFromString(remotePublicKey, selfPrivateKey string) (*Ed25519Signer, error)

初始化一个签名器

func (*Ed25519Signer) RemotePublicKeyString

func (e *Ed25519Signer) RemotePublicKeyString() string

func (*Ed25519Signer) SelfPrivateKeyString

func (e *Ed25519Signer) SelfPrivateKeyString() string

func (*Ed25519Signer) Sign

func (e *Ed25519Signer) Sign(rawData []byte) ([]byte, error)

对指定输入进行签名

func (*Ed25519Signer) SignatureLen added in v1.1.0

func (e *Ed25519Signer) SignatureLen() int

func (*Ed25519Signer) Verify

func (e *Ed25519Signer) Verify(utf8Bytes []byte, signature []byte) bool

验证指定输入的签名

type Empty

type Empty struct{}

type FastQueue

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

func (*FastQueue[T]) Clear

func (queue *FastQueue[T]) Clear()

O(1)

func (*FastQueue[T]) In

func (queue *FastQueue[T]) In(val *T)

O(1)

func (*FastQueue[T]) InAll

func (queue *FastQueue[T]) InAll(vals ...T)

O(n)

func (*FastQueue[T]) IsEmpty

func (queue *FastQueue[T]) IsEmpty() bool

O(1)

func (*FastQueue[T]) Out

func (queue *FastQueue[T]) Out() *T

O(1)

func (*FastQueue[T]) Print

func (queue *FastQueue[T]) Print()

for test only

func (*FastQueue[T]) Size

func (queue *FastQueue[T]) Size() int

O(1)

type FastStack

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

func (*FastStack[T]) Clear

func (stack *FastStack[T]) Clear()

O(1)

func (*FastStack[T]) IsEmpty

func (stack *FastStack[T]) IsEmpty() bool

O(1)

func (*FastStack[T]) Peek

func (stack *FastStack[T]) Peek() *T

O(1)

func (*FastStack[T]) Pop

func (stack *FastStack[T]) Pop() *T

O(1)

func (*FastStack[T]) Print

func (stack *FastStack[T]) Print()

for test only

func (*FastStack[T]) Push

func (stack *FastStack[T]) Push(val *T)

O(1)

func (*FastStack[T]) PushAll

func (stack *FastStack[T]) PushAll(vals ...T)

O(n)

func (*FastStack[T]) Size

func (stack *FastStack[T]) Size() int

O(1)

type HmacSigner added in v1.1.0

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

func NewHmacSigner added in v1.1.0

func NewHmacSigner(secret []byte) *HmacSigner

func (*HmacSigner) Sign added in v1.1.0

func (h *HmacSigner) Sign(data []byte) ([]byte, error)

Golang 生成 HMAC 签名

func (*HmacSigner) SignatureLen added in v1.1.0

func (h *HmacSigner) SignatureLen() int

func (*HmacSigner) Verify added in v1.1.0

func (h *HmacSigner) Verify(dataToSign []byte, signature []byte) bool

type HttpOptions

type HttpOptions struct {
	Headers map[string]string
	Timeout time.Duration
}

func NewEmptyHttpOptions

func NewEmptyHttpOptions() *HttpOptions

func NewHttpOptions

func NewHttpOptions(headers map[string]string) *HttpOptions

func NewHttpOptionsJson

func NewHttpOptionsJson(authorization string) *HttpOptions

type Hub

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

func NewHub

func NewHub(
	subprotocols []string,
	liveCheckDuration, connMaxIdleTime,
	readTimeout, writeTimeout time.Duration,
	pool CoroutinePool,
	handshakeTimeout time.Duration,
	enableCompression bool,
	checkOriginFn func(r *http.Request) bool,
) (*Hub, error)

func (*Hub) BroadcastMessage

func (h *Hub) BroadcastMessage(data []byte)

func (*Hub) Close

func (h *Hub) Close(wait time.Duration)

func (*Hub) CloseUserLines added in v1.1.14

func (h *Hub) CloseUserLines(userIds ...string)

关闭指定用户的所有连接

func (*Hub) ErrorChan

func (h *Hub) ErrorChan() <-chan *LineError

func (*Hub) GetUserLines added in v1.1.14

func (h *Hub) GetUserLines(userId string) *UserLines

获取指定用户的所有连接

func (*Hub) LiveCount

func (h *Hub) LiveCount() int

func (*Hub) MessageChan

func (h *Hub) MessageChan() <-chan *LineMessage

返回只读通道

func (*Hub) PushMessage

func (h *Hub) PushMessage(userIds []string, data []byte)

func (*Hub) RegisteredChan

func (h *Hub) RegisteredChan() <-chan *Line

func (*Hub) UnegisteredChan

func (h *Hub) UnegisteredChan() <-chan *Line

func (*Hub) UpgradeWebSocket

func (h *Hub) UpgradeWebSocket(userId string, platform Platform, lineId string, w http.ResponseWriter, r *http.Request) error

type IdGenerator added in v1.1.8

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

func (*IdGenerator) Next added in v1.1.8

func (c *IdGenerator) Next(ctx context.Context) (int, error)

type JsonMarshaler

type JsonMarshaler struct{}

func (*JsonMarshaler) Marshal

func (m *JsonMarshaler) Marshal(v any) ([]byte, error)

func (*JsonMarshaler) Unmarshal

func (m *JsonMarshaler) Unmarshal(data []byte, v any) error

type Line

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

客户端连接

func (*Line) Hub added in v1.1.14

func (ln *Line) Hub() *Hub

func (*Line) Id added in v1.1.14

func (ln *Line) Id() string

func (*Line) LastActive added in v1.1.14

func (ln *Line) LastActive() int64

func (*Line) Platform

func (ln *Line) Platform() Platform

func (*Line) UserId

func (ln *Line) UserId() string

type LineError

type LineError struct {
	UserId   string
	Platform Platform
	LineId   string
	Error    error
}

客户端连接的错误

type LineMessage added in v1.1.14

type LineMessage struct {
	UserId   string
	Platform Platform
	LineId   string
	Data     []byte
}

客户端连接的消息

type MessageQueue

type MessageQueue interface {
	Publish(ctx context.Context, topic string, body map[string]any) error
	Subscribe(ctx context.Context, topic, group, consumer string, handler ConsumeMsgHandler) error
	Close()
}

type MsgPackMarshaler

type MsgPackMarshaler struct{}

func (*MsgPackMarshaler) Marshal

func (m *MsgPackMarshaler) Marshal(v any) ([]byte, error)

func (*MsgPackMarshaler) Unmarshal

func (m *MsgPackMarshaler) Unmarshal(data []byte, v any) error

type PacketMetaData added in v1.1.16

type PacketMetaData struct {
	MsgType   byte  // 1字节
	RequestId int32 // 4字节
	Timestamp int32 // 4字节,从2025-01-01 00:00:00开始的秒数
}

type PacketProtocol added in v1.1.16

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

func NewJsonProtocol

func NewJsonProtocol(signer Signer, cryptor Cryptor) *PacketProtocol

func NewMsgPackProtocol

func NewMsgPackProtocol(signer Signer, cryptor Cryptor) *PacketProtocol

func (*PacketProtocol) DecodeReq added in v1.1.16

func (m *PacketProtocol) DecodeReq(data []byte) (*RequestPacket, error)

func (*PacketProtocol) EncodeResp added in v1.1.16

func (m *PacketProtocol) EncodeResp(msgType, requestId int32, code byte, payload any) ([]byte, error)

func (*PacketProtocol) GetMeta added in v1.1.16

func (m *PacketProtocol) GetMeta(data []byte) (*PacketMetaData, error)

type PayloadMarshaler

type PayloadMarshaler interface {
	Marshal(v any) ([]byte, error)
	Unmarshal(data []byte, v any) error
}

type Platform

type Platform int8
const (
	Unspecify  Platform = 0
	Android    Platform = 1
	AndroidPad Platform = 2
	IPhone     Platform = 3
	Mac        Platform = 4
	IPad       Platform = 5
	Windows    Platform = 6
	Linux      Platform = 7
	Web        Platform = 8
	Harmony    Platform = 9
)

func ParsePlatform added in v1.1.5

func ParsePlatform(pstr string) Platform

type RedisMessageQueue

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

func NewRedisMessageQueue

func NewRedisMessageQueue(ctx context.Context, opt *redis.Options, pool CoroutinePool, xaddMaxLen, batchSize int) (*RedisMessageQueue, error)

func (*RedisMessageQueue) Close added in v1.1.8

func (m *RedisMessageQueue) Close()

func (*RedisMessageQueue) Publish

func (m *RedisMessageQueue) Publish(ctx context.Context, topic string, body map[string]any) error

发布消息

func (*RedisMessageQueue) Subscribe added in v0.0.7

func (m *RedisMessageQueue) Subscribe(ctx context.Context, topic, group, consumer string, handler ConsumeMsgHandler) error

开启协程后台消费。返回值代表消费过程中遇到的无法处理的错误 group 消费者组,一般为当前服务的名称 consumer 消费者组里的消费者,一般为一个uuid handler 消费消息的处理器,如果返回nil,则表示消息被成功消费,如果返回非nil,则表示消息被消费失败,需要重试

type ReplyDto

type ReplyDto[TCode any, TData any] struct {
	Code TCode  `json:"code"`
	Msg  string `json:"msg"`
	Data TData  `json:"data"`
}

type RequestPacket added in v1.1.16

type RequestPacket struct {
	PacketMetaData
	Payload any
}

type RetryStrategy

type RetryStrategy interface {
	Next() time.Duration
}

func LinearRetryStrategy

func LinearRetryStrategy(backoff time.Duration) RetryStrategy

LinearRetryStrategy allows retries regularly with customized intervals

func NoRetry

func NoRetry() RetryStrategy

NoRetry acquire the lock only once.

type RsaCryptor

type RsaCryptor struct {
	PublicKey  []byte // PEM format: 即有-----BEGIN XXX KEY-----...-----END XXX KEY-----
	PrivateKey []byte // PEM format: 即有-----BEGIN XXX KEY-----...-----END XXX KEY-----
}

func NewRsaCryptor

func NewRsaCryptor(publicKey, privateKey []byte) *RsaCryptor

func (*RsaCryptor) Decrypt

func (r *RsaCryptor) Decrypt(ciphertext []byte) ([]byte, error)

func (*RsaCryptor) DecryptFromString

func (r *RsaCryptor) DecryptFromString(ciphertext string) ([]byte, error)

func (*RsaCryptor) Encrypt

func (r *RsaCryptor) Encrypt(rawData []byte) ([]byte, error)

func (*RsaCryptor) EncryptToString

func (r *RsaCryptor) EncryptToString(rawData []byte) (string, error)

type Set

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

func (*Set[T]) Add

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

O(1)~O(n)

func (*Set[T]) AddRange

func (s *Set[T]) AddRange(items ...T)

O(n)

func (*Set[T]) Clear

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

O(1)

func (*Set[T]) Contains

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

O(1)~O(n)

func (*Set[T]) IsEmpty

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

O(n)

func (*Set[T]) Remove

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

O(1)~O(n)

func (*Set[T]) Size

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

O(n)

func (*Set[T]) ToSlice

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

O(n)

type Signer

type Signer interface {
	Sign(rawData []byte) ([]byte, error)
	Verify(utf8Bytes []byte, signature []byte) bool
	SignatureLen() int
}

type Snowflake

type Snowflake struct {
	sync.Mutex
	// contains filtered or unexported fields
}

func NewSnowflake

func NewSnowflake(workerid int64) *Snowflake

func (*Snowflake) Next

func (s *Snowflake) Next() int64

type UserLines added in v1.1.14

type UserLines struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

用户在各个平台的所有连接

func (*UserLines) Close added in v1.1.14

func (u *UserLines) Close(lineId string)

关闭指定连接

func (*UserLines) CloseAll added in v1.1.14

func (u *UserLines) CloseAll()

关闭所有连接

func (*UserLines) CloseLines added in v1.1.14

func (u *UserLines) CloseLines(lineIds ...string)

关闭指定连接

func (*UserLines) CloseLinesExcept added in v1.1.14

func (u *UserLines) CloseLinesExcept(exceptLineIds ...string)

关闭除指定连接外的所有连接

func (*UserLines) ClosePlatforms added in v1.1.14

func (u *UserLines) ClosePlatforms(platforms ...Platform)

关闭指定平台的所有连接

func (*UserLines) ClosePlatformsExcept added in v1.1.14

func (u *UserLines) ClosePlatformsExcept(exceptPlatforms ...Platform)

关闭除指定平台外的所有连接

func (*UserLines) Get added in v1.1.14

func (u *UserLines) Get(lineId string) *Line

获取指定连接

func (*UserLines) GetPlatformLines added in v1.1.14

func (u *UserLines) GetPlatformLines(platforms ...Platform) []*Line

获取指定平台的所有连接

func (*UserLines) Len added in v1.1.14

func (u *UserLines) Len() int

获取连接数量

func (*UserLines) PushMessage added in v1.1.14

func (u *UserLines) PushMessage(data []byte)

向该用户的所有连接发送消息

func (*UserLines) PushMessageExceptLines added in v1.1.14

func (u *UserLines) PushMessageExceptLines(data []byte, exceptLineIds ...string)

向该用户的所有连接发送消息,除了指定连接

func (*UserLines) PushMessageExceptPlatforms added in v1.1.14

func (u *UserLines) PushMessageExceptPlatforms(data []byte, exceptPlatforms ...Platform)

向该用户的所有连接发送消息,除了指定平台

func (*UserLines) PushMessageToLines added in v1.1.14

func (u *UserLines) PushMessageToLines(data []byte, lineIds ...string)

向该用户的指定连接发送消息

func (*UserLines) PushMessageToPlatforms added in v1.1.14

func (u *UserLines) PushMessageToPlatforms(data []byte, platforms ...Platform)

向该用户的指定平台发送消息

Jump to

Keyboard shortcuts

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