-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
75 lines (60 loc) · 1.69 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
package kroki
import (
"log"
"net/http"
"github.com/gorilla/websocket"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
type Server struct {
handler http.Handler
upgrader *websocket.Upgrader
games GameRepo
// Metrics
numClients prometheus.Gauge
}
type GameRepo interface {
GetOrCreate(string) (*Game, error)
}
func NewServer() Server {
var (
upgrader = &websocket.Upgrader{}
mux = http.NewServeMux()
games = NewRepo()
numClients = promauto.NewGauge(prometheus.GaugeOpts{
Namespace: "kroki",
Subsystem: "websocket",
Name: "num_clients",
Help: "Number of currently connected clients",
})
s = Server{mux, upgrader, games, numClients}
)
upgrader.CheckOrigin = func(_ *http.Request) bool { return true }
mux.Handle("/metrics", promhttp.Handler())
mux.HandleFunc("/_healthz", s.handleHealthz)
mux.HandleFunc("/ws", s.handleWS)
mux.Handle("/", http.FileServer(http.Dir("public")))
return s
}
func (s Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
s.handler.ServeHTTP(w, r)
}
func (s Server) handleHealthz(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNoContent)
}
func (s Server) handleWS(w http.ResponseWriter, r *http.Request) {
conn, err := s.upgrader.Upgrade(w, r, nil)
if err != nil {
log.Println(err.Error())
http.Error(w, "", http.StatusInternalServerError)
return
}
s.readLoop(conn)
}
func sendState(conn *websocket.Conn, game *Game) {
msg := &Message{Event: "update", Payload: game}
if err := conn.WriteJSON(msg); err != nil {
log.Println("Error writing response:", err)
}
}