-
-
Notifications
You must be signed in to change notification settings - Fork 239
/
websocket.go
52 lines (47 loc) · 1.01 KB
/
websocket.go
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
43
44
45
46
47
48
49
50
51
52
package examples
import (
"net/http"
"github.com/gorilla/websocket"
fastwebsocket "github.com/fasthttp/websocket"
"github.com/valyala/fasthttp"
)
// WsHttpHandler is a simple http.Handler that implements WebSocket echo server.
func WsHTTPHandler(w http.ResponseWriter, r *http.Request) {
upgrader := &websocket.Upgrader{}
c, err := upgrader.Upgrade(w, r, nil)
if err != nil {
panic(err)
}
defer c.Close()
for {
mt, message, err := c.ReadMessage()
if err != nil {
break
}
err = c.WriteMessage(mt, message)
if err != nil {
break
}
}
}
// WsFastHandler is a simple fasthttp.RequestHandler that implements
// WebSocket echo server.
func WsFastHTTPHandler(ctx *fasthttp.RequestCtx) {
var upgrader fastwebsocket.FastHTTPUpgrader
err := upgrader.Upgrade(ctx, func(c *fastwebsocket.Conn) {
defer c.Close()
for {
mt, message, err := c.ReadMessage()
if err != nil {
break
}
err = c.WriteMessage(mt, message)
if err != nil {
break
}
}
})
if err != nil {
panic(err)
}
}