Skip to content

Commit

Permalink
fix: add health endpoint
Browse files Browse the repository at this point in the history
  • Loading branch information
jmattheis committed Oct 11, 2024
1 parent 844cca4 commit 19e411f
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 0 deletions.
19 changes: 19 additions & 0 deletions router/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,12 @@ import (
"github.com/screego/server/ws"
)

type Health struct {
Status string `json:"status"`
Clients int `json:"clients"`
Reason string `json:"reason,omitempty"`
}

type UIConfig struct {
AuthMode string `json:"authMode"`
User string `json:"user"`
Expand Down Expand Up @@ -47,6 +53,19 @@ func Router(conf config.Config, rooms *ws.Rooms, users *auth.Users, version stri
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 {
log.Info().Msg("Prometheus enabled")
router.Methods("GET").Path("/metrics").Handler(basicAuth(promhttp.Handler(), users))
Expand Down
10 changes: 10 additions & 0 deletions ws/event_health.go
Original file line number Diff line number Diff line change
@@ -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
}
16 changes: 16 additions & 0 deletions ws/rooms.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
room, ok := r.Rooms[roomID]
if !ok {
Expand Down

0 comments on commit 19e411f

Please sign in to comment.