diff --git a/health.go b/health.go index 96db543..fa806b3 100644 --- a/health.go +++ b/health.go @@ -2,12 +2,20 @@ package main import "net/http" -func healthHandler(w http.ResponseWriter, r *http.Request) { - // Currently we don't have any health probes implemented. - // We can return by default an HTTP 200 response. - // But in a future version, we will need to define how our agent - // can be marked as ready by the system to be able to trigger functions. - JSONResponse(w, &HealthResponse{ - Status: "UP", - }) +func healthHandler(downstreamUrl string) func(w http.ResponseWriter, r *http.Request) { + return func(w http.ResponseWriter, r *http.Request) { + // Perform healthcheck on the downstream URL + // If an error is returned or the status code is not 200, we consider + // for now that the downstream is not healthy + if res, err := http.Get(downstreamUrl); err != nil || res.StatusCode != 200 { + JSONResponseWithStatusCode(w, http.StatusServiceUnavailable, &HealthResponse{ + Status: "DOWN", + }) + return + } + + JSONResponse(w, &HealthResponse{ + Status: "UP", + }) + } } diff --git a/helpers.go b/helpers.go index edc9024..8575041 100644 --- a/helpers.go +++ b/helpers.go @@ -13,13 +13,18 @@ func prettyJson(b []byte) []byte { } func JSONResponse(w http.ResponseWriter, data interface{}) { + JSONResponseWithStatusCode(w, http.StatusOK, data) +} + +func JSONResponseWithStatusCode(w http.ResponseWriter, status int, data interface{}) { body, err := json.Marshal(data) if err != nil { w.WriteHeader(http.StatusInternalServerError) + return } w.Header().Set("Content-Type", "application/json; charset=utf-8") w.Header().Set("X-Content-Type-Options", "nosniff") - w.WriteHeader(http.StatusOK) + w.WriteHeader(status) w.Write(prettyJson(body)) } diff --git a/main.go b/main.go index f648c38..1cab850 100644 --- a/main.go +++ b/main.go @@ -215,7 +215,7 @@ func main() { r := http.NewServeMux() r.HandleFunc(rootEndpoint, handler(proxy)) - r.HandleFunc(healthEndpoint, healthHandler) + r.HandleFunc(healthEndpoint, healthHandler(remote.String())) server := &http.Server{ Addr: fmt.Sprintf("0.0.0.0:%d", cfg.Server.Port),