-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtracinghandler.go
50 lines (42 loc) · 1.18 KB
/
tracinghandler.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
package tracing
import (
"net/http"
"github.com/opentracing/opentracing-go"
"github.com/opentracing/opentracing-go/ext"
)
type withHTTPCodeResponse struct {
writer http.ResponseWriter
code int
}
func (w *withHTTPCodeResponse) Header() http.Header {
return w.writer.Header()
}
func (w *withHTTPCodeResponse) Write(bytes []byte) (int, error) {
return w.writer.Write(bytes)
}
func (w *withHTTPCodeResponse) WriteHeader(code int) {
w.writer.WriteHeader(code)
w.code = code
}
// OpenTracingHandler http.Handler.
func OpenTracingHandler(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
tracer := opentracing.GlobalTracer()
spanCtx, _ := tracer.Extract(
opentracing.HTTPHeaders,
opentracing.HTTPHeadersCarrier(r.Header))
span := tracer.StartSpan(r.RequestURI, opentracing.ChildOf(spanCtx))
ext.HTTPMethod.Set(span, r.Method)
defer span.Finish()
cw := &withHTTPCodeResponse{writer: w}
rc := opentracing.ContextWithSpan(r.Context(), span)
r = r.WithContext(rc)
defer func() {
ext.HTTPStatusCode.Set(span, uint16(cw.code))
if cw.code >= http.StatusBadRequest {
ext.Error.Set(span, true)
}
}()
next(cw, r)
}
}