-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.go
88 lines (77 loc) · 1.92 KB
/
api.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
package api
import (
"context"
"encoding/gob"
//"encoding/gob"
"encoding/json"
"log"
"math/rand"
"net/http"
"time"
"github.com/google/uuid"
"github.com/gorilla/sessions"
"github.com/pshvedko/battleship/api/websocket"
"github.com/pshvedko/battleship/battle"
)
func init() {
rand.Seed(time.Now().Unix())
gob.Register(uuid.UUID{})
}
type Application struct {
Logging *log.Logger
Session sessions.Store
Service battle.Battle
}
func (a *Application) SessionMiddleware(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
session, err := a.Session.Get(r, "session")
for err == nil {
sid, ok := session.Values["sid"]
if !ok {
sid = uuid.New()
session.Options.SameSite = http.SameSiteLaxMode
session.Options.HttpOnly = true
session.Values["sid"] = sid
err = session.Save(r, w)
if err != nil {
break
}
}
h.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), "sid", sid)))
return
}
w.WriteHeader(http.StatusInternalServerError)
})
}
type point struct {
X int
Y int
}
type reply struct {
point
F int
C int
}
func (a *Application) Begin(w websocket.ResponseWriter, r *websocket.Request) {
s := r.Context().Value("sid").(uuid.UUID)
j := json.NewEncoder(w)
for _, p := range a.Service.Begin(s) {
w.WriteHeader(http.StatusOK)
j.Encode(reply{F: p.F(), point: point{X: p.X(), Y: p.Y()}, C: p.C()})
}
}
func (a *Application) Click(w websocket.ResponseWriter, r *websocket.Request) {
s := r.Context().Value("sid").(uuid.UUID)
var q point
json.NewDecoder(r.Body).Decode(&q)
j := json.NewEncoder(w)
for _, p := range a.Service.Click(s, q.X, q.Y) {
w.WriteHeader(http.StatusOK)
j.Encode(reply{F: p.F(), point: point{X: p.X(), Y: p.Y()}, C: p.C()})
}
}
func (a *Application) Reset(w websocket.ResponseWriter, r *websocket.Request) {
s := r.Context().Value("sid").(uuid.UUID)
a.Service.Reset(s)
w.WriteHeader(http.StatusOK)
}