-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.go
More file actions
55 lines (47 loc) · 1.23 KB
/
middleware.go
File metadata and controls
55 lines (47 loc) · 1.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
package tracing
import (
"bytes"
"encoding/json"
"net/http"
"github.com/go-chi/chi/v5/middleware"
"github.com/go-chi/traceid"
)
func Middleware(errorFn func(http.ResponseWriter, error)) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var body bytes.Buffer
ww := middleware.NewWrapResponseWriter(w, r.ProtoMajor)
ww.Tee(&body)
ww.Discard()
tid := traceid.FromContext(r.Context())
ctx, span := Trace(
r.Context(),
r.URL.Path,
WithSpanKind(SpanKindServer),
WithMetadata(map[string]any{
"sequence.traceid": tid,
"net.host.name": r.Host,
"server.address": r.Host,
"http.method": r.Method,
"http.url": r.URL.String(),
"url.path": r.URL.Path,
"url.query": r.URL.RawQuery,
}),
)
next.ServeHTTP(ww, r.WithContext(ctx))
span.SetStatus(ww.Status())
span.End()
spanJSON, err := json.Marshal(span)
if err != nil {
errorFn(w, err)
return
}
w.Header().Set("X-Sequence-Span", string(spanJSON))
w.WriteHeader(ww.Status())
if _, err := body.WriteTo(w); err != nil {
errorFn(w, err)
return
}
})
}
}