-
Notifications
You must be signed in to change notification settings - Fork 12
/
websocket_controller.go
76 lines (64 loc) · 1.51 KB
/
websocket_controller.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package controllers
import (
"fmt"
nethttp "net/http"
"github.com/goravel/framework/contracts/http"
"github.com/gorilla/websocket"
)
/*********************************
1. Install package
go get -u github.com/gorilla/websocket
2. Add route to `/route/web.go`
3. Run Server
air
4. Run Client
cd ./packages/websocket_client && go run .
5. Result
Server got `ping` and Client got `pong`
********************************/
type WebsocketController struct {
// Dependent services
}
func NewWebsocketController() *WebsocketController {
return &WebsocketController{
// Inject services
}
}
func (r *WebsocketController) Server(ctx http.Context) http.Response {
upGrader := websocket.Upgrader{
ReadBufferSize: 4096, // Specify the read buffer size
WriteBufferSize: 4096, // Specify the write buffer size
// Detect request origin
CheckOrigin: func(r *nethttp.Request) bool {
if r.Method != "GET" {
fmt.Println("method is not GET")
return false
}
if r.URL.Path != "/ws" {
fmt.Println("path error")
return false
}
return true
},
}
ws, err := upGrader.Upgrade(ctx.Response().Writer(), ctx.Request().Origin(), nil)
if err != nil {
return ctx.Response().String(http.StatusInternalServerError, err.Error())
}
defer ws.Close()
for {
mt, message, err := ws.ReadMessage()
fmt.Println("Received:", string(message))
if err != nil {
break
}
if string(message) == "ping" {
message = []byte("pong")
}
err = ws.WriteMessage(mt, message)
if err != nil {
break
}
}
return nil
}