-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathhandlers.go
100 lines (86 loc) · 2.27 KB
/
handlers.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
package main
import (
"encoding/json"
"github.com/gorilla/mux"
"log"
"net/http"
"github.com/cloudfoundry-samples/pong_matcher_go/domain"
)
type MatchRequestPersister func(domain.MatchRequest) error
type MatchRequestRetriever func(string) (bool, domain.MatchRequest, error)
type MatchRetriever func(string) (bool, domain.Match)
type ResultPersister func(domain.Result) error
type Wiper func() error
func AllHandler(wipe Wiper) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if err := wipe(); err != nil {
w.WriteHeader(500)
}
}
}
func CreateMatchRequestHandler(persist MatchRequestPersister) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var matchRequest domain.MatchRequest
decoder := json.NewDecoder(r.Body)
if err := decoder.Decode(&matchRequest); err != nil {
w.WriteHeader(400)
return
}
matchRequest.Uuid = mux.Vars(r)["uuid"]
if err := persist(matchRequest); err != nil {
w.WriteHeader(500)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(200)
}
}
func GetMatchRequestHandler(retrieve MatchRequestRetriever) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
found, matchRequest, err := retrieve(mux.Vars(r)["uuid"])
if err != nil {
w.WriteHeader(500)
return
}
if found {
js, err := json.Marshal(matchRequest)
if err != nil {
log.Fatalln("Error writing JSON:", err)
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(200)
w.Write(js)
} else {
w.WriteHeader(404)
}
}
}
func MatchHandler(retrieve MatchRetriever) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if found, match := retrieve(mux.Vars(r)["uuid"]); found {
js, err := json.Marshal(match)
if err != nil {
log.Fatalln("Error writing JSON:", err)
}
w.WriteHeader(200)
w.Write(js)
} else {
w.WriteHeader(404)
}
}
}
func ResultsHandler(persist ResultPersister) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var result domain.Result
decoder := json.NewDecoder(r.Body)
if err := decoder.Decode(&result); err != nil {
w.WriteHeader(400)
return
}
if err := persist(result); err != nil {
w.WriteHeader(500)
} else {
w.WriteHeader(201)
}
}
}