fix: add health endpoint

This commit is contained in:
Jannis Mattheis
2024-10-11 14:56:44 +02:00
parent a0f3c37498
commit ae86223ace
3 changed files with 45 additions and 0 deletions

View File

@@ -16,6 +16,12 @@ import (
"github.com/screego/server/ws" "github.com/screego/server/ws"
) )
type Health struct {
Status string `json:"status"`
Clients int `json:"clients"`
Reason string `json:"reason,omitempty"`
}
type UIConfig struct { type UIConfig struct {
AuthMode string `json:"authMode"` AuthMode string `json:"authMode"`
User string `json:"user"` User string `json:"user"`
@@ -47,6 +53,19 @@ func Router(conf config.Config, rooms *ws.Rooms, users *auth.Users, version stri
CloseRoomWhenOwnerLeaves: conf.CloseRoomWhenOwnerLeaves, CloseRoomWhenOwnerLeaves: conf.CloseRoomWhenOwnerLeaves,
}) })
}) })
router.Methods("GET").Path("/health").HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
i, err := rooms.Count()
status := "up"
if err != "" {
status = "down"
w.WriteHeader(500)
}
_ = json.NewEncoder(w).Encode(Health{
Status: status,
Clients: i,
Reason: err,
})
})
if conf.Prometheus { if conf.Prometheus {
log.Info().Msg("Prometheus enabled") log.Info().Msg("Prometheus enabled")
router.Methods("GET").Path("/metrics").Handler(basicAuth(promhttp.Handler(), users)) router.Methods("GET").Path("/metrics").Handler(basicAuth(promhttp.Handler(), users))

10
ws/event_health.go Normal file
View File

@@ -0,0 +1,10 @@
package ws
type Health struct {
Response chan int
}
func (e *Health) Execute(rooms *Rooms, current ClientInfo) error {
e.Response <- len(rooms.connected)
return nil
}

View File

@@ -110,6 +110,22 @@ func (r *Rooms) Start() {
} }
} }
func (r *Rooms) Count() (int, string) {
h := Health{Response: make(chan int, 1)}
select {
case r.Incoming <- ClientMessage{SkipConnectedCheck: true, Incoming: &h}:
case <-time.After(5 * time.Second):
return -1, "main loop didn't accept a message within 5 second"
}
r.Incoming <- ClientMessage{SkipConnectedCheck: true, Incoming: &h}
select {
case count := <-h.Response:
return count, ""
case <-time.After(5 * time.Second):
return -1, "main loop didn't respond to a message within 5 second"
}
}
func (r *Rooms) closeRoom(roomID string) { func (r *Rooms) closeRoom(roomID string) {
room, ok := r.Rooms[roomID] room, ok := r.Rooms[roomID]
if !ok { if !ok {