-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathhttp_server.go
113 lines (87 loc) · 2 KB
/
http_server.go
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
package metrics
import (
"fmt"
"net/http"
"github.com/gorilla/mux"
)
type Server struct {
metrics *Metrics
cfg *ServerConfig
}
type ServerConfig struct {
Addr string
}
func NewServer(metrics *Metrics, cfg *ServerConfig) *Server {
return &Server{metrics: metrics, cfg: cfg}
}
func (s Server) Run() error {
http.Handle("/", s.GetHandler(""))
return http.ListenAndServe(s.cfg.Addr, nil)
}
func (s Server) GetHandler(prefix string) http.Handler {
handler := func(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
metricType := params["type"]
metricName := params["name"]
var (
metricValue string
err error
)
switch metricType {
case "system":
metricValue, err = s.getSystemMetrics(metricName)
break
case "internal":
metricValue, err = s.getInternalMetrics(metricName)
break
default:
err = fmt.Errorf("unknown metric type: %s", metricType)
break
}
if err != nil {
w.Write([]byte(err.Error()))
return
}
w.Write([]byte(metricValue))
}
rtr := mux.NewRouter()
rtr.HandleFunc("/"+prefix+"/{type:[a-zA-Z_]+}/{name:[a-zA-Z_]+}", handler).Methods("GET")
return rtr
}
func (s Server) getSystemMetrics(name string) (string, error) {
value := .0
switch name {
case "cpu":
value = s.metrics.System.CPU()
break
case "ram":
value = s.metrics.System.RAM()
break
case "disk":
value = s.metrics.System.Disk()
break
}
if value == .0 {
return "", fmt.Errorf("unknown metric name: %s", name)
}
return fmt.Sprintf("%.2f", value), nil
}
func (s Server) getInternalMetrics(name string) (string, error) {
value := ""
counterValue, err := s.metrics.Internal.Counter.Get(name)
if err != nil {
return "", err
}
avgCounterValue, err := s.metrics.Internal.AvgCounter.GetAvg(name)
if err != nil {
return "", err
}
if counterValue != 0 {
value = fmt.Sprintf("%d", counterValue)
} else if avgCounterValue != 0 {
value = fmt.Sprintf("%d", avgCounterValue)
} else {
value = fmt.Sprintf("%d", 0)
}
return value, nil
}