-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
163 lines (132 loc) · 3.65 KB
/
main.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
152
153
154
155
156
157
158
159
160
161
162
163
package main
import (
"encoding/json"
"log"
"net/http"
"os"
"github.com/go-chi/chi/v5"
"github.com/rs/zerolog"
"github.com/rs/zerolog/hlog"
zlog "github.com/rs/zerolog/log"
)
type GameState struct {
Game Game `json:"game"`
Turn int `json:"turn"`
Board Board `json:"board"`
You Battlesnake `json:"you"`
}
type Game struct {
ID string `json:"id"`
Ruleset Ruleset `json:"ruleset"`
Timeout int32 `json:"timeout"`
}
type Ruleset struct {
Name string `json:"name"`
Version string `json:"version"`
}
type Board struct {
Height int `json:"height"`
Width int `json:"width"`
Food []Coord `json:"food"`
Snakes []Battlesnake `json:"snakes"`
// Used in non-standard game modes
Hazards []Coord `json:"hazards"`
}
type Battlesnake struct {
ID string `json:"id"`
Name string `json:"name"`
Health int32 `json:"health"`
Body []Coord `json:"body"`
Head Coord `json:"head"`
Length int32 `json:"length"`
Latency string `json:"latency"`
// Used in non-standard game modes
Shout string `json:"shout"`
Squad string `json:"squad"`
}
type Coord struct {
X int `json:"x"`
Y int `json:"y"`
}
// Response Structs
type BattlesnakeInfoResponse struct {
APIVersion string `json:"apiversion"`
Author string `json:"author"`
Color string `json:"color"`
Head string `json:"head"`
Tail string `json:"tail"`
}
type BattlesnakeMoveResponse struct {
Move string `json:"move"`
Shout string `json:"shout,omitempty"`
}
// HTTP Handlers
func HandleIndex(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
response := info(ctx)
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(response); err != nil {
zerolog.Ctx(ctx).Error().Err(err).Msg("ERROR: Failed to encode info response")
}
}
func HandleStart(w http.ResponseWriter, r *http.Request) {
state := GameState{}
if err := json.NewDecoder(r.Body).Decode(&state); err != nil {
zlog.Printf("ERROR: Failed to decode start json, %s", err)
return
}
start(r.Context(), state)
}
func HandleMove(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
logger := zerolog.Ctx(ctx)
state := GameState{}
if err := json.NewDecoder(r.Body).Decode(&state); err != nil {
logger.Error().Err(err).Msg("Failed to decode move json")
return
}
logger.UpdateContext(func(c zerolog.Context) zerolog.Context {
c = c.Str("GameID", state.Game.ID)
c = c.Str("SnakeID", state.You.ID)
c = c.Int("Turn", state.Turn)
c = c.Stringer("url", r.URL)
return c
})
response := move(r.Context(), state)
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(response); err != nil {
logger.Error().Err(err).Msg("Failed to encode move response")
return
}
}
func HandleEnd(w http.ResponseWriter, r *http.Request) {
state := GameState{}
err := json.NewDecoder(r.Body).Decode(&state)
if err != nil {
zlog.Printf("ERROR: Failed to decode end json, %s", err)
return
}
end(r.Context(), state)
// Nothing to respond with here
}
func main() {
port := os.Getenv("PORT")
if len(port) == 0 {
port = "3000"
}
logger := zlog.Output(zerolog.ConsoleWriter{Out: os.Stderr})
// Replace the global logger
log.SetFlags(0)
log.SetOutput(logger)
r := chi.NewRouter()
r.Use(hlog.NewHandler(logger))
r.Use(hlog.RequestIDHandler("req_id", "Request-Id"))
r.Get("/", HandleIndex)
r.Post("/start", HandleStart)
r.Post("/move", HandleMove)
r.Post("/end", HandleEnd)
logger.Info().Msgf("Starting Battlesnake Server at http://0.0.0.0:%s...", port)
if err := http.ListenAndServe(":"+port, r); err != nil {
logger.Panic().Err(err).Msg("ListenAndServe error")
}
}