-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrouter.go
65 lines (52 loc) · 1.24 KB
/
router.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
package router
import (
"encoding/json"
"io"
"log"
"net/http"
"github.com/gorilla/mux"
)
type Box struct {
Content string `json:"content"`
}
func NewRouter() *mux.Router {
boxes := map[string]string{}
r := mux.NewRouter()
r.HandleFunc("/ping", func(w http.ResponseWriter, req *http.Request) {
io.WriteString(w, "pong")
})
// GET /boxes/{id}
r.HandleFunc("/boxes/{id}", func(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
switch r.Method {
case "GET":
if box, ok := boxes[params["id"]]; ok {
resp := Box{
Content: box,
}
jResp, err := json.MarshalIndent(resp, "", " ")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
w.Header().Set("Content-Type", "application/json")
w.Write(jResp)
} else {
w.WriteHeader(http.StatusNotFound)
}
case "PUT":
body, err := io.ReadAll(r.Body)
if err != nil {
log.Fatal("Error reading body", err)
}
var box Box
err = json.Unmarshal(body, &box)
if err != nil {
log.Fatal("Error unmarshaling box", err)
}
log.Printf("Adding box[%s] = %+v", params["id"], box)
boxes[params["id"]] = box.Content
w.WriteHeader(http.StatusCreated)
}
}).Methods("GET", "PUT")
return r
}