This repository was archived by the owner on Aug 6, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver-status.go
More file actions
78 lines (67 loc) · 2.07 KB
/
server-status.go
File metadata and controls
78 lines (67 loc) · 2.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package serverstatus
import (
"encoding/json"
"fmt"
"net/http"
"sync"
"time"
"github.com/urfave/negroni/v2"
)
type SsRequest struct {
// TBD. What should we support?
}
type SsMiddleware struct {
path string
startTimeUnix int64
busyWorkers int64
totalAccesses int64
totalBytes int64
stats []SsRequest
mutex *sync.Mutex
}
type ssRequestJsonResponse struct {
// TBD
}
type ssJsonResponse struct {
Uptime string `json:"Uptime"`
TotalAccesses string `json:"TotalAccesses"`
TotalKbytes string `json:"TotalKbytes"`
BusyWorkers string `json:"BusyWorkers"`
IdleWorkers string `json:"IdleWorkers"`
Stats []ssRequestJsonResponse `json:"stats"`
}
// Middleware is a struct that has a ServeHTTP method
func NewMiddleware(path string) *SsMiddleware {
return &SsMiddleware{startTimeUnix: time.Now().Unix(), totalAccesses: 0, totalBytes: 0, busyWorkers: 0, mutex: new(sync.Mutex), path: path}
}
func (s *SsMiddleware) HandleServerStatus(w http.ResponseWriter, req *http.Request) {
stats := ssJsonResponse{
Uptime: fmt.Sprintf("%d", time.Now().Unix()-s.startTimeUnix),
TotalAccesses: fmt.Sprintf("%d", s.totalAccesses),
TotalKbytes: fmt.Sprintf("%d", s.totalBytes/1024),
BusyWorkers: fmt.Sprintf("%d", s.busyWorkers),
IdleWorkers: "", // XXX it's infinity!
Stats: make([]ssRequestJsonResponse, 0),
}
res, _ := json.Marshal(stats)
w.Header().Set("Content-Type", "application/json")
w.Write(res)
}
// ServeHTTP implements negroni.Handler interface
func (s *SsMiddleware) ServeHTTP(w http.ResponseWriter, req *http.Request, next http.HandlerFunc) {
s.mutex.Lock()
s.busyWorkers++
s.mutex.Unlock()
// Trap request when it is (GET|HEAD) /server-status
if req.URL.Path == s.path && (req.Method == "GET" || req.Method == "HEAD") {
s.HandleServerStatus(w, req)
} else {
next(w, req)
}
res := w.(negroni.ResponseWriter)
s.mutex.Lock()
s.totalAccesses++
s.busyWorkers--
s.totalBytes += int64(res.Size())
s.mutex.Unlock()
}