-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.go
82 lines (70 loc) · 1.54 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
package server
import (
"errors"
"net/http"
"github.com/go-chi/render"
"github.com/google/uuid"
"github.com/nathan-osman/guessing-game/manager"
)
var (
errEmptyName = errors.New("a valid name must be supplied for the game")
)
type apiGame struct {
Name string `json:"name"`
}
func (g *apiGame) Bind(r *http.Request) error {
if g.Name == "" {
return errEmptyName
}
return nil
}
type apiGameReadOnly struct {
*apiGame
UUID string `json:"uuid"`
}
func (*apiGameReadOnly) Render(w http.ResponseWriter, r *http.Request) error {
return nil
}
type apiError struct {
Error string `json:"error"`
}
func (*apiError) Render(w http.ResponseWriter, r *http.Request) error {
return nil
}
func (s *Server) apiGames(w http.ResponseWriter, r *http.Request) {
s.mutex.Lock()
defer s.mutex.Unlock()
games := []render.Renderer{}
for uuid, m := range s.managers {
games = append(games, &apiGameReadOnly{
apiGame: &apiGame{
Name: m.Name(),
},
UUID: uuid,
})
}
render.RenderList(w, r, games)
}
func (s *Server) apiJoin(w http.ResponseWriter, r *http.Request) {
//...
}
func (s *Server) apiCreate(w http.ResponseWriter, r *http.Request) {
s.mutex.Lock()
defer s.mutex.Unlock()
game := &apiGame{}
if err := render.Bind(r, game); err != nil {
render.Render(w, r, &apiError{
Error: err.Error(),
})
return
}
gameUUID := uuid.Must(uuid.NewRandom()).String()
s.managers[gameUUID] = manager.New(&manager.Config{
Name: game.Name,
Logger: s.baseLogger,
})
render.Render(w, r, &apiGameReadOnly{
apiGame: game,
UUID: gameUUID,
})
}