-
Notifications
You must be signed in to change notification settings - Fork 1
/
objects.go
104 lines (96 loc) · 2.55 KB
/
objects.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package gateway
import (
"bytes"
"encoding/json"
"net/http"
"github.com/go-chi/chi/v5"
"github.com/nats-io/nats.go"
"github.com/verifa/horizon/pkg/hz"
)
type ObjectsHandler struct {
Conn *nats.Conn
}
func (o *ObjectsHandler) router() *chi.Mux {
r := chi.NewRouter()
r.Get("/", o.get)
r.Post("/", o.create)
r.Patch("/", o.apply)
r.Delete("/{group}/{version}/{kind}/{account}/{name}", o.delete)
return r
}
func (o *ObjectsHandler) create(w http.ResponseWriter, r *http.Request) {
client := hz.NewClient(o.Conn, hz.WithClientSessionFromRequest(r))
var obj hz.GenericObject
if err := json.NewDecoder(r.Body).Decode(&obj); err != nil {
http.Error(
w,
"decoding request body: "+err.Error(),
http.StatusBadRequest,
)
return
}
if err := client.Create(r.Context(), hz.WithCreateObject(obj)); err != nil {
httpError(w, err)
return
}
w.WriteHeader(http.StatusCreated)
}
func (o *ObjectsHandler) get(w http.ResponseWriter, r *http.Request) {
key := hz.ObjectKey{
Group: r.URL.Query().Get("group"),
Version: r.URL.Query().Get("version"),
Kind: r.URL.Query().Get("kind"),
Name: r.URL.Query().Get("name"),
Account: r.URL.Query().Get("account"),
}
client := hz.NewClient(o.Conn, hz.WithClientSessionFromRequest(r))
resp := bytes.Buffer{}
if err := client.List(
r.Context(),
hz.WithListKey(key),
hz.WithListResponseWriter(&resp),
); err != nil {
httpError(w, err)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write(resp.Bytes())
}
func (o *ObjectsHandler) apply(w http.ResponseWriter, r *http.Request) {
manager := r.Header.Get(hz.HeaderApplyFieldManager)
client := hz.NewClient(
o.Conn,
hz.WithClientSessionFromRequest(r),
hz.WithClientManager(manager),
)
var obj hz.GenericObject
if err := json.NewDecoder(r.Body).Decode(&obj); err != nil {
http.Error(
w,
"decoding request body: "+err.Error(),
http.StatusBadRequest,
)
return
}
if _, err := client.Apply(r.Context(), hz.WithApplyObject(obj)); err != nil {
httpError(w, err)
return
}
w.WriteHeader(http.StatusOK)
}
func (o *ObjectsHandler) delete(w http.ResponseWriter, r *http.Request) {
key := hz.ObjectKey{
Group: chi.URLParam(r, "group"),
Version: chi.URLParam(r, "version"),
Kind: chi.URLParam(r, "kind"),
Account: chi.URLParam(r, "account"),
Name: chi.URLParam(r, "name"),
}
client := hz.NewClient(o.Conn, hz.WithClientSessionFromRequest(r))
if err := client.Delete(r.Context(), hz.WithDeleteKey(key)); err != nil {
httpError(w, err)
return
}
w.WriteHeader(http.StatusNoContent)
}