-
Notifications
You must be signed in to change notification settings - Fork 9
/
main.go
103 lines (84 loc) · 2.19 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
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
100
101
102
103
package main
import (
"context"
"log/slog"
"math/rand"
"net/http"
"os"
"os/signal"
"strconv"
"syscall"
"time"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"github.com/go-chi/telemetry"
)
var (
AppMetrics = &MyAppMetrics{telemetry.NewScope("app")}
)
type MyAppMetrics struct {
*telemetry.Scope
}
func (m *MyAppMetrics) RecordMyAppHit() {
m.RecordHit("my_app_hit", nil)
}
func (m *MyAppMetrics) RecordAppGauge(value float64) {
m.RecordGauge("my_app_gauge", nil, value)
}
func main() {
r := chi.NewRouter()
r.Use(middleware.Logger)
// telemetry.Collector middleware mounts /metrics endpoint
// with prometheus metrics collector.
r.Use(telemetry.Collector(telemetry.Config{
AllowAny: true,
}, []string{"/api"})) // path prefix filters records generic http request metrics
r.Route("/api", func(r chi.Router) {
r.Get("/hello", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello World!"))
})
r.Get("/hit", func(w http.ResponseWriter, r *http.Request) {
// record a hit
AppMetrics.RecordMyAppHit()
w.Write([]byte("Hit recorded!"))
})
r.Get("/gauge/{value}", func(w http.ResponseWriter, r *http.Request) {
value := chi.URLParam(r, "value")
floatValue, err := strconv.ParseFloat(value, 64)
if err != nil {
w.Write([]byte("Invalid value"))
return
}
// record a gauge
AppMetrics.RecordAppGauge(floatValue)
w.Write([]byte("Gauge recorded!"))
})
r.Get("/compute", func(w http.ResponseWriter, r *http.Request) {
span := AppMetrics.RecordSpan("compute", nil)
defer span.Stop()
// do random work for random tie,,
time.Sleep(time.Duration(rand.Intn(5)) * time.Second)
w.Write([]byte("Span recorded!"))
})
})
sig := make(chan os.Signal, 1)
signal.Notify(sig, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)
srvAddr := "localhost:3000"
srv := &http.Server{
Addr: srvAddr,
Handler: r,
}
go func() {
<-sig
slog.Info("server is shutting down")
err := srv.Shutdown(context.Background())
if err != nil {
panic(err)
}
}()
slog.Info("server is running on", "address", srvAddr)
err := srv.ListenAndServe()
if err != nil && err != http.ErrServerClosed {
panic(err)
}
}