-
Notifications
You must be signed in to change notification settings - Fork 429
/
Copy pathhttp.go
41 lines (34 loc) · 1.28 KB
/
http.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
package metrics
import (
"errors"
"net/http"
"github.com/go-chi/chi/v5"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
// CreateRegistryAndServeHTTP establishes an HTTP server that exposes the /metrics endpoint for Prometheus at the given address.
// It returns a new prometheus registry (to register the metrics on) and a canceling function that ends the server.
func CreateRegistryAndServeHTTP(addr string) (registry *prometheus.Registry, cancel func()) {
registry = prometheus.NewRegistry()
return registry, ServeHTTP(addr, registry)
}
// ServeHTTP establishes an HTTP server that exposes the /metrics endpoint for Prometheus at the given address.
// It takes an existing Prometheus registry and returns a canceling function that ends the server.
func ServeHTTP(addr string, registry *prometheus.Registry) (cancel func()) {
router := chi.NewRouter()
handler := promhttp.HandlerFor(registry, promhttp.HandlerOpts{})
router.Get("/metrics", func(w http.ResponseWriter, r *http.Request) {
handler.ServeHTTP(w, r)
})
server := http.Server{
Addr: addr,
Handler: router,
}
go func() {
err := server.ListenAndServe()
if !errors.Is(err, http.ErrServerClosed) {
panic(err)
}
}()
return func() { _ = server.Close() }
}