forked from gavv/httpexpect
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fruits.go
85 lines (68 loc) · 1.6 KB
/
fruits.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
package examples
import (
"encoding/json"
"net/http"
"path"
)
type (
fruitMap map[string]interface{}
)
// FruitsHandler creates http.Handler for the fruits server.
//
// Routes:
// GET /fruits get fruit list
// GET /fruits/{name} get fruit
// PUT /fruits/{name} add or update fruit
func FruitsHandler() http.Handler {
fruits := fruitMap{}
mux := http.NewServeMux()
mux.HandleFunc("/fruits", func(w http.ResponseWriter, r *http.Request) {
handleFruitList(fruits, w, r)
})
mux.HandleFunc("/fruits/", func(w http.ResponseWriter, r *http.Request) {
handleFruit(fruits, w, r)
})
return mux
}
func handleFruitList(fruits fruitMap, w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "GET":
ret := []string{}
for k := range fruits {
ret = append(ret, k)
}
b, err := json.Marshal(ret)
if err != nil {
panic(err)
}
w.Header().Set("Content-Type", "application/json")
w.Write(b)
default:
w.WriteHeader(http.StatusMethodNotAllowed)
}
}
func handleFruit(fruits fruitMap, w http.ResponseWriter, r *http.Request) {
_, name := path.Split(r.URL.Path)
switch r.Method {
case "GET":
if data, ok := fruits[name]; ok {
b, err := json.Marshal(data)
if err != nil {
panic(err)
}
w.Header().Set("Content-Type", "application/json")
w.Write(b)
} else {
w.WriteHeader(http.StatusNotFound)
}
case "PUT":
var data map[string]interface{}
if err := json.NewDecoder(r.Body).Decode(&data); err != nil {
panic(err)
}
fruits[name] = data
w.WriteHeader(http.StatusNoContent)
default:
w.WriteHeader(http.StatusMethodNotAllowed)
}
}