-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
82 lines (70 loc) · 2.23 KB
/
main.go
File metadata and controls
82 lines (70 loc) · 2.23 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
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
// httpserver demonstrates the httputil middleware wrapping a real HTTP server.
// Spans are created automatically for each request with method, path, status,
// and response size annotations.
package main
import (
"context"
"fmt"
"math/rand/v2"
"net/http"
"time"
"storj.io/hydrant"
"storj.io/hydrant/config"
"storj.io/hydrant/filter"
"storj.io/hydrant/process"
"storj.io/hydrant/submitters"
"storj.io/hydrant/utils/httputil"
)
func main() {
sub, err := submitters.Environment{
Filter: filter.NewBuiltinEnvionment(),
Process: process.DefaultStore,
}.New(config.Config{
Submitter: config.GrouperSubmitter{
FlushInterval: 10 * time.Second,
GroupBy: []string{"name"},
Submitter: config.HydratorSubmitter{},
},
})
if err != nil {
panic(err)
}
hydrant.SetDefaultSubmitter(sub)
go sub.Run(context.Background())
// Application routes wrapped with hydrant middleware.
mux := http.NewServeMux()
mux.HandleFunc("GET /api/users", handleUsers)
mux.HandleFunc("GET /api/slow", handleSlow)
mux.HandleFunc("GET /api/error", handleError)
// Mount the web UI and the instrumented app on different paths.
http.Handle("/ui/", http.StripPrefix("/ui", sub.Handler()))
http.Handle("/", httputil.Wrap(mux))
// Drive some traffic so there's data to look at.
go driveTraffic()
fmt.Println("app at http://localhost:9912/api/users")
fmt.Println("web UI at http://localhost:9912/ui/")
panic(http.ListenAndServe(":9912", nil))
}
func handleUsers(w http.ResponseWriter, r *http.Request) {
time.Sleep(time.Duration(rand.IntN(20)) * time.Millisecond)
fmt.Fprintln(w, `[{"id":1,"name":"alice"},{"id":2,"name":"bob"}]`)
}
func handleSlow(w http.ResponseWriter, r *http.Request) {
time.Sleep(time.Duration(rand.IntN(500)+200) * time.Millisecond)
fmt.Fprintln(w, `{"status":"ok"}`)
}
func handleError(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintln(w, `{"error":"something broke"}`)
}
func driveTraffic() {
paths := []string{"/api/users", "/api/users", "/api/users", "/api/slow", "/api/error"}
for {
time.Sleep(50 * time.Millisecond)
path := paths[rand.IntN(len(paths))]
resp, err := http.Get("http://localhost:9912" + path)
if err == nil {
resp.Body.Close()
}
}
}