MinWs

package module
v0.8.0 Latest Latest
Warning

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

Go to latest
Published: Jun 22, 2026 License: MIT Imports: 12 Imported by: 0

README

MinWs

一个用 Go 标准库从零实现的轻量级 WebSocket 服务端,遵循 RFC 6455零第三方依赖

特性

  • 完整的握手升级(Sec-WebSocket-Accept 计算 + 连接 Hijack)
  • 帧解析与构建,支持 7/16/64 位负载长度
  • 掩码(Masking)处理,原地异或
  • 控制帧支持:Ping / Pong / Close
  • 分片消息聚合(Aggregator),可配置最大负载上限
  • 文本帧 UTF-8 校验、Close 状态码校验(RFC 6455 §7.4.1)
  • 基于回调的事件模型:OnOpen / OnMessage / OnClose / OnError
  • 使用 sync.Pool 复用读取缓冲,减少分配

环境要求

  • Go 1.25+

快速开始

package main

import "net/http"

func main() {
	http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
		client, err := Upgrade(w, r)
		if err != nil {
			return
		}

		client.OnOpen = func() {
			// 连接建立
		}
		client.OnMessage = func(data []byte) {
			// 回显收到的消息
			client.SendText("echo: " + string(data))
		}
		client.OnClose = func() {
			// 连接关闭
		}
		client.OnError = func(err error) {
			// 处理错误
		}

		client.Listen() // 启动读取循环(非阻塞,内部 goroutine)
	})

	http.ListenAndServe(":8080", nil)
}

API 概览

升级
函数 说明
Upgrade(w http.ResponseWriter, r *http.Request) (*Client, error) 完成握手并返回 *Client
Client
字段 / 方法 说明
OnOpen func() 连接建立时触发
OnMessage func(data []byte) 收到完整消息(文本/二进制)时触发
OnClose func() 连接关闭时触发
OnError func(err error) 发生错误时触发
Listen() 启动后台读取循环
SendText(text string) 发送文本帧
SendBinary(data []byte) 发送二进制帧
Ping() 发送 Ping 帧
Pong(payload []byte) 发送 Pong 帧
Close() 正常关闭连接
CloseWith(code uint16, reason string) error 以指定状态码和原因关闭

项目结构

文件 职责
Upgrader.go HTTP 握手升级与连接 Hijack
FrameResolver.go 帧的读取、解析、构建与发送,Client 事件循环
Aggregation.go 分片消息聚合
Validation.go UTF-8 校验

许可证

MIT © 2026 23jdd

Documentation

Index

Constants

View Source
const (
	OpcodeContinuation = 0x0
	OpcodeText         = 0x1
	OpcodeBinary       = 0x2
	OpcodeClose        = 0x8
	OpcodePing         = 0x9
	OpcodePong         = 0xA
)

WebSocket 常量定义

View Source
const (
	CloseNormalClosure           uint16 = 1000
	CloseGoingAway               uint16 = 1001
	CloseProtocolError           uint16 = 1002
	CloseUnsupportedData         uint16 = 1003
	CloseNoStatusReceived        uint16 = 1005
	CloseInvalidFramePayloadData uint16 = 1007
	ClosePolicyViolation         uint16 = 1008
	CloseMessageTooBig           uint16 = 1009
	CloseMandatoryExtension      uint16 = 1010
	CloseInternalServerErr       uint16 = 1011
)

Close 状态码 (RFC 6455 §7.4.1)

Variables

This section is empty.

Functions

func IsValidUtf8

func IsValidUtf8(d []byte) bool

func Mask

func Mask(data []byte, key []byte)

Mask 统一掩码算法 (原地异或,高效)

Types

type Aggregator

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

func NewAggregator

func NewAggregator(maxsize uint) *Aggregator

func (*Aggregator) Clear

func (a *Aggregator) Clear()

func (*Aggregator) Received

func (a *Aggregator) Received(data []byte) error

type Client

type Client struct {
	OnOpen    func()
	OnClose   func()
	OnError   func(err error)
	OnMessage func(data []byte)
	// contains filtered or unexported fields
}

func Upgrade

func Upgrade(w http.ResponseWriter, r *http.Request) (*Client, error)

func (*Client) Close

func (client *Client) Close()

func (*Client) CloseWith

func (client *Client) CloseWith(code uint16, reason string) error

CloseWith 发送带状态码和原因的 Close 帧

func (*Client) Listen

func (c *Client) Listen()

func (*Client) Ping

func (client *Client) Ping()

func (*Client) Pong

func (client *Client) Pong(pingPayload []byte)

func (*Client) SendBinary

func (client *Client) SendBinary(data []byte)

func (*Client) SendText

func (client *Client) SendText(text string)

type Connect

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

func NewConnect

func NewConnect(maxsize uint) *Connect

func (*Connect) ReadHeader

func (c *Connect) ReadHeader() (*FrameHeader, error)

ReadHeader 解析报头

func (*Connect) ReadPayload

func (c *Connect) ReadPayload(header *FrameHeader) ([]byte, error)

ReadPayload 读取并解密负载数据

func (*Connect) WriteFrame

func (c *Connect) WriteFrame(opcode byte, isMasked bool, data []byte) error

WriteFrame 构建并发送 WebSocket 帧

type FrameHeader

type FrameHeader struct {
	Fin    bool
	Opcode byte
	Masked bool
	Length uint64
}

Jump to

Keyboard shortcuts

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