websocket

package module
v0.0.0-...-4598771 Latest Latest
Warning

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

Go to latest
Published: May 2, 2026 License: Apache-2.0 Imports: 5 Imported by: 0

README

tao-websocket

Go Report Card GoDoc

Tao Universe WebSocket 组件,基于 gorilla/websocket 封装,提供 WebSocket 连接升级能力,支持多实例配置。

安装

go get github.com/taouniverse/tao-websocket

使用

导入
import _ "github.com/taouniverse/tao-websocket"
快速开始
import (
    "net/http"
    websocket "github.com/taouniverse/tao-websocket"
)

func wsHandler(w http.ResponseWriter, r *http.Request) {
    // 创建 WebSocket 连接(使用默认配置)
    conn, err := websocket.New(w, r, websocket.Standard())
    if err != nil {
        http.Error(w, err.Error(), http.StatusBadRequest)
        return
    }
    defer conn.Close()

    // 读取消息
    data, err := conn.Read()
    if err != nil {
        return
    }

    // 发送消息
    err = conn.Write([]byte("Hello!"))
}
使用指定实例
// 使用名为 "admin" 的 Upgrader 实例创建连接
conn, err := websocket.NewWith(w, r, "admin", websocket.Standard())

配置

单实例配置
websocket:
  check_origin: true
  read_buffer_size: 1024
  write_buffer_size: 1024
多实例配置
websocket:
  default_instance: "public"  # 指定默认实例
  public:                     # 公开接口实例
    check_origin: true        # 允许跨域
    read_buffer_size: 1024
    write_buffer_size: 1024
  admin:                      # 管理接口实例
    check_origin: false       # 不允许跨域
    read_buffer_size: 4096
    write_buffer_size: 4096
    subprotocols: ["admin-v1"]
配置项说明
配置项 类型 默认值 说明
check_origin *bool true 是否允许跨域请求
read_buffer_size int 1024 读缓冲区大小(字节)
write_buffer_size int 1024 写缓冲区大小(字节)
subprotocols []string [] 支持的子协议列表

API 参考

工厂方法
API 说明
websocket.Upgrader() 获取默认实例的 Upgrader
websocket.GetUpgrader(name) 获取指定名称的 Upgrader
websocket.Factory.Get(name) 通过工厂获取 Upgrader
连接创建
API 说明
websocket.New(w, r, options...) 使用默认 Upgrader 创建连接
websocket.NewWith(w, r, name, options...) 使用指定名称的 Upgrader 创建连接
连接选项
选项 说明
websocket.Standard() 标准连接模式(带读写缓冲和 goroutine)
连接方法
方法 说明
conn.Read() 读取消息
conn.Write(data) 发送消息
conn.Close() 关闭连接

单元测试

测试文件 说明 运行条件
config_test.go Config 解析与默认值验证 无需外部依赖
websocket_test.go Upgrader 创建与多实例测试 无需外部服务
connection_test.go WebSocket 连接测试 无需外部服务
运行单元测试
# 全部测试
go test -v ./...

# 仅运行配置测试
go test -v -run TestConfig ./...

# 仅运行连接测试
go test -v -run TestNew ./...

依赖

Documentation

Index

Constants

View Source
const ConfigKey = "websocket"

ConfigKey for this repo

Variables

Factory is the global factory instance for managing ws.Upgrader

View Source
var W = &Config{}

W is the global config instance for tao-websocket

Functions

func GetUpgrader

func GetUpgrader(name string) (ws.Upgrader, error)

GetUpgrader returns the websocket upgrader instance by name

func NewWebSocket

func NewWebSocket(name string, config InstanceConfig) (ws.Upgrader, func() error, error)

NewWebSocket creates a new WebSocket upgrader for factory pattern

func Standard

func Standard() func(conn *Connection) error

Standard websocket connection

func Upgrader

func Upgrader() (ws.Upgrader, error)

Upgrader returns the default websocket upgrader instance

Types

type Config

type Config struct {
	tao.BaseMultiConfig[InstanceConfig]
	RunAfters []string `json:"run_after,omitempty" yaml:"run_after,omitempty"`
}

Config 总配置,实现 tao.MultiConfig 接口

func (*Config) Name

func (w *Config) Name() string

Name of Config

func (*Config) RunAfter

func (w *Config) RunAfter() []string

RunAfter defines pre task names

func (*Config) ToTask

func (w *Config) ToTask() tao.Task

ToTask transform itself to Task

func (*Config) ValidSelf

func (w *Config) ValidSelf()

ValidSelf with some default values

type Connection

type Connection struct {
	*ws.Conn
	// contains filtered or unexported fields
}

Connection of websocket

func New

func New(w http.ResponseWriter, r *http.Request, options ...func(*Connection) error) (*Connection, error)

New constructor of websocket connection with default upgrader

func NewWith

func NewWith(w http.ResponseWriter, r *http.Request, name string, options ...func(*Connection) error) (*Connection, error)

NewWith constructor of websocket connection with specified upgrader instance name

func (*Connection) Close

func (conn *Connection) Close() error

Close websocket connection

func (*Connection) Read

func (conn *Connection) Read() ([]byte, error)

Read request payload

func (*Connection) Request

func (conn *Connection) Request() error

Request from websocket client

func (*Connection) Response

func (conn *Connection) Response() error

Response to websocket client

func (*Connection) Write

func (conn *Connection) Write(p []byte) error

Write response payload

type InstanceConfig

type InstanceConfig struct {
	CheckOrigin     *bool    `json:"check_origin" yaml:"check_origin"`
	ReadBufferSize  int      `json:"read_buffer_size" yaml:"read_buffer_size"`
	WriteBufferSize int      `json:"write_buffer_size" yaml:"write_buffer_size"`
	Subprotocols    []string `json:"subprotocols" yaml:"subprotocols"`
}

InstanceConfig 单实例配置

Jump to

Keyboard shortcuts

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