websocket

package
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Mar 19, 2026 License: MIT Imports: 8 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var MessageTypeAck = MessageType("__ack__")
View Source
var MessageTypeHeartbeat = MessageType([]byte{202}) // heartbeat

Functions

func WrapperBytesToWebsocketResponse

func WrapperBytesToWebsocketResponse(id, responseToId string, msgType MessageType, data []byte) []byte

Return messagetype.WebSocketReponse wrapped, when receive data, unwrap it first

func WrapperErrorToWebsocketResponse

func WrapperErrorToWebsocketResponse(id, responseToId string, msgType MessageType, err error) []byte

Return messagetype.WebSocketReponse wrapped, when receive data, unwrap it first

Types

type ClientMsgHandler

type ClientMsgHandler interface {
	HandleTextMessage(payload string, auth voAuth.WebsocketAuth, sendFn func([]byte))
	HandleBinMessage(payload []byte, auth voAuth.WebsocketAuth, sendFn func([]byte))
}

type ConnectionManager

type ConnectionManager interface {
	AddConnection(connection WebsocketConn)
	RemoveConnection(auth voAuth.WebsocketAuth)

	GetConnection(auth voAuth.WebsocketAuth) (conn WebsocketConn, ok bool)
	GetAllUserConn(userID string) []WebsocketConn
	GetAllAnonymousConn() []WebsocketConn
	GetAllAuthenticatedConn() []WebsocketConn
	GetAllConnections() []WebsocketConn
}

type ExchangeToken

type ExchangeToken interface {
	// From auth token parse to voAuth.WebsocketAuth, then create new conn tmp token and store it in cache with ttl.
	Exchange(ctx context.Context, auth voAuth.WebsocketAuth) (connTmpToken string, aerr aerror.AError)
	// Scan
	ScanConnToken(ctx context.Context, connTmpToken string) (auth voAuth.WebsocketAuth, aerr aerror.AError)
}

ExchangeToken create new token from auth token, the new token will be used to connect to websocket server later. It has a short ttl (e.g: 15s), that enough for client to connect to websocket server but not enough for attacker to use it later.

type MessageType

type MessageType string

type OnBinMessageFn

type OnBinMessageFn func(
	payload []byte,
	auth voAuth.WebsocketAuth,
	sendFn func([]byte),
)

type OnCloseStuffFn

type OnCloseStuffFn interface {
	GetStuffs() []voAuth.WebsocketAuth // GetStuffs returns the auths that need to be processed on close

	// Register registers the function to be called on close event for a given auth
	Register(auth voAuth.WebsocketAuth, fn func(auth voAuth.WebsocketAuth))

	RegisterAll(fn func(auth voAuth.WebsocketAuth))

	// Do function executes the registered function for the given auth and removes it from the map
	Do(auth voAuth.WebsocketAuth)
}

type OnNewStuffFn

type OnNewStuffFn interface {
	Register(key OnNewWsKeyName, fn func(conn WebsocketConn) error)
	Deregister(key OnNewWsKeyName)

	Do(conn WebsocketConn) error
}

type OnNewWsKeyName

type OnNewWsKeyName string

type OnReadErrorFn

type OnReadErrorFn func(auth voAuth.WebsocketAuth, err error)

type OnTextMessageFn

type OnTextMessageFn func(
	payload string,
	auth voAuth.WebsocketAuth,
	sendFn func([]byte),
)

type OnWriteErrorFn

type OnWriteErrorFn func(auth voAuth.WebsocketAuth, err error)

type RateLimiter

type RateLimiter interface {
	Get(auth voAuth.WebsocketAuth) *rate.Limiter
	New(auth voAuth.WebsocketAuth) *rate.Limiter
	Remove(auth voAuth.WebsocketAuth)
}

type ServerDelivery

type ServerDelivery interface {
	/* Mux returns an *http.ServeMux with all WebSocket endpoints pre-registered:
	- POST /issue-tmp-token
		- Input:
			- Header: Authorization
		- Output:
			- Body: string (connection token)
	- GET /gw
		- Input:
			- Query:
				- tk: string (connection token issued by /issue-tmp-token)
		- Output:
			- websocket connection is established
	*/
	Mux() *http.ServeMux
}

type SessionInfo added in v0.1.1

type SessionInfo struct {
	InstanceID  string
	ConnectedAt time.Time
	IsAnonymous bool
}

SessionInfo contains information about an active user session.

type WebsocketConn

type WebsocketConn interface {
	Auth() voAuth.WebsocketAuth
	Send(payload []byte)
	Close()
	Ping()
}

type WebsocketResponse

type WebsocketResponse struct {
	Id           string      `msgpack:"i,omitempty"`
	ResponseToId string      `msgpack:"r,omitempty"`
	MsgType      MessageType `msgpack:"t"`
	Error        string      `msgpack:"e,omitempty"`
	Binary       []byte      `msgpack:"b,omitempty"`
	AckId        string      `msgpack:"a,omitempty"`
}

func (*WebsocketResponse) Marshall

func (wsRes *WebsocketResponse) Marshall() []byte

func (*WebsocketResponse) Unmarshall

func (wsRes *WebsocketResponse) Unmarshall(data []byte) error

type WebsocketResquest

type WebsocketResquest struct {
	Id      string      `msgpack:"i,omitempty"`
	MsgType MessageType `msgpack:"t"`
	Binary  []byte      `msgpack:"b,omitempty"`
}

func (*WebsocketResquest) Marshall

func (wsReq *WebsocketResquest) Marshall() []byte

func (*WebsocketResquest) Unmarshall

func (wsReq *WebsocketResquest) Unmarshall(data []byte) error

type WebsocketServer

type WebsocketServer interface {
	NewConnection(
		conn net.Conn,
		propAuth voAuth.WebsocketAuth,
	) (wsConn WebsocketConn, aErr aerror.AError)
}

type WsService

type WsService interface {
	// SendToSession broadcasts to all containers to find the specific instanceID.
	SendToSession(ctx context.Context, userID string, instanceID string, msgType string, payload []byte) aerror.AError

	// SendToUser broadcasts to all containers to find all sessions of the given userID.
	SendToUser(ctx context.Context, userID string, msgType string, payload []byte) aerror.AError

	// PingConnections actively pings all connected clients to verify liveness.
	// Broadcasts to all containers; removes sessions that do not respond.
	// Browser automatically responds with Pong when:
	//   - Tab is active/focused
	//   - Page is not suspended
	//   - JavaScript engine is running
	//   - WebSocket connection is open
	//   - Browser process is active
	PingConnections()

	SendToAnonymous(ctx context.Context, msgType string, payload []byte, isSendAll bool, instanceID []string) aerror.AError

	CheckOnline(ctx context.Context, userID string) (isOnline bool, aErr aerror.AError)

	Shutdown()

	// DisconnectSession force disconnects a specific session.
	DisconnectSession(ctx context.Context, userID string, instanceID string) aerror.AError

	// DisconnectUser force disconnects all sessions of a user.
	DisconnectUser(ctx context.Context, userID string) aerror.AError

	// SendToUsers broadcasts to multiple users in a single publish.
	SendToUsers(ctx context.Context, userIDs []string, msgType string, payload []byte) aerror.AError

	// Broadcast sends to all connected clients based on target filter.
	Broadcast(ctx context.Context, target int, msgType string, payload []byte) aerror.AError

	// CheckOnlineMultiple checks online status of multiple users at once.
	CheckOnlineMultiple(ctx context.Context, userIDs []string) (map[string]bool, aerror.AError)

	// GetUserSessions returns detailed session info for a user.
	GetUserSessions(ctx context.Context, userID string) ([]SessionInfo, aerror.AError)

	// SendToSessionWithAck sends to a specific session and waits for client acknowledgment.
	SendToSessionWithAck(ctx context.Context, userID string, instanceID string, msgType string, payload []byte, timeout time.Duration) (acked bool, aErr aerror.AError)

	// SendToUserWithAck sends to a user and waits for client acknowledgment.
	SendToUserWithAck(ctx context.Context, userID string, msgType string, payload []byte, timeout time.Duration) (acked bool, aErr aerror.AError)
}

Jump to

Keyboard shortcuts

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