Skip to content

Instantly share code, notes, and snippets.

@checkaayush
Created October 24, 2018 07:58
Show Gist options
  • Select an option

  • Save checkaayush/4f1ea5bdc802a48087d442a3ebf0c17b to your computer and use it in GitHub Desktop.

Select an option

Save checkaayush/4f1ea5bdc802a48087d442a3ebf0c17b to your computer and use it in GitHub Desktop.

Revisions

  1. checkaayush created this gist Oct 24, 2018.
    46 changes: 46 additions & 0 deletions server.go
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,46 @@
    package main

    import (
    "fmt"
    "log"
    "net/http"
    "os"
    )

    // main starts an HTTP server listening on $PORT which dispatches to request handlers.
    func main() {
    http.Handle("/healthz", http.HandlerFunc(healthcheckHandler))
    // wrap the poweredByHandler with logging middleware
    http.Handle("/", logRequestMiddleware(http.HandlerFunc(poweredByHandler)))
    port := "8000"
    log.Printf("listening on %v...\n", port)
    err := http.ListenAndServe(":"+port, nil)
    if err != nil {
    panic(err)
    }
    }

    // poweredByHandler writes "Powered by $POWERED_BY" to the response.
    func poweredByHandler(w http.ResponseWriter, r *http.Request) {
    hostname, _ := os.Hostname()
    fmt.Fprintf(w, "Hello World! Container: %v", hostname)
    }

    // healthcheckHandler returns 200 for kubernetes healthchecks.
    func healthcheckHandler(w http.ResponseWriter, r *http.Request) {
    w.WriteHeader(http.StatusOK)
    w.Write([]byte("OK"))
    }

    // logRequestMiddleware writes out HTTP request information before passing to the next handler.
    func logRequestMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    remote := r.RemoteAddr
    if forwardedFor := r.Header.Get("X-Forwarded-For"); forwardedFor != "" {
    remote = forwardedFor
    }
    log.Printf("%s %s %s", remote, r.Method, r.URL)
    // pass the request to the next handler
    next.ServeHTTP(w, r)
    })
    }