/
http.go
99 lines (81 loc) · 2.29 KB
/
http.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
package game
import (
"context"
"encoding/json"
"net/http"
"github.com/derailed/hangman/internal/svc"
"github.com/go-kit/kit/endpoint"
"github.com/gorilla/mux"
kitlog "github.com/go-kit/kit/log"
kithttp "github.com/go-kit/kit/transport/http"
)
const dictionaryURL = "http://localhost:9090/dictionary/v1/random_word"
type (
// NewGameRequest requests a new game given a word
NewGameRequest struct {
Word string `json:"word"`
Cookies []*http.Cookie `json:"cookies"`
}
// Response replies with the current game
Response struct {
Game Game `json:"game"`
}
// GuessRequest proposes a new guess
GuessRequest struct {
Game Game `json:"game"`
Guess string `json:"guess"`
}
)
func decodeNewGameRequest(_ context.Context, r *http.Request) (interface{}, error) {
var req NewGameRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
return nil, err
}
req.Cookies = r.Cookies()
return req, nil
}
// DecodeGuessRequest extracts guess and game state from requests
func DecodeGuessRequest(_ context.Context, r *http.Request) (interface{}, error) {
var req GuessRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
return nil, err
}
return req, nil
}
func makeNewGameEndPoint(s Service) endpoint.Endpoint {
return func(_ context.Context, request interface{}) (interface{}, error) {
req := request.(NewGameRequest)
game := s.NewGame(req.Word)
return Response{Game: game}, nil
}
}
func makeGuessEndPoint(s Service) endpoint.Endpoint {
return func(_ context.Context, request interface{}) (interface{}, error) {
req := request.(GuessRequest)
game := s.Guess(req.Game, rune(req.Guess[0]))
return Response{Game: game}, nil
}
}
// MakeHandler to serve game routes
func MakeHandler(s Service, l kitlog.Logger) http.Handler {
opts := []kithttp.ServerOption{
kithttp.ServerErrorLogger(l),
}
newGameHandler := kithttp.NewServer(
makeNewGameEndPoint(s),
decodeNewGameRequest,
svc.EncodeResponse,
opts...,
)
guessHandler := kithttp.NewServer(
makeGuessEndPoint(s),
DecodeGuessRequest,
svc.EncodeResponse,
opts...,
)
r := mux.NewRouter()
r.Handle("/game/v1/health", svc.MakeHealthHandler(opts))
r.Handle("/game/v1/new_game", newGameHandler).Methods("POST")
r.Handle("/game/v1/guess", guessHandler).Methods("POST")
return r
}