-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
47 lines (42 loc) · 1.37 KB
/
main.go
File metadata and controls
47 lines (42 loc) · 1.37 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
package main
import (
"fmt"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"log"
"net/http"
"time"
)
func main() {
requestCountMetric := prometheus.NewCounterVec(prometheus.CounterOpts{
Namespace: "hello_server",
Name: "request_count",
}, []string{"method", "path"})
err := prometheus.Register(requestCountMetric)
if err != nil {
log.Fatalf("Could not register requestCountMetric: %v", err)
}
defer prometheus.Unregister(requestCountMetric)
requestDurationMetric := prometheus.NewSummaryVec(prometheus.SummaryOpts{
Namespace: "hello_server",
Name: "request_duration",
}, []string{"method", "path"})
err = prometheus.Register(requestDurationMetric)
if err != nil {
log.Fatalf("Could not register requestDurationMetric: %v", err)
}
defer prometheus.Unregister(requestDurationMetric)
http.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
requestCountMetric.WithLabelValues(r.Method, "/hello").Add(1)
startTime := time.Now()
defer func() {
requestDurationMetric.WithLabelValues(r.Method, "/hello").Observe(time.Since(startTime).Seconds())
}()
fmt.Println("Received request for /hello")
fmt.Fprintln(w, "Hello World")
})
http.Handle("/metrics", promhttp.Handler())
port := ":8080"
log.Printf("Server started on %s", port)
log.Fatal(http.ListenAndServe(port, nil))
}