-
Notifications
You must be signed in to change notification settings - Fork 0
/
defaulter_handler.go
48 lines (38 loc) · 1.27 KB
/
defaulter_handler.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
package defaulter_handler
import (
"context"
"encoding/json"
"net/http"
"github.com/erkanzileli/admission-webhooks-the-easy-way/internal/consts"
corev1 "k8s.io/api/core/v1"
"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
)
// PodDefaulterHandler sets the consts.PodAnnotationKey as consts.PodAnnotationValue
type PodDefaulterHandler struct {
decoder *admission.Decoder
}
func NewPodDefaulterHandler() *PodDefaulterHandler {
return &PodDefaulterHandler{}
}
func (h *PodDefaulterHandler) Handle(ctx context.Context, req admission.Request) admission.Response {
pod := &corev1.Pod{}
err := h.decoder.Decode(req, pod)
if err != nil {
return admission.Errored(http.StatusBadRequest, err)
}
if pod.Annotations == nil {
pod.Annotations = map[string]string{}
}
pod.Annotations[consts.PodAnnotationKey] = consts.PodAnnotationValue
marshaledPod, err := json.Marshal(pod)
if err != nil {
return admission.Errored(http.StatusInternalServerError, err)
}
return admission.PatchResponseFromRaw(req.Object.Raw, marshaledPod)
}
// InjectDecoder injects the decoder.
// PodDefaulterHandler implements admission.DecoderInjector so a decoder will be automatically injected.
func (h *PodDefaulterHandler) InjectDecoder(d *admission.Decoder) error {
h.decoder = d
return nil
}