Skip to content

Instantly share code, notes, and snippets.

@alex-leonhardt
Created July 27, 2019 15:26
Show Gist options
  • Save alex-leonhardt/edd6fd402a81f9fee5944b8452b8f4d3 to your computer and use it in GitHub Desktop.
Save alex-leonhardt/edd6fd402a81f9fee5944b8452b8f4d3 to your computer and use it in GitHub Desktop.
basic https web server in go
package main
import (
"fmt"
"html"
"io/ioutil"
"log"
"net/http"
"time"
m "github.com/alex-leonhardt/k8s-mutate-webhook/pkg/mutate"
)
func handleRoot(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "hello %q", html.EscapeString(r.URL.Path))
}
func handleMutate(w http.ResponseWriter, r *http.Request) {
// read the body / 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)
}
// mutate the request
mutated, err := m.Mutate(body)
if err != nil {
log.Println(err)
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(w, "%s", err)
}
// and write it back
w.WriteHeader(http.StatusOK)
w.Write(mutated)
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/", handleRoot)
mux.HandleFunc("/mutate", handleMutate)
s := &http.Server{
Addr: ":8443",
Handler: mux,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
MaxHeaderBytes: 1 << 20, // 1048576
}
log.Fatal(s.ListenAndServeTLS("./ssl/mutateme.pem", "./ssl/mutateme.key"))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment