-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathhttp_handler_list.go
66 lines (54 loc) · 1.5 KB
/
http_handler_list.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
package main
import (
"encoding/json"
"errors"
"log/slog"
"net/http"
kerrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apiserver/pkg/authentication/authenticator"
)
var _ http.Handler = &ListNamespacesHandler{}
type ListNamespacesHandler struct {
lister NamespaceLister
}
func NewListNamespacesHandler(lister NamespaceLister) http.Handler {
return &ListNamespacesHandler{
lister: lister,
}
}
func (h *ListNamespacesHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
l := getLoggerFromContext(ctx)
ud := r.Context().Value(ContextKeyUserDetails).(*authenticator.Response)
// retrieve projects as the user
nn, err := h.lister.ListNamespaces(r.Context(), ud.User.GetName())
if err != nil {
serr := &kerrors.StatusError{}
if errors.As(err, &serr) {
w.WriteHeader(int(serr.Status().Code))
h.write(l, w, []byte(serr.Error()))
return
}
w.WriteHeader(http.StatusInternalServerError)
h.write(l, w, []byte(err.Error()))
return
}
// build response
// for PoC limited to JSON
b, err := json.Marshal(nn)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
h.write(l, w, []byte(err.Error()))
return
}
w.Header().Add(HttpContentType, HttpContentTypeApplication)
h.write(l, w, b)
}
func (h *ListNamespacesHandler) write(l *slog.Logger, w http.ResponseWriter, data []byte) bool {
if _, err := w.Write(data); err != nil {
l.Error("error writing reply", "error", err)
w.WriteHeader(http.StatusInternalServerError)
return false
}
return true
}