/
handle_mappings.go
69 lines (55 loc) · 1.6 KB
/
handle_mappings.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
package admin
import (
"encoding/json"
"net/http"
myhttp "github.com/Everbridge/go-proxy/http"
"github.com/Everbridge/go-proxy/mapping"
"github.com/gorilla/mux"
)
func handleGetMappings(w http.ResponseWriter, req *http.Request) {
respondWithMappings(w, req)
}
func handlePutMapping(w http.ResponseWriter, req *http.Request) {
mappingID := mux.Vars(req)["mappingID"]
decoder := json.NewDecoder(req.Body)
var passedInMapping mapping.Mapping
err := decoder.Decode(&passedInMapping)
if err != nil {
myhttp.InternalError(req, w, err)
return
}
err = mapping.Set(mappingID, passedInMapping)
if err != nil {
myhttp.InternalError(req, w, err)
return
}
respondWithMappings(w, req)
}
func handlePutMappings(w http.ResponseWriter, req *http.Request) {
decoder := json.NewDecoder(req.Body)
var passedInMappings []mapping.Mapping
err := decoder.Decode(&passedInMappings)
if err != nil {
myhttp.InternalError(req, w, err)
return
}
err = mapping.SetAll(passedInMappings)
if err != nil {
myhttp.InternalError(req, w, err)
return
}
respondWithMappings(w, req)
}
func registerMappingsEndpoints(router *mux.Router) {
router.HandleFunc("/api/mappings", handleGetMappings).Methods(http.MethodGet)
router.HandleFunc("/api/mappings", handlePutMappings).Methods(http.MethodPut)
router.HandleFunc("/api/mappings/{mappingID}", handlePutMapping).Methods(http.MethodPut)
}
func respondWithMappings(w http.ResponseWriter, req *http.Request) {
mappings, mappingError := mapping.GetMappings()
if mappingError != nil {
myhttp.InternalError(req, w, mappingError)
return
}
responseWithJSON(mappings, w, req)
}