Skip to content

Commit ae86223

Browse files
committed
fix: add health endpoint
1 parent a0f3c37 commit ae86223

File tree

3 files changed

+45
-0
lines changed

3 files changed

+45
-0
lines changed

router/router.go

+19
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,12 @@ import (
1616
"github.com/screego/server/ws"
1717
)
1818

19+
type Health struct {
20+
Status string `json:"status"`
21+
Clients int `json:"clients"`
22+
Reason string `json:"reason,omitempty"`
23+
}
24+
1925
type UIConfig struct {
2026
AuthMode string `json:"authMode"`
2127
User string `json:"user"`
@@ -47,6 +53,19 @@ func Router(conf config.Config, rooms *ws.Rooms, users *auth.Users, version stri
4753
CloseRoomWhenOwnerLeaves: conf.CloseRoomWhenOwnerLeaves,
4854
})
4955
})
56+
router.Methods("GET").Path("/health").HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
57+
i, err := rooms.Count()
58+
status := "up"
59+
if err != "" {
60+
status = "down"
61+
w.WriteHeader(500)
62+
}
63+
_ = json.NewEncoder(w).Encode(Health{
64+
Status: status,
65+
Clients: i,
66+
Reason: err,
67+
})
68+
})
5069
if conf.Prometheus {
5170
log.Info().Msg("Prometheus enabled")
5271
router.Methods("GET").Path("/metrics").Handler(basicAuth(promhttp.Handler(), users))

ws/event_health.go

+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
package ws
2+
3+
type Health struct {
4+
Response chan int
5+
}
6+
7+
func (e *Health) Execute(rooms *Rooms, current ClientInfo) error {
8+
e.Response <- len(rooms.connected)
9+
return nil
10+
}

ws/rooms.go

+16
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,22 @@ func (r *Rooms) Start() {
110110
}
111111
}
112112

113+
func (r *Rooms) Count() (int, string) {
114+
h := Health{Response: make(chan int, 1)}
115+
select {
116+
case r.Incoming <- ClientMessage{SkipConnectedCheck: true, Incoming: &h}:
117+
case <-time.After(5 * time.Second):
118+
return -1, "main loop didn't accept a message within 5 second"
119+
}
120+
r.Incoming <- ClientMessage{SkipConnectedCheck: true, Incoming: &h}
121+
select {
122+
case count := <-h.Response:
123+
return count, ""
124+
case <-time.After(5 * time.Second):
125+
return -1, "main loop didn't respond to a message within 5 second"
126+
}
127+
}
128+
113129
func (r *Rooms) closeRoom(roomID string) {
114130
room, ok := r.Rooms[roomID]
115131
if !ok {

0 commit comments

Comments
 (0)