-
Notifications
You must be signed in to change notification settings - Fork 4
/
world.go
108 lines (92 loc) · 2.36 KB
/
world.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
package main
import (
"net/http"
"strconv"
"github.com/fnatte/pizza-tribes/internal/game"
"github.com/fnatte/pizza-tribes/internal/game/models"
"github.com/fnatte/pizza-tribes/internal/game/protojson"
"github.com/fnatte/pizza-tribes/internal/game/redis"
"github.com/gorilla/mux"
"github.com/rs/zerolog/log"
)
type WorldController struct {
r redis.RedisClient
world *game.WorldService
auth *game.AuthService
}
func (c *WorldController) Handler() http.Handler {
r := mux.NewRouter()
r.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
err := c.auth.Authorize(req)
if err != nil {
log.Error().Err(err).Msg("Failed to authorize")
w.WriteHeader(403)
return
}
state, err := c.world.GetState(req.Context())
if err != nil {
log.Error().Err(err).Msg("Failed to get state")
w.WriteHeader(500)
return
}
b, err := protojson.Marshal(state)
if err != nil {
w.WriteHeader(500)
log.Error().Err(err).Msg("Failed to entries response")
return
}
w.Header().Add("Content-Type", "application/json")
w.WriteHeader(200)
w.Write(b)
})
r.HandleFunc("/entries", func(w http.ResponseWriter, req *http.Request) {
err := c.auth.Authorize(req)
if err != nil {
log.Error().Err(err).Msg("Failed to authorize")
w.WriteHeader(403)
return
}
paramX := req.URL.Query().Get("x")
paramY := req.URL.Query().Get("y")
paramR := req.URL.Query().Get("r")
var x, y, radius int
if x, err = strconv.Atoi(paramX); err != nil {
w.WriteHeader(400)
log.Error().Err(err).Msg("Param x and y is required")
return
}
if y, err = strconv.Atoi(paramY); err != nil {
w.WriteHeader(400)
log.Error().Err(err).Msg("Param x and y is required")
return
}
if paramR != "" {
if radius, err = strconv.Atoi(paramR); err != nil {
w.WriteHeader(400)
log.Error().Err(err).Msg("Failed to parse radius")
return
}
} else {
radius = 10
}
entries, err := c.world.GetEntries(req.Context(), x, y, radius)
if err != nil {
w.WriteHeader(500)
log.Error().Err(err).Msg("Failed to get zone")
return
}
resp := models.EntriesResponse{
Entries: entries,
}
b, err := protojson.Marshal(&resp)
if err != nil {
w.WriteHeader(500)
log.Error().Err(err).Msg("Failed to entries response")
return
}
w.Header().Add("Content-Type", "application/json")
w.WriteHeader(200)
w.Write(b)
})
return r
}