Skip to content

Commit

Permalink
feat: forward healthcheck to underlying process
Browse files Browse the repository at this point in the history
Signed-off-by: thomasgouveia <gouveia.thomas@outlook.fr>
  • Loading branch information
thomasgouveia committed May 26, 2023
1 parent 93ffd28 commit 058d8aa
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 10 deletions.
24 changes: 16 additions & 8 deletions health.go
Original file line number Diff line number Diff line change
Expand Up @@ -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",
})
}
}
7 changes: 6 additions & 1 deletion helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -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))
}
2 changes: 1 addition & 1 deletion main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down

0 comments on commit 058d8aa

Please sign in to comment.