ws

package
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Mar 3, 2025 License: Apache-2.0 Imports: 23 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrServerError          = NewError(sys, 1100, "Server under maintenance")
	ErrUncertified          = NewError(sys, 1120, "Please log in first")
	ErrCertificationExpired = NewError(sys, 1121, "Login has expired")
	ErrJwtBLOCKED           = NewError(sys, 1123, "Login has expired")
	ErrParamsInvalid        = NewError(sys, 1131, "Invalid parameters")
	ErrAuthentic            = NewError(sys, 1141, "Please login first")
)

Functions

func BindingErrors

func BindingErrors(e error) error

BindingErrors 处理错误信息

func Code

func Code(action string, code int, msg string) []byte

func Data

func Data(action string, data any) []byte

func Dispatcher

func Dispatcher(c *Client, request string)

func HttpHandler

func HttpHandler(w http.ResponseWriter, r *http.Request)

func IsValidStatus

func IsValidStatus(s UserOnlineStatus) bool

func Msg

func Msg(action, msg string) []byte

func Pub added in v1.2.0

func Pub(topic string, data any)

func Sub added in v1.2.0

func Sub(topicId string, user *User)

func SubFunc added in v1.2.0

func SubFunc(topicId string, f func(msg *TopicMsg))

Types

type Action

type Action struct {
	Action string `json:"action"`

	Code int    `json:"code"`
	Msg  string `json:"msg,omitempty"`
	Data any    `json:"data,omitempty"`
}

Action Websocket通讯协议

func New

func New(action string) *Action

func (*Action) Encode

func (m *Action) Encode() []byte

func (*Action) WithCode

func (m *Action) WithCode(code int) *Action

func (*Action) WithData

func (m *Action) WithData(data any) *Action

func (*Action) WithMsg

func (m *Action) WithMsg(msg string) *Action

type ActionManager

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

func InitManager

func InitManager() *ActionManager

func (*ActionManager) Add

func (m *ActionManager) Add(name string, router HandlersChain)

func (*ActionManager) Handlers

func (m *ActionManager) Handlers(name string) HandlersChain

func (*ActionManager) Has

func (m *ActionManager) Has(name string) bool

type ApiData

type ApiData struct {
	Code int    `json:"code"`
	Msg  string `json:"msg"`
	Data any    `json:"data,omitempty"`

	HttpStatus int
}

type Appid

type Appid int

type Client

type Client struct {
	Hub            *Hubc       `json:"-"`
	Conn           net.Conn    `json:"-"`
	Send           chan []byte `json:"-"`
	Endpoint       string      `json:"-"` //入口地址
	OnceId         string      `json:"-"` //临时ID,扫码登录等场景作为客户端唯一标识
	ClientId       string      `json:"-"` //客户端ID
	Disconnecting  bool        `json:"-"` //已被设置为断开状态(消息发送完之后断开连接)
	SyncMsg        bool        `json:"-"` //是否接收消息
	LastMsgId      int         `json:"-"` //最后一条消息ID
	RequiredValid  bool        `json:"-"` //人机验证标识
	Validated      bool        `json:"-"` //是否已验证
	ValidExpiry    time.Time   `json:"-"` //验证有效期
	ValidCacheData any         `json:"-"` //验证相关缓存数据
	AuthCode       string      `json:"-"` //用于校验JWT中的code,如果相等识别为同一个用户的网络地址变更
	ErrorCount     int         `json:"-"` //错误次数
	Closed         bool        `json:"-"` //是否已经关闭

	HttpRequest *http.Request       `json:"-"`
	HttpWriter  http.ResponseWriter `json:"-"`

	User              *User     `json:"user,omitempty"` //关联用户
	Scope             string    `json:"scope"`          //登录jwt scope, 用于判断用户从哪里登录的
	AppId             string    `json:"appId"`          //登录应用Id
	StoreId           uint      `json:"storeId"`        //店铺ID
	MerchantId        uint      `json:"merchantId"`     //商户ID
	TenantId          uint      `json:"tenantId"`       //租户ID
	Platform          string    `json:"platform"`       //登录平台
	GroupId           string    `json:"groupId"`        //用户分组Id
	IsLogin           bool      `json:"isLogin"`        //是否已登录
	LoginAction       string    `json:"loginAction"`    //登录动作
	ForceDialogId     string    `json:"forceDialogId"`  //打开聊天界面的会话ID
	IpAddress         string    `json:"ipAddress"`      //IP地址
	IpAddressPort     string    `json:"IpAddressPort"`  //IP地址和端口
	IpLocation        string    `json:"ipLocation"`     //通过IP转换获得的地理位置
	ConnectionTime    time.Time `json:"connectionTime"`
	LastRequestTime   time.Time `json:"lastRequestTime"`
	LastHeartbeatTime time.Time `json:"lastHeartbeatTime"`

	Keys map[string]any
	// contains filtered or unexported fields
}

func (*Client) Close

func (c *Client) Close()

Close 关闭客户端

func (*Client) GetIP added in v1.2.0

func (c *Client) GetIP() string

func (*Client) GetKey

func (c *Client) GetKey(key string) *Value

func (*Client) Log

func (c *Client) Log(symbol string, msg ...string)

Log websocket日志

func (*Client) Reader

func (c *Client) Reader()

Reader 读取

func (*Client) SendMsg

func (c *Client) SendMsg(msg []byte)

SendMsg 把消息加入发送队列

func (*Client) SendRawMsg

func (c *Client) SendRawMsg(code int, action, msg string, data any)

SendRawMsg 构造消息再发送

func (*Client) SetKey

func (c *Client) SetKey(key string, value any)

func (*Client) Write

func (c *Client) Write()

Write 发送

type Context

type Context struct {
	Client   *Client
	Action   string
	Params   string
	Response *Action
	Server   *Server
	// contains filtered or unexported fields
}

func (*Context) Abort

func (c *Context) Abort()

Abort 放弃调用后续方法

func (*Context) AddLog added in v1.2.0

func (c *Context) AddLog(log string)

func (*Context) BindingJson

func (c *Context) BindingJson(s any) error

func (*Context) BindingJsonPath

func (c *Context) BindingJsonPath(s any, path string) error

func (*Context) BindingValidateJson

func (c *Context) BindingValidateJson(s any) error

func (*Context) Broadcast

func (c *Context) Broadcast(msg *Action)

Broadcast 发送广播

func (*Context) FlushLog added in v1.2.0

func (c *Context) FlushLog()

func (*Context) Get

func (c *Context) Get(key string) string

func (*Context) GetBool

func (c *Context) GetBool(key string) bool

func (*Context) GetId

func (c *Context) GetId(key string) uint

func (*Context) GetInt

func (c *Context) GetInt(key string) int

func (*Context) GetJson

func (c *Context) GetJson(s any) error

func (*Context) GetMinInt

func (c *Context) GetMinInt(key string, min int) int

func (*Context) GetPagination

func (c *Context) GetPagination() *Pagination

func (*Context) GetRangeInt

func (c *Context) GetRangeInt(key string, min, max int) int

func (*Context) GetSizePagination

func (c *Context) GetSizePagination(pageSize int) *Pagination

func (*Context) GetSliceVal

func (c *Context) GetSliceVal(key string, options ...string) string

func (*Context) Next

func (c *Context) Next()

func (*Context) Send

func (c *Context) Send(data any)

Send 发送数据给用户

func (*Context) SendActionData

func (c *Context) SendActionData(action string, data any)

SendActionData 发送数据给当前用户

func (*Context) SendActionMsg

func (c *Context) SendActionMsg(action, msg string)

SendActionMsg 发送消息给当前用户

func (*Context) SendCode

func (c *Context) SendCode(code int, msg string)

SendCode 发送状态消息

func (*Context) SendMsg

func (c *Context) SendMsg(msg string)

SendMsg 发送消息给当前用户

func (*Context) SendOk

func (c *Context) SendOk()

SendOk 发送成功消息

func (*Context) SendRawTo

func (c *Context) SendRawTo(uid string, msg *Action)

SendRawTo 发送RAW消息给指定用户

func (*Context) SendTo

func (c *Context) SendTo(uid, action string, data any)

SendTo 发送给指定用户

func (*Context) SendToApp

func (c *Context) SendToApp(appId string, msg *Action)

SendToApp 发送消息给指定的app

func (*Context) SendToApps

func (c *Context) SendToApps(msg *Action)

SendToApps 发送RAW消息给当前用户所有客户端

type Error

type Error ApiData

func NewError

func NewError(appId Appid, code int, msg string) *Error

func (*Error) WithError

func (e *Error) WithError(err error) *Error

WithError 兼容Binding错误码及多语言翻译 使用前需要调用 validate.GinValidator() 初始化 字段中文名称使用 `label:"名称"` 指定

func (*Error) WithHttpStatus

func (e *Error) WithHttpStatus(status int) *Error

WithHttpStatus 处理HTTP状态码

func (*Error) WithMsg

func (e *Error) WithMsg(msg string) *Error

WithMsg 覆盖业务错误提示内容

type H

type H map[string]any

H 类似gin.H

func (*H) Get

func (h *H) Get(key string) (any, bool)

func (*H) Marshal

func (h *H) Marshal() []byte

func (*H) Set

func (h *H) Set(key string, val any)

func (*H) Unmarshal

func (h *H) Unmarshal(v any) error

type HandlerFunc

type HandlerFunc func(a *Context)

type HandlersChain

type HandlersChain []HandlerFunc

type Hubc

type Hubc struct {
	//访客列表
	Guests []*Client

	//已登录用户 map[string]*User
	Users *sync.Map

	//用户数统计
	LoginCount int
	GuestCount int

	//发布订阅
	PubSub *PubSub

	//登录和断开通道
	Connection chan *Client
	Disconnect chan *Client
}
var Hub *Hubc

func NewHubc

func NewHubc() *Hubc

func (*Hubc) Broadcast

func (h *Hubc) Broadcast(msg []byte)

Broadcast 发送广播消息

func (*Hubc) Run

func (h *Hubc) Run()

func (*Hubc) User

func (h *Hubc) User(uid string) *User

User 获取用户信息

func (*Hubc) UserClient

func (h *Hubc) UserClient(uid, appId string) *Client

UserClient 获取用户客户端信息

func (*Hubc) UserLogin

func (h *Hubc) UserLogin(uid, appId string, client *Client) error

UserLogin 用户登录

type IRouter

type IRouter interface {
	Use(middleware ...HandlerFunc) IRouter
	Group(name string) IRouter
	Add(name string, fn ...HandlerFunc)
}

type Location

type Location struct {
	Latitude  float64  `json:"latitude" validate:"required"`
	Longitude float64  `json:"longitude" validate:"required"`
	AdInfo    []string `json:"adInfo" validate:"required"`
	RegionId  string   `json:"regionId" validate:"required"`
	CityCode  string   `json:"cityCode" validate:"required"`
	Address   string   `json:"address" validate:"required"`

	SelectCityCode string `json:"selectCityCode"` //选择的城市编码
	SelectCityName string `json:"selectCityName"` //选择的城市名称
	LatestUpdateAt time.Time
}

type Page

type Page struct {
	Current  int   `json:"current"`
	PageSize int   `json:"pageSize"`
	Total    int64 `json:"total"`
}

type Pagination

type Pagination struct {
	*Page `json:"page"`

	Rows   any `json:"rows,omitempty"`
	ExData H   `json:"exData,omitempty"`

	Limit  int `json:"-"` //PageSize alias
	Offset int `json:"-"` //避免每次计算offset
}

func InitPagination

func InitPagination(p *Page, maxSize int) *Pagination

func (*Pagination) AddExData

func (p *Pagination) AddExData(key string, val any)

type PubSub

type PubSub struct {
	Topics        *sync.Map      //Topics map[string]*Topic //主题名称和Top对应map
	TopicMsgQueue chan *TopicMsg //主题消息队列
}

func NewPubSub

func NewPubSub() *PubSub

func (*PubSub) Pub

func (a *PubSub) Pub(topicId string, data any)

Pub 发布主题

func (*PubSub) Start

func (a *PubSub) Start()

func (*PubSub) Sub

func (a *PubSub) Sub(topicId string, user *User)

Sub 订阅主题

func (*PubSub) SubFunc

func (a *PubSub) SubFunc(topicId string, f func(msg *TopicMsg))

SubFunc 以函数方式订阅

type Resource

type Resource struct {
	Path     string         `json:"path,omitempty"`     // 文件路径
	CdnUrl   string         `json:"cdnUrl,omitempty"`   // cdn地址
	Scenes   string         `json:"scenes"`             // 使用场景
	MimeType string         `json:"mimeType,omitempty"` // 文件类型
	ExtData  datatypes.JSON `json:"extData,omitempty"`
}

type Response

type Response struct {
	Ctx *ApiData
	// contains filtered or unexported fields
}

func NewResponse

func NewResponse(g *gin.Context, httpCode int) *Response

func (*Response) Send

func (r *Response) Send()

func (*Response) WithData

func (r *Response) WithData(data any) *Response

func (*Response) WithError

func (r *Response) WithError(e Error, err error) *Response

type Routers

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

func NewRouter

func NewRouter() Routers

func (Routers) Add

func (r Routers) Add(name string, fn ...HandlerFunc)

func (Routers) Group

func (r Routers) Group(name string) IRouter

func (Routers) Use

func (r Routers) Use(middleware ...HandlerFunc) IRouter

type Server

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

func NewServer

func NewServer(engine http.Handler) *Server

func (*Server) Handler

func (s *Server) Handler(fn http.HandlerFunc)

func (*Server) Init

func (s *Server) Init()

func (*Server) Run

func (s *Server) Run()

func (*Server) SetDataPath

func (s *Server) SetDataPath(p string)

func (*Server) SetIsDev

func (s *Server) SetIsDev(dev bool)

func (*Server) SetPort

func (s *Server) SetPort(p string)

type Stack

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

func NewStack

func NewStack() *Stack

func (*Stack) Len

func (s *Stack) Len() int

func (*Stack) Pop

func (s *Stack) Pop() any

func (*Stack) Push

func (s *Stack) Push(value any)

type Topic

type Topic struct {
	Id          string   //订阅主题ID
	PubSub      *PubSub  //关联PubSub
	SubUsers    sync.Map //SubUsers map[string]*time.Time //订阅用户uniqueId和订阅时间
	SubHandlers sync.Map //SubHandlers map[string]func(msg *TopicMsg) //内部组件间通知
}

func (*Topic) AddSubHandle

func (a *Topic) AddSubHandle(f func(msg *TopicMsg))

func (*Topic) AddSubUser

func (a *Topic) AddSubUser(user *User)

func (*Topic) ApplyFunc

func (a *Topic) ApplyFunc(msg *TopicMsg)

func (*Topic) SendToSubUser

func (a *Topic) SendToSubUser(msg []byte)

type TopicMsg

type TopicMsg struct {
	Ori     any    //原始数据方便订阅主题的函数处理
	TopicId string //话题ID
	Msg     []byte //消息内容,方便客户端处理
}

type User

type User struct {
	//公共基础信息
	Uid          uint             `json:"uid"`                //整型唯一ID
	Suid         string           `json:"suid"`               //字符唯一ID
	GroupId      string           `json:"groupId"`            //分组ID
	SuperAdmin   bool             `json:"superAdmin"`         //是否超管
	RoleId       []uint           `json:"roleId,omitempty"`   //用户角色
	Nickname     string           `json:"nickname"`           //昵称
	Avatar       *Resource        `json:"avatar"`             //用户头像
	OnlineStatus UserOnlineStatus `json:"onlineStatus"`       //在线状态
	Location     *Location        `json:"location,omitempty"` //地理位置

	CurrentWindowId string //当前的窗口ID

	//禁言时间
	Ban *time.Time `json:"ban,omitempty"`

	//最后心跳时间
	LastHeartbeatTime time.Time

	//用户相关数据
	Hub        *Hubc     `json:"-"`
	AppClients []*Client `json:"-"` //appId对应客户端

	SubTopics map[string]*Topic `json:"-"` //topicId订阅的主题名称及信息
	sync.RWMutex
}

func NewUser

func NewUser(uid string) *User

func (*User) AddSubTopic

func (u *User) AddSubTopic(topic *Topic) int

func (*User) AppClient

func (u *User) AppClient(appId string) *Client

AppClient 获取APP客户端

func (*User) Banned

func (u *User) Banned(t time.Duration) *time.Time

Banned 禁言用户

func (*User) IsBanned

func (u *User) IsBanned() (bool, *time.Time)

IsBanned 是否被封禁

func (*User) IsOnline

func (u *User) IsOnline() bool

IsOnline 用户是否在线

func (*User) SendMsg

func (u *User) SendMsg(msg []byte)

SendMsg 发送消息

func (*User) SendMsgToApp

func (u *User) SendMsgToApp(appId string, msg []byte)

SendMsgToApp 发送消息到指定客户端

func (*User) Unban

func (u *User) Unban() *time.Time

Unban 禁言解除

func (*User) UnsubTopic

func (u *User) UnsubTopic(topicId string) int

type UserOnlineStatus

type UserOnlineStatus byte
const (
	UserStatusOnline UserOnlineStatus = iota
	UserStatusBusy
	UserStatusLeaving
)

type Value

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

func (*Value) Bool

func (v *Value) Bool() bool

func (*Value) By added in v1.2.0

func (v *Value) By(t any)

func (*Value) Duration

func (v *Value) Duration() time.Duration

func (*Value) Float32

func (v *Value) Float32() float32

func (*Value) Float64

func (v *Value) Float64() float64

func (*Value) Int

func (v *Value) Int() int

func (*Value) Int16

func (v *Value) Int16() int16

func (*Value) Int32

func (v *Value) Int32() int32

func (*Value) Int64

func (v *Value) Int64() int64

func (*Value) Int8

func (v *Value) Int8() int8

func (*Value) IsNil added in v1.2.0

func (v *Value) IsNil() bool

func (*Value) Map

func (v *Value) Map() map[string]any

func (*Value) Raw

func (v *Value) Raw() any

func (*Value) Slice

func (v *Value) Slice() []any

func (*Value) SliceInt

func (v *Value) SliceInt() []int

func (*Value) SliceString

func (v *Value) SliceString() []string

func (*Value) String

func (v *Value) String() string

func (*Value) StringMap

func (v *Value) StringMap() map[string]string

func (*Value) Time

func (v *Value) Time() time.Time

func (*Value) Uint

func (v *Value) Uint() uint

func (*Value) Uint16

func (v *Value) Uint16() uint16

func (*Value) Uint32

func (v *Value) Uint32() uint32

func (*Value) Uint64

func (v *Value) Uint64() uint64

func (*Value) Uint8

func (v *Value) Uint8() uint8

Jump to

Keyboard shortcuts

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