-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathexample_test.go
80 lines (66 loc) · 1.89 KB
/
example_test.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
package promhttp
import (
"fmt"
"log"
"net/http"
"net/http/httptest"
"github.com/prometheus/client_golang/prometheus"
dto "github.com/prometheus/client_model/go"
)
func ExampleServeMux() {
// Create a promhttp ServeMux
mux := &ServeMux{
ServeMux: &http.ServeMux{},
}
// Attach two endpoints to the mux
mux.Handle("/path-a", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Println("path-b handler called")
w.WriteHeader(http.StatusOK)
}))
mux.Handle("/path-b", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Println("path-b handler called")
}))
// Create a test server to easily interact with the newly created mux.
ts := httptest.NewServer(mux)
defer ts.Close()
// Call the endpoint three times.
for i := 0; i < 3; i++ {
_, err := http.Get(ts.URL + "/path-a")
if err != nil {
log.Fatal(err)
}
}
// The following code is obtaining the Prometheus data. Normally this is
// done automatically. In this example we are going to get the the counter
// of how many times an endopint is called along with all of it's labels.
// Make the chan from which the prom metrics will come in.
in := make(chan prometheus.Metric)
// Concurrently fetch the metrics.
go mux.Collect(in)
// Create the varible to store the Prom metric
m := &dto.Metric{}
// Itterate through the incomming metrics until we get a counter.
for {
promMetric := <-in
promMetric.Write(m)
if m.Counter != nil {
break
}
}
// Display the output. First the labels for the metric.
fmt.Println("Labels:")
for _, labelPair := range m.Label {
fmt.Printf("%s -> %s\n", *labelPair.Name, *labelPair.Value)
}
// Then the value of the counter.
fmt.Println("Endpoint calls:", *m.Counter.Value)
// Output:
// path-b handler called
// path-b handler called
// path-b handler called
// Labels:
// code -> 200
// method -> get
// path -> /path-a
// Endpoint calls: 3
}