-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
107 lines (82 loc) · 2.25 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
package poker
import (
"encoding/json"
"fmt"
"html/template"
"net/http"
"strconv"
"github.com/gorilla/websocket"
)
type PlayerStore interface {
GetPlayerScore(name string) int
RecordWin(name string)
GetLeague() League
}
type Player struct {
Name string
Wins int
}
type PlayerServer struct {
store PlayerStore
http.Handler
template *template.Template
game Game
}
const jsonContentType = "application/json"
const htmlTemplatePath = "game.html"
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.game = game
p.template = tmpl
p.store = store
router := http.NewServeMux()
router.Handle("/league", http.HandlerFunc(p.leagueHander))
router.Handle("/players/", http.HandlerFunc(p.playersHandler))
router.Handle("/game", http.HandlerFunc(p.playGame))
router.Handle("/ws", http.HandlerFunc(p.websocket))
p.Handler = router
return p, nil
}
func (p *PlayerServer) leagueHander(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 := r.URL.Path[len("/players/"):]
switch r.Method {
case http.MethodPost:
p.processWin(w, player)
case http.MethodGet:
p.showScore(w, player)
}
}
func (p *PlayerServer) playGame(w http.ResponseWriter, r *http.Request) {
p.template.Execute(w, nil)
}
var upgrader = 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(numberOfPlayersMsg)
p.game.Start(numberOfPlayers, ws)
winner := ws.WaitForMsg()
p.game.Finish(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)
}