This repository has been archived by the owner on Aug 23, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
85 lines (71 loc) · 1.66 KB
/
server.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
77
78
79
80
81
82
83
84
85
package main
import (
"context"
"net/http"
"sync"
log "github.com/Sirupsen/logrus"
"github.com/gorilla/websocket"
"github.com/rgraphql/magellan"
proto "github.com/rgraphql/rgraphql/pkg/proto"
)
type WebServer struct {
clients map[uint32]*WSClient
clientsMtx sync.RWMutex
clientsCtr uint32
gqlServer *magellan.Server
}
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
func init() {
upgrader.CheckOrigin = func(r *http.Request) bool {
return true
}
}
func NewWebServer(
gqlServer *magellan.Server,
) *WebServer {
return &WebServer{
clients: make(map[uint32]*WSClient),
gqlServer: gqlServer,
}
}
func (ws *WebServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.WithError(err).Error("Unable to upgrade WS connection")
return
}
sendQueue := make(chan *proto.RGQLServerMessage, 20)
ws.clientsMtx.Lock()
ws.clientsCtr++
id := ws.clientsCtr
ctx, ctxCancel := context.WithCancel(context.Background())
defer ctxCancel()
gc, err := ws.gqlServer.BuildClient(ctx, sendQueue, &RootQueryResolver{}, nil)
if err != nil {
log.WithError(err).Error("Unable to build client")
return
}
client := &WSClient{
id: id,
ctx: ctx,
ctxCancel: ctxCancel,
server: ws,
sock: conn,
sendQueue: sendQueue,
gqlClient: gc,
}
ws.clients[id] = client
ws.clientsMtx.Unlock()
client.initHandlers(ws.clientDisposed)
go client.writePump()
client.readPump()
}
func (ws *WebServer) clientDisposed(id uint32) {
ws.clientsMtx.Lock()
delete(ws.clients, id)
log.WithField("id", id).Debug("Client disconnected")
ws.clientsMtx.Unlock()
}