-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontext_websocket.go
More file actions
42 lines (36 loc) · 1022 Bytes
/
context_websocket.go
File metadata and controls
42 lines (36 loc) · 1022 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// Package gin 提供基于 Gin 的增强上下文与相关组件。
package gin
import (
"net/http"
"github.com/darkit/gin/pkg/websocket"
ws "github.com/gorilla/websocket"
)
// UpgradeWebSocket 升级 HTTP 连接为 WebSocket,userID 为连接标识。
// opts 为 WebSocket 选项配置。
func (c *Context) UpgradeWebSocket(userID string, opts ...websocket.WSOption) (*websocket.WebSocket, error) {
// 合并选项
options := websocket.DefaultWSOptions()
for _, opt := range opts {
if opt != nil {
opt(options)
}
}
// 创建 upgrader
upgrader := ws.Upgrader{
ReadBufferSize: options.ReadBufferSize(),
WriteBufferSize: options.WriteBufferSize(),
CheckOrigin: func(r *http.Request) bool {
if options.CheckOrigin() != nil {
return options.CheckOrigin()(r)
}
return true
},
}
// 升级连接
conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
if err != nil {
return nil, err
}
// 创建 WebSocket 包装
return websocket.NewWebSocket(conn, userID, options), nil
}