Files
canada-kaktus/internal/health.go
Tobias Trabelsi d3682557b1
All checks were successful
Gitea Docker Build Demo / Test (push) Successful in 1m2s
Gitea Docker Build Demo / Build_Image (push) Successful in 1m22s
cleanup and refactor health service
2025-10-07 11:13:15 +02:00

57 lines
1.1 KiB
Go

package internal
import (
"fmt"
"net/http"
"sync"
"github.com/gorilla/mux"
log "github.com/sirupsen/logrus"
)
type HealthServer struct {
mu sync.RWMutex
state int
}
func NewHealthServer() *HealthServer {
return &HealthServer{
state: http.StatusOK,
}
}
func (hs *HealthServer) SetHealthState(code int) {
hs.mu.Lock()
defer hs.mu.Unlock()
hs.state = code
}
func (hs *HealthServer) GetHealthState() int {
hs.mu.RLock()
defer hs.mu.RUnlock()
return hs.state
}
func (hs *HealthServer) Start() {
r := mux.NewRouter()
r.Use(mux.CORSMethodMiddleware(r))
r.HandleFunc("/health", hs.sendHealth).Methods(http.MethodGet)
err := http.ListenAndServe("0.0.0.0:8080", r)
if err != nil {
log.WithFields(log.Fields{
"Caller": "HealthServer.Start",
}).Error(fmt.Sprintf("Error creating health endpoint: %s", err.Error()))
}
}
func (hs *HealthServer) sendHealth(w http.ResponseWriter, r *http.Request) {
code := hs.GetHealthState()
w.WriteHeader(code)
_, err := w.Write([]byte{})
if err != nil {
log.WithFields(log.Fields{
"Caller": "HealthServer.sendHealth",
}).Error(fmt.Sprintf("Error answering health endpoint: %s", err.Error()))
}
}