-
-
Notifications
You must be signed in to change notification settings - Fork 17
/
addLinkedCloud.go
60 lines (54 loc) · 1.5 KB
/
addLinkedCloud.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
package service
import (
"bytes"
"fmt"
"net/http"
"github.com/plgd-dev/cloud/cloud2cloud-connector/events"
"github.com/plgd-dev/cloud/cloud2cloud-connector/store"
"github.com/gofrs/uuid"
"github.com/plgd-dev/kit/codec/json"
)
func writeJson(w http.ResponseWriter, v interface{}) error {
data, err := json.Encode(v)
if err != nil {
return err
}
w.Header().Set(events.ContentTypeKey, "application/json")
_, err = w.Write(data)
if err != nil {
return err
}
return nil
}
func (rh *RequestHandler) addLinkedCloud(w http.ResponseWriter, r *http.Request) (int, error) {
buffer := bytes.NewBuffer(make([]byte, 0, 1024))
_, err := buffer.ReadFrom(r.Body)
if err != nil {
return http.StatusBadRequest, fmt.Errorf("cannot read body: %w", err)
}
var l store.LinkedCloud
err = json.Decode(buffer.Bytes(), &l)
if err != nil {
return http.StatusBadRequest, fmt.Errorf("cannot decode body: %w", err)
}
uuid, err1 := uuid.NewV4()
if err1 != nil {
return http.StatusBadRequest, fmt.Errorf("cannot generate uuid %v", err1)
}
l.ID = uuid.String()
l, _, err = rh.store.LoadOrCreateCloud(r.Context(), l)
if err != nil {
return http.StatusBadRequest, err
}
err = writeJson(w, l)
if err != nil {
return http.StatusInternalServerError, err
}
return http.StatusOK, nil
}
func (rh *RequestHandler) AddLinkedCloud(w http.ResponseWriter, r *http.Request) {
statusCode, err := rh.addLinkedCloud(w, r)
if err != nil {
logAndWriteErrorResponse(fmt.Errorf("cannot add linked cloud: %w", err), statusCode, w)
}
}