-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathmain.go.orig
99 lines (82 loc) · 2.47 KB
/
main.go.orig
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package main
import (
"errors"
"fmt"
"log"
"math/rand"
"net/http"
"time"
"github.com/autometrics-dev/autometrics-go/prometheus/autometrics"
"github.com/autometrics-dev/autometrics-go/prometheus/midhttp"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
// This should be `//go:generate autometrics` in practice. Those are hacks to get the example working, see
// README
//go:generate go run ../../../cmd/autometrics/main.go
var (
Version = "development"
Commit = "n/a"
Branch string
)
func main() {
rand.Seed(time.Now().UnixNano())
// Everything in BuildInfo is optional.
// You can also use any string variable whose value is
// injected at build time by ldflags.
autometrics.Init(
nil,
autometrics.DefBuckets,
autometrics.BuildInfo{
Version: Version,
Commit: Commit,
Branch: Branch,
},
)
http.HandleFunc("/", errorable(indexHandler))
// Wrapping a route in Autometrics middleware
http.Handle("/random-error", midhttp.Autometrics(
http.HandlerFunc(randomErrorHandler),
autometrics.WithSloName("API"),
autometrics.WithAlertSuccess(90),
))
http.Handle("/metrics", promhttp.HandlerFor(
prometheus.DefaultGatherer,
promhttp.HandlerOpts{
EnableOpenMetrics: true,
}))
log.Println("binding on http://localhost:62086")
log.Fatal(http.ListenAndServe(":62086", nil))
}
// indexHandler handles the / route.
//
// It always succeeds and says hello.
//
//autometrics:inst --slo "API" --latency-target 99 --latency-ms 5
func indexHandler(w http.ResponseWriter, r *http.Request) error {
msSleep := rand.Intn(200)
time.Sleep(time.Duration(msSleep) * time.Millisecond)
_, err := fmt.Fprintf(w, "Slept %v ms\n", msSleep)
return err
}
var handlerError = errors.New("failed to handle request")
// randomErrorHandler handles the /random-error route.
//
// It returns an error around 90% of the time.
func randomErrorHandler(w http.ResponseWriter, r *http.Request) {
isOk := rand.Intn(10) == 0
if !isOk {
http.Error(w, handlerError.Error(), http.StatusInternalServerError)
} else {
w.WriteHeader(http.StatusOK)
}
return
}
// errorable is a wrapper to allow using functions that return `error` in route handlers.
func errorable(handler func(w http.ResponseWriter, r *http.Request) error) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
if err := handler(w, r); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
}