diff --git a/app.go b/app.go index c0fac31..a03b2c1 100644 --- a/app.go +++ b/app.go @@ -4,6 +4,8 @@ import ( "encoding/json" "flag" "fmt" + "sync" + "github.com/gorilla/websocket" // "github.com/pkg/profile" "log" @@ -32,6 +34,7 @@ func main() { http.HandleFunc("/bench", benchHandler) http.HandleFunc("/", whoamI) http.HandleFunc("/api", api) + http.HandleFunc("/health", healthHandler) fmt.Println("Starting up on port " + port) log.Fatal(http.ListenAndServe(":"+port, nil)) } @@ -127,3 +130,30 @@ func api(w http.ResponseWriter, req *http.Request) { } json.NewEncoder(w).Encode(data) } + +type healthState struct { + StatusCode int +} + +var currentHealthState = healthState{200} +var mutexHealthState = &sync.RWMutex{} + +func healthHandler(w http.ResponseWriter, req *http.Request) { + if req.Method == http.MethodPost { + var statusCode int + err := json.NewDecoder(req.Body).Decode(&statusCode) + if err != nil { + w.WriteHeader(http.StatusBadRequest) + w.Write([]byte(err.Error())) + } else { + fmt.Printf("Update health check status code [%d]\n", statusCode) + mutexHealthState.Lock() + defer mutexHealthState.Unlock() + currentHealthState.StatusCode = statusCode + } + } else { + mutexHealthState.RLock() + defer mutexHealthState.RUnlock() + w.WriteHeader(currentHealthState.StatusCode) + } +}