-
Notifications
You must be signed in to change notification settings - Fork 488
/
api.go
53 lines (43 loc) · 1.23 KB
/
api.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
package metric
import (
"fmt"
"net/http"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
const (
metricURL = "/metrics"
)
// Config describe the metric server configs.
type Config struct {
IP string
MetricPort uint
}
// NewMetricServer get a new http server for metrics data.
func NewMetricServer(c *Config, collectors ...prometheus.Collector) (*Server, error) {
registry := prometheus.NewRegistry()
collectors = append([]prometheus.Collector{prometheus.NewGoCollector()}, collectors...)
for _, collector := range collectors {
if err := registry.Register(collector); err != nil {
return nil, err
}
}
handler := http.NewServeMux()
handler.Handle(metricURL, promhttp.HandlerFor(registry, promhttp.HandlerOpts{Timeout: 10 * time.Second}))
return &Server{
config: c,
registry: registry,
handler: handler,
}, nil
}
// Server describe the metric server.
type Server struct {
config *Config
registry *prometheus.Registry
handler http.Handler
}
// Start brings up the metric server and bind to address and port.
func (s *Server) Start() error {
return http.ListenAndServe(fmt.Sprintf("%s:%d", s.config.IP, s.config.MetricPort), s.handler)
}