-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
151 lines (119 loc) · 3.47 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
140
141
142
143
144
145
146
147
148
149
150
151
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"strconv"
"github.com/julienschmidt/httprouter"
)
const (
playerCookieConst = "player_id"
)
type ErrorMessage struct {
Message string `json:"error"`
}
type MatchResponse struct {
Id string `json:"match"`
Board [][]int `json:"board"`
MyTurn bool `json:"my_turn"`
}
type Handler struct {
dealer Dealer
}
func startServer(d Dealer) error {
log.SetFlags(log.LstdFlags | log.Lshortfile)
h := Handler{dealer: d}
router := httprouter.New()
router.GET("/", h.joinMatch)
router.GET("/:matchId", h.getMatch)
router.PUT("/:matchId/:pit", h.move)
return http.ListenAndServe(":8080", router)
}
func (h Handler) joinMatch(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
defer handle5xx(w)
defer setContectType(w)
match, playerId := h.dealer.JoinMatch()
response := MatchResponse{Id: match.Id, Board: match.Board, MyTurn: false}
bs, _ := json.Marshal(response)
cookie := &http.Cookie{
Name: playerCookieConst,
Value: playerId,
}
http.SetCookie(w, cookie)
w.Write(bs)
}
func (h Handler) getMatch(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
defer handle5xx(w)
defer setContectType(w)
matchIdParam := ps.ByName("matchId")
playerCookie, err := r.Cookie(playerCookieConst)
if err != nil {
log.Print("ERROR - player cookie missing")
writeErrorResponse("not your match", http.StatusUnauthorized, w)
return
}
http.SetCookie(w, playerCookie)
match, err := h.dealer.GetMatch(matchIdParam, playerCookie.Value)
if err != nil {
log.Printf("ERROR - match %v not found: %v", matchIdParam, err)
msg := fmt.Sprintf("match %v not found", matchIdParam)
writeErrorResponse(msg, http.StatusNotFound, w)
return
}
myTurn := h.dealer.PlayerTurn(*match, playerCookie.Value)
if playerCookie.Value == match.P2 {
tmp := match.Board[0]
match.Board[0] = match.Board[1]
match.Board[1] = tmp
}
response := MatchResponse{Id: match.Id, Board: match.Board, MyTurn: myTurn}
bs, _ := json.Marshal(response)
w.Write(bs)
}
func (h Handler) move(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
defer handle5xx(w)
defer setContectType(w)
matchIdParam := ps.ByName("matchId")
pit, _ := strconv.Atoi(ps.ByName("pit"))
playerCookie, err := r.Cookie(playerCookieConst)
if err != nil {
log.Print("ERROR - player cookie missing")
writeErrorResponse("not your match", http.StatusUnauthorized, w)
return
}
http.SetCookie(w, playerCookie)
m, err := h.dealer.GetMatch(matchIdParam, playerCookie.Value)
if err != nil {
log.Printf("ERROR - match %v not found: %v", matchIdParam, err)
msg := fmt.Sprintf("match %v not found", matchIdParam)
writeErrorResponse(msg, http.StatusNotFound, w)
return
}
validMove, err := h.dealer.MakeMove(pit, *m, playerCookie.Value)
if err != nil {
log.Printf("ERROR - invalid move: %v", err)
writeErrorResponse("invalid move", http.StatusBadRequest, w)
return
}
if validMove {
w.WriteHeader(http.StatusAccepted)
return
}
w.WriteHeader(http.StatusNoContent)
}
func setContectType(w http.ResponseWriter) {
w.Header().Add("Content-Type", "application/json")
}
func writeErrorResponse(msg string, statusCode int, w http.ResponseWriter) {
errMsg := ErrorMessage{Message: msg}
errorBs, _ := json.Marshal(errMsg)
w.WriteHeader(statusCode)
w.Write(errorBs)
}
func handle5xx(w http.ResponseWriter) {
if r := recover(); r != nil {
log.Println("ERROR - InternalServerError: ", r)
w.WriteHeader(http.StatusInternalServerError)
}
}