-
Notifications
You must be signed in to change notification settings - Fork 1
/
socket.go
48 lines (37 loc) · 924 Bytes
/
socket.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
package main
import (
"context"
"fmt"
"net/http"
"nhooyr.io/websocket"
"time"
)
var SOCKET_ACCEPT_PATTERN string
var socket_table = map[string]*websocket.Conn{}
func socket_write(s *websocket.Conn, m string, r *http.Request) {
if r == nil {
fmt.Println(m)
return
}
s.Write(r.Context(), websocket.MessageText, []byte(m))
}
func socket_destroy(id string, s *websocket.Conn, m string) {
s.Close(websocket.StatusNormalClosure, m)
delete(socket_table, id)
}
func socket_create(id string, w http.ResponseWriter, r *http.Request) {
s, err := websocket.Accept(w, r, &websocket.AcceptOptions{
OriginPatterns: []string{SOCKET_ACCEPT_PATTERN},
})
if err != nil {
fmt.Printf("%v\n", err)
return
}
socket_table[id] = s
ctx, cancel := context.WithTimeout(r.Context(), 15*time.Minute)
defer cancel()
select {
case <-ctx.Done():
socket_destroy(id, s, fmt.Sprintf("timed out - %v", ctx.Err()))
}
}