-
Notifications
You must be signed in to change notification settings - Fork 678
/
Copy pathroutesapi.go
76 lines (64 loc) · 1.77 KB
/
routesapi.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
package routesapi
import (
"encoding/json"
"io"
"log"
"net/http"
"github.com/gorilla/mux"
"github.com/gliderlabs/logspout/router"
)
func init() {
router.HTTPHandlers.Register(RoutesAPI, "routes")
}
// RoutesAPI returns a handler for the routes API
func RoutesAPI() http.Handler {
routes := router.Routes
r := mux.NewRouter()
r.HandleFunc("/routes/{id}", func(w http.ResponseWriter, req *http.Request) {
params := mux.Vars(req)
route, _ := routes.Get(params["id"])
if route == nil {
http.NotFound(w, req)
return
}
w.Write(append(marshal(route), '\n'))
}).Methods("GET")
r.HandleFunc("/routes/{id}", func(w http.ResponseWriter, req *http.Request) {
params := mux.Vars(req)
if ok := routes.Remove(params["id"]); !ok {
http.NotFound(w, req)
}
}).Methods("DELETE")
r.HandleFunc("/routes", func(w http.ResponseWriter, req *http.Request) {
w.Header().Add("Content-Type", "application/json")
rts, _ := routes.GetAll()
w.Write(append(marshal(rts), '\n'))
}).Methods("GET")
r.HandleFunc("/routes", func(w http.ResponseWriter, req *http.Request) {
route := new(router.Route)
if err := unmarshal(req.Body, route); err != nil {
http.Error(w, "Bad request: "+err.Error(), http.StatusBadRequest)
return
}
err := routes.Add(route)
if err != nil {
http.Error(w, "Bad route: "+err.Error(), http.StatusBadRequest)
return
}
w.Header().Add("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
w.Write(append(marshal(route), '\n'))
}).Methods("POST")
return r
}
func marshal(obj interface{}) []byte {
bytes, err := json.MarshalIndent(obj, "", " ")
if err != nil {
log.Println("marshal:", err)
}
return bytes
}
func unmarshal(input io.Reader, obj interface{}) error {
dec := json.NewDecoder(input)
return dec.Decode(obj)
}