/
server.go
139 lines (108 loc) · 2.96 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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
package poker
import (
"encoding/json"
"fmt"
"html/template"
"log"
"net/http"
"strconv"
"strings"
"github.com/gorilla/websocket"
)
type PlayerStore interface {
GetPlayerScore(name string) int
RecordWin(name string)
GetLeague() League
}
type Player struct {
Name string
Wins int
}
func NewPlayerServer(store PlayerStore, game Game) (*PlayerServer, error) {
p := new(PlayerServer)
tmpl, err := template.ParseFiles(htmlTemplatePath)
if err != nil {
return nil, fmt.Errorf("problem opening %s, %v", htmlTemplatePath, err)
}
p.template = tmpl
p.store = store
p.game = game
router := http.NewServeMux()
router.Handle("/league", http.HandlerFunc(p.leagueHandler))
router.Handle("/players/", http.HandlerFunc(p.playersHandler))
router.Handle("/game", http.HandlerFunc(p.gameHandler))
router.Handle("/ws", http.HandlerFunc(p.webSocket))
p.Handler = router
return p, nil
}
type PlayerServer struct {
store PlayerStore
// embedding
http.Handler
template *template.Template
game Game
}
const jsonContentType = "application/json"
const htmlTemplatePath = "game.html"
func (p *PlayerServer) leagueHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("content-type", jsonContentType)
json.NewEncoder(w).Encode(p.store.GetLeague())
}
func (p *PlayerServer) playersHandler(w http.ResponseWriter, r *http.Request) {
player := strings.TrimPrefix(r.URL.Path, "/players/")
switch r.Method {
case http.MethodPost:
p.processWin(w, player)
case http.MethodGet:
p.showScore(w, player)
}
}
func (p *PlayerServer) gameHandler(w http.ResponseWriter, r *http.Request) {
p.template.Execute(w, nil)
}
var wsUpgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
func (p *PlayerServer) webSocket(w http.ResponseWriter, r *http.Request) {
ws := newPlayerServerWs(w, r)
numberOfPlayersMsg := ws.WaitForMsg()
numberOfPlayers, _ := strconv.Atoi(string(numberOfPlayersMsg))
p.game.Start(numberOfPlayers, ws)
winner := ws.WaitForMsg()
p.game.Finish(string(winner))
}
func (p *PlayerServer) showScore(w http.ResponseWriter, player string) {
score := p.store.GetPlayerScore(player)
if score == 0 {
w.WriteHeader(http.StatusNotFound)
}
fmt.Fprint(w, score)
}
func (p *PlayerServer) processWin(w http.ResponseWriter, player string) {
p.store.RecordWin(player)
w.WriteHeader(http.StatusAccepted)
}
func newPlayerServerWs(w http.ResponseWriter, r *http.Request) *playerServerWs {
conn, err := wsUpgrader.Upgrade(w, r, nil)
if err != nil {
log.Printf("problem upgrading connection to WebSockets %v\n", err)
}
return &playerServerWs{conn}
}
type playerServerWs struct {
*websocket.Conn
}
func (w *playerServerWs) WaitForMsg() string {
_, msg, err := w.ReadMessage()
if err != nil {
log.Printf("error reading from WebSocket %v\n", err)
}
return string(msg)
}
func (w *playerServerWs) Write(p []byte) (n int, err error) {
if err = w.WriteMessage(websocket.TextMessage, p); err != nil {
return 0, err
}
return len(p), nil
}