This repository has been archived by the owner on Aug 19, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
83 lines (68 loc) · 1.76 KB
/
main.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
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"time"
"k8s.io/api/admission/v1beta1"
)
// Based on https://medium.com/ovni/writing-a-very-basic-kubernetes-mutating-admission-webhook-398dbbcb63ec
func handleRoot(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, world!")
}
func handleHealthz(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "ok")
}
func handleMutate(w http.ResponseWriter, r *http.Request) {
// Decode the request
body, err := ioutil.ReadAll(r.Body)
defer r.Body.Close()
if err != nil {
log.Println(err)
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(w, "%s", err)
return
}
admissionReview := v1beta1.AdmissionReview{}
if err := json.Unmarshal(body, &admissionReview); err != nil {
log.Println(err)
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(w, "%s", err)
return
}
response, err := mutate(*admissionReview.Request)
if err != nil {
log.Println(err)
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(w, "%s", err)
return
}
reviewResponse := v1beta1.AdmissionReview{
Response: &response,
}
if body, err = json.Marshal(reviewResponse); err != nil {
log.Println(err)
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(w, "%s", err)
return
}
w.WriteHeader(http.StatusOK)
w.Write(body)
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/", handleRoot)
mux.HandleFunc("/_healthz", handleHealthz)
mux.HandleFunc("/mutate", handleMutate)
s := &http.Server{
Addr: ":8443",
Handler: mux,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
MaxHeaderBytes: 1 << 20,
}
log.Println("Listening on :8443")
log.Fatal(s.ListenAndServeTLS("./certs/tls.crt", "./certs/tls.key"))
}