|
| 1 | +package telemetry |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "net/http" |
| 6 | + |
| 7 | + "github.com/go-chi/chi/middleware" |
| 8 | + "github.com/go-chi/chi/v5" |
| 9 | + "go.opentelemetry.io/otel" |
| 10 | + "go.opentelemetry.io/otel/attribute" |
| 11 | + "go.opentelemetry.io/otel/codes" |
| 12 | +) |
| 13 | + |
| 14 | +// HTTPMW adds tracing to http routes. |
| 15 | +func HTTPMW(tracer string) func(http.Handler) http.Handler { |
| 16 | + return func(next http.Handler) http.Handler { |
| 17 | + return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { |
| 18 | + // start span with default span name. Span name will be updated once request finishes |
| 19 | + _, span := otel.Tracer(tracer).Start(r.Context(), "http.request") |
| 20 | + defer span.End() |
| 21 | + |
| 22 | + wrw := middleware.NewWrapResponseWriter(rw, r.ProtoMajor) |
| 23 | + |
| 24 | + // pass the span through the request context and serve the request to the next middleware |
| 25 | + next.ServeHTTP(rw, r) |
| 26 | + |
| 27 | + // set the resource name as we get it only once the handler is executed |
| 28 | + resourceName := chi.RouteContext(r.Context()).RoutePattern() |
| 29 | + if resourceName == "" { |
| 30 | + resourceName = "unknown" |
| 31 | + } |
| 32 | + resourceName = r.Method + " " + resourceName |
| 33 | + span.SetName(resourceName) |
| 34 | + |
| 35 | + // set the status code |
| 36 | + status := wrw.Status() |
| 37 | + // 0 status means one has not yet been sent in which case net/http library will write StatusOK |
| 38 | + if status == 0 { |
| 39 | + status = http.StatusOK |
| 40 | + } |
| 41 | + span.SetAttributes(attribute.KeyValue{ |
| 42 | + Key: "http.status_code", |
| 43 | + Value: attribute.IntValue(status), |
| 44 | + }) |
| 45 | + |
| 46 | + // if 5XX we set the span to "error" status |
| 47 | + if status >= 500 { |
| 48 | + span.SetStatus(codes.Error, fmt.Sprintf("%d: %s", status, http.StatusText(status))) |
| 49 | + } |
| 50 | + }) |
| 51 | + } |
| 52 | +} |
0 commit comments