-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandlers.go
70 lines (56 loc) · 1.67 KB
/
handlers.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
package main
import (
"context"
"fmt"
"io"
"math/rand"
"net/http"
"time"
"go.opentelemetry.io/contrib/bridges/otelslog"
"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/codes"
)
var tracer = otel.Tracer("")
var logger = otelslog.NewLogger("")
func githubHandler(w http.ResponseWriter, r *http.Request) {
ctx, span := tracer.Start(r.Context(), "entering the githubHandler")
defer span.End()
waitAround(ctx)
req, err := http.NewRequestWithContext(r.Context(), "GET", "https://api.github.com/", nil)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
req.Header.Add("Accept", `application/json`)
client := http.Client{
Timeout: time.Duration(1) * time.Second,
Transport: otelhttp.NewTransport(http.DefaultTransport),
}
resp, err := client.Do(req)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer resp.Body.Close()
_, err = io.ReadAll(resp.Body)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if rand.Int()%2 != 0 {
span.SetStatus(codes.Error, "github handler failed")
span.RecordError(fmt.Errorf("looks like you got unlucky"))
logger.ErrorContext(ctx, "this logs the made up error")
http.Error(w, "this is a made up error", http.StatusInternalServerError)
return
}
fmt.Printf("client.Do response status : %s \n", resp.Status)
fmt.Fprint(w, "External call ok\n")
}
func waitAround(context context.Context) {
_, span := tracer.Start(context, "starting to wait around")
defer span.End()
// Add sleep to make spans more distinct
time.Sleep(50 * time.Millisecond)
}