-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
71 lines (57 loc) · 2.05 KB
/
main.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
package main
import (
"fmt"
"log"
"net/http"
"os"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
var (
environment = os.Getenv("ENVIRONMENT")
appVersion string
version = prometheus.NewGauge(prometheus.GaugeOpts{
Name: "version",
Help: "Version information about this binary",
ConstLabels: map[string]string{
"version": appVersion,
},
})
httpRequestsTotal = prometheus.NewCounterVec(prometheus.CounterOpts{
Name: "http_requests_total",
Help: "Count of all HTTP requests",
}, []string{"code", "method"})
httpRequestDuration = prometheus.NewHistogramVec(prometheus.HistogramOpts{
Name: "http_request_duration_seconds",
Help: "Duration of all HTTP requests",
}, []string{"code", "handler", "method"})
foundHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte(fmt.Sprintf("New feature: Hello World from %s", environment)))
})
notfoundHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
})
internalErrorHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusInternalServerError)
})
)
var r *prometheus.Registry // Exported Prometheus registry variable
func main() {
version.Set(1)
r = prometheus.NewRegistry()
r.MustRegister(httpRequestsTotal)
r.MustRegister(httpRequestDuration)
r.MustRegister(version)
foundChain := promhttp.InstrumentHandlerDuration(
httpRequestDuration.MustCurryWith(prometheus.Labels{"handler": "found"}),
promhttp.InstrumentHandlerCounter(httpRequestsTotal, foundHandler),
)
mux := http.NewServeMux()
mux.Handle("/", foundChain)
mux.Handle("/err", promhttp.InstrumentHandlerCounter(httpRequestsTotal, notfoundHandler))
mux.Handle("/internal-err", promhttp.InstrumentHandlerCounter(httpRequestsTotal, internalErrorHandler))
mux.Handle("/metrics", promhttp.HandlerFor(r, promhttp.HandlerOpts{}))
srv := &http.Server{Addr: ":8080", Handler: mux}
log.Fatal(srv.ListenAndServe())
}