-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchallenge.go
93 lines (78 loc) · 2.22 KB
/
challenge.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
package cmes
import (
"encoding/json"
"log"
"net/http"
"github.com/gorilla/mux"
)
type Challenge struct {
ID string `json:"id"`
Title string `json:"title"`
Description string `json:"description"`
Location string `json:"location"`
}
type Promise struct {
ID string `json:"id"`
Title string `json:"title"`
Description string `json:"description"`
}
var challenges []Challenge
var promises []Promise
func route() {
r := mux.NewRouter()
// challenge routes
r.HandleFunc("/challenge", createChallenge).Methods("POST")
r.HandleFunc("/challenge/{id}", getChallenge).Methods("GET")
r.HandleFunc("/challenges", getAllChallenges).Methods("GET")
// promise routes
r.HandleFunc("/promise", createPromise).Methods("POST")
r.HandleFunc("/promise/{id}", getPromise).Methods("GET")
r.HandleFunc("/promises", getAllPromises).Methods("GET")
log.Fatal(http.ListenAndServe(":8080", r))
}
func createChallenge(w http.ResponseWriter, r *http.Request) {
var challenge Challenge
err := json.NewDecoder(r.Body).Decode(&challenge)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
challenges = append(challenges, challenge)
json.NewEncoder(w).Encode(challenge)
}
func getChallenge(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
for _, challenge := range challenges {
if challenge.ID == params["id"] {
json.NewEncoder(w).Encode(challenge)
return
}
}
http.Error(w, "Challenge not found", http.StatusNotFound)
}
func getAllChallenges(w http.ResponseWriter, r *http.Request) {
json.NewEncoder(w).Encode(challenges)
}
func createPromise(w http.ResponseWriter, r *http.Request) {
var promise Promise
err := json.NewDecoder(r.Body).Decode(&promise)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
promises = append(promises, promise)
json.NewEncoder(w).Encode(promise)
}
func getPromise(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
for _, promise := range promises {
if promise.ID == params["id"] {
json.NewEncoder(w).Encode(promise)
return
}
}
http.Error(w, "Promise not found", http.StatusNotFound)
}
func getAllPromises(w http.ResponseWriter, r *http.Request) {
json.NewEncoder(w).Encode(promises)
}