Update TwiN/health to v1.1.0

This commit is contained in:
TwiN
2021-11-15 20:11:13 -05:00
parent 787f6f0d74
commit 31bf2aeb80
5 changed files with 41 additions and 16 deletions

View File

@ -1,6 +1,9 @@
package health
import "net/http"
import (
"net/http"
"sync"
)
var (
handler = &healthHandler{
@ -13,6 +16,8 @@ var (
type healthHandler struct {
useJSON bool
status Status
sync.RWMutex
}
// WithJSON configures whether the handler should output a response in JSON or in raw text
@ -24,30 +29,48 @@ func (h *healthHandler) WithJSON(v bool) *healthHandler {
}
// ServeHTTP serves the HTTP request for the health handler
func (h healthHandler) ServeHTTP(writer http.ResponseWriter, _ *http.Request) {
var status int
func (h *healthHandler) ServeHTTP(writer http.ResponseWriter, _ *http.Request) {
var statusCode int
var body []byte
if h.status == Up {
status = http.StatusOK
handlerStatus := h.getStatus()
if handlerStatus == Up {
statusCode = http.StatusOK
} else {
status = http.StatusInternalServerError
statusCode = http.StatusInternalServerError
}
if h.useJSON {
writer.Header().Set("Content-Type", "application/json")
body = []byte(`{"status":"` + h.status + `"}`)
body = []byte(`{"status":"` + handlerStatus + `"}`)
} else {
body = []byte(h.status)
body = []byte(handlerStatus)
}
writer.WriteHeader(status)
writer.WriteHeader(statusCode)
_, _ = writer.Write(body)
}
func (h *healthHandler) getStatus() Status {
h.Lock()
defer h.Unlock()
return h.status
}
func (h *healthHandler) setStatus(status Status) {
h.Lock()
h.status = status
h.Unlock()
}
// Handler retrieves the health handler
func Handler() *healthHandler {
return handler
}
// SetStatus sets the status to be reflected by the health handler
func SetStatus(status Status) {
handler.status = status
// GetStatus retrieves the current status returned by the health handler
func GetStatus() Status {
return handler.getStatus()
}
// SetStatus sets the status to be returned by the health handler
func SetStatus(status Status) {
handler.setStatus(status)
}