/
jsonplaceholder.go
89 lines (77 loc) · 1.99 KB
/
jsonplaceholder.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
package httpclient
import (
"context"
"io"
"net/http"
"time"
"github.com/spf13/cobra"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/metric"
"github.com/mpapenbr/otlpdemo/log"
)
func NewJsonPlaceholderCommand() *cobra.Command {
ret := cobra.Command{
Use: "jsonplaceholder",
Short: "issue requests to jsonplaceholder",
Long: ``,
RunE: func(cmd *cobra.Command, args []string) error {
return queryJsonPlaceholder()
},
}
return &ret
}
func queryJsonPlaceholder() error {
meter := otel.Meter("jsonplaceholder")
apiCounter, err := meter.Int64Counter("api.counter",
metric.WithDescription("Number of calls"),
metric.WithUnit("{call}"))
if err != nil {
return err
}
apiDurations, err := meter.Float64Histogram("api.duration",
metric.WithDescription("The duration of task execution"),
metric.WithUnit("s"))
if err != nil {
return err
}
for i := 0; i < 30; i++ {
doit(apiCounter, apiDurations) //nolint:errcheck //temp
time.Sleep(1 * time.Second)
}
return nil
}
func doit(apiCounter metric.Int64Counter, apiDuration metric.Float64Histogram) error {
tracer := otel.Tracer("jsonplaceholder")
start := time.Now()
_, span := tracer.Start(context.Background(), "jsonplaceholder")
defer span.End()
req, err := http.NewRequestWithContext(
context.Background(),
http.MethodGet,
"https://jsonplaceholder.typicode.com/todos/1",
http.NoBody)
if err != nil {
return err
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return err
}
span.AddEvent("got result")
body, err := io.ReadAll(resp.Body)
attrs := []attribute.KeyValue{
attribute.Int("status", resp.StatusCode),
attribute.Int("bytes", len(body)),
}
span.SetAttributes(attrs...)
if err != nil {
return err
}
log.Debug("request done",
log.Int("status", resp.StatusCode), log.Int("bytes", len(body)))
resp.Body.Close()
apiCounter.Add(context.Background(), 1)
apiDuration.Record(context.Background(), (time.Since(start)).Seconds())
return nil
}