-
Notifications
You must be signed in to change notification settings - Fork 7
/
handler.go
54 lines (47 loc) · 1.33 KB
/
handler.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
package jhop
import (
"encoding/json"
"fmt"
"io"
"net/http"
"strconv"
"github.com/gorilla/mux"
"github.com/pkg/errors"
)
// NewHandler generates new http.Handler, which handles
// resources from given files.
func NewHandler(rs ...io.Reader) (http.Handler, error) {
router := mux.NewRouter()
for _, r := range rs {
var resources map[string]interface{}
if err := json.NewDecoder(r).Decode(&resources); err != nil {
return nil, errors.Wrap(err, "unmarshal failed")
}
addResource(router, resources)
}
return router, nil
}
func addResource(r *mux.Router, resources map[string]interface{}) {
for k := range resources {
p := k // why doing this? see https://stackoverflow.com/a/44045012/4794989
r.HandleFunc(fmt.Sprintf("/%s", p), func(w http.ResponseWriter, r *http.Request) {
json.NewEncoder(w).Encode(map[string]interface{}{p: resources[p]})
}).Methods("GET")
r.HandleFunc(fmt.Sprintf("/%s/{id}", p), func(w http.ResponseWriter, r *http.Request) {
switch v := resources[p].(type) {
case []interface{}:
for _, m := range v {
id, _ := strconv.ParseInt(mux.Vars(r)["id"], 10, 64)
if int64(m.(map[string]interface{})["id"].(float64)) == id {
json.NewEncoder(w).Encode(m)
return
}
}
http.NotFound(w, r)
return
default:
http.NotFound(w, r)
}
}).Methods("GET")
}
}