in webhooks/alloydb-nodeselector-mwh/handlers/pod_nodeselector_handler.go [49:102]
func serve(w http.ResponseWriter, r *http.Request, admit AdmitFunc) {
if r.Method != http.MethodPost {
if r.Header.Get("User-Agent") == "Kubelet" {
w.WriteHeader(http.StatusOK)
return
}
log.Errorf("handlers.serve():Received a %s request instead of POST", r.Method)
http.Error(w, fmt.Sprintf("Only POST requests are accepted, received: %s", r.Method), http.StatusMethodNotAllowed)
return
}
var body []byte
if r.Body != nil {
if data, err := io.ReadAll(r.Body); err != nil {
log.Errorf("handlers.serve():Error occured while reading from the request %v", err)
http.Error(w, fmt.Sprintf("Could not read the request body or the request body is empty: %v", err), http.StatusBadRequest)
return
} else {
body = data
}
} else {
http.Error(w, "Empty request received from the client", http.StatusBadRequest)
return
}
defer r.Body.Close()
contentType := r.Header.Get("Content-Type")
if contentType != "application/json" {
log.Errorf("handlers.serve():Error occurred, content-type must be set to application/json but received %s", contentType)
http.Error(w, fmt.Sprintf("Invalid Content-Type header received: %s", contentType), http.StatusBadRequest)
return
}
addmissionReview := v1beta1.AdmissionReview{}
if err := json.Unmarshal(body, &addmissionReview); err != nil {
log.Errorf("handlers.serve():Could not unmarshall the AdmissionReview object from the request:: %v", err)
http.Error(w, fmt.Sprintf("Could not unmarshall AdmissionReview from the request body is empty:: %v", err), http.StatusBadRequest)
return
}
log.Infof("handlers.serve():Received a valid AdmissionReview for mutating the pod UID = %s", addmissionReview.Request.UID)
admissionResponse := admit(&addmissionReview, nodelSelectors)
addmissionReview.Response = admissionResponse
resp, err := json.Marshal(addmissionReview)
if err != nil {
log.Errorf("handlers.serve():Error marshalling the AdmissionReview object:: %v", err)
http.Error(w, fmt.Sprintf("Error marshalling the AdmissionReview object:: %v", err), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
if _, err := w.Write(resp); err != nil {
log.Errorf("handlers.serve():Error writing JSON response back to the client:: %v", err)
http.Error(w, fmt.Sprintf("Error writing the JSON back to the client:: %v", err), http.StatusInternalServerError)
return
}
}