Skip to content

Instantly share code, notes, and snippets.

@karrick
Created October 4, 2018 17:49
Show Gist options
  • Save karrick/590ada6bab43d5aaa1b077a38821d633 to your computer and use it in GitHub Desktop.
Save karrick/590ada6bab43d5aaa1b077a38821d633 to your computer and use it in GitHub Desktop.
makeHealthcheck returns a healthcheck http.HandlerFunc
package main
import (
"fmt"
"io/ioutil"
"net/http"
"os"
gohm "github.com/karrick/gohm/v2"
)
func makeHealthcheck(downfilePathname string) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Headers are always going to be the same for this request.
h := w.Header()
h.Set("Cache-Control", "no-cache, no-store")
h.Set("Content-Type", "text/plain; charset=utf-8")
// When no down file, reply Status OK, and text GOOD.
fi, err := os.Stat(downfilePathname)
if err != nil {
if _, err = w.Write([]byte("GOOD\r\n")); err != nil {
gohm.Error(w, err.Error(), http.StatusInternalServerError)
}
return
}
// Otherwise, reply Status Service Unavailable, with text "BAD".
if fi.Size() == 0 {
// When empty down file, just reply.
gohm.Error(w, fmt.Sprintf("BAD: %s\r\n", downfilePathname), http.StatusServiceUnavailable)
return
}
// Otherwise, append down file contents to response.
message, err := ioutil.ReadFile(downfilePathname)
if err != nil {
message = []byte(err.Error())
}
gohm.Error(w, fmt.Sprintf("BAD: %s\r\n%s\r\n", downfilePathname, message), http.StatusServiceUnavailable)
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment