-
Notifications
You must be signed in to change notification settings - Fork 6
/
handler_datacenter.go
58 lines (49 loc) · 1.18 KB
/
handler_datacenter.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
package server
import (
"encoding/json"
"io/ioutil"
"net/http"
"time"
"github.com/gbolo/vsummary/common"
"gopkg.in/go-playground/validator.v9"
)
func handlerDatacenter(w http.ResponseWriter, req *http.Request) {
// log time on debug
defer common.ExecutionTime(time.Now(), "handle")
// read in body
reqBody, err := ioutil.ReadAll(req.Body)
if err != nil {
log.Errorf("error reading request body: %s", err)
w.WriteHeader(http.StatusBadRequest)
return
}
req.Body.Close()
// decode json body
var reqStruct []common.Datacenter
err = json.Unmarshal(reqBody, &reqStruct)
if err != nil {
log.Errorf("failed to decode body: %s", err)
w.WriteHeader(http.StatusBadRequest)
return
}
// validate
// TODO: fail if any dc is invalid?
validate := validator.New()
for _, dc := range reqStruct {
err = validate.Struct(dc)
if err != nil {
log.Errorf("failed to validate body: %s", err)
w.WriteHeader(http.StatusBadRequest)
return
}
}
// insert to backend
err = backend.InsertDatacenters(reqStruct)
if err != nil {
log.Errorf("failed to insert dc: %s", err)
w.WriteHeader(http.StatusServiceUnavailable)
return
}
w.WriteHeader(http.StatusAccepted)
return
}