-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.go
36 lines (30 loc) · 1.01 KB
/
middleware.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
package goyavetrace
import (
"gopkg.in/DataDog/dd-trace-go.v1/ddtrace/tracer"
"goyave.dev/goyave/v5"
)
// Middleware substitutes the original response writer with a trace writer wrapper.
type Middleware struct {
goyave.Component
cfg Config
// SpanOptions these functions are executed before finishing the span
// associated with the request. This can be used to add custom tags to the span.
SpanOptions []SpanOption
}
// NewMiddleware create a new trace middleware.
func NewMiddleware(cfg Config, spanOptions ...SpanOption) *Middleware {
return &Middleware{
cfg: cfg,
SpanOptions: spanOptions,
}
}
// Handle substitutes the original response writer with a trace writer wrapper.
func (m Middleware) Handle(next goyave.Handler) goyave.Handler {
return func(resp *goyave.Response, req *goyave.Request) {
traceWriter := NewWriter(resp, req, m.cfg, m.SpanOptions...)
resp.SetWriter(traceWriter)
ctx := tracer.ContextWithSpan(req.Context(), traceWriter.span)
req.WithContext(ctx)
next(resp, req)
}
}