File: baggage_handler.go

package info (click to toggle)
golang-gitlab-gitlab-org-labkit 1.17.0-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,092 kB
  • sloc: sh: 210; javascript: 49; makefile: 4
file content (32 lines) | stat: -rw-r--r-- 928 bytes parent folder | download | duplicates (4)
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
package tracingcorrelation

import (
	"net/http"

	opentracing "github.com/opentracing/opentracing-go"
	"gitlab.com/gitlab-org/labkit/correlation"
)

// BaggageHandler will set opentracing baggage items with the current correlation_id.
func BaggageHandler(h http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		ctx := r.Context()

		if span := opentracing.SpanFromContext(ctx); span != nil {
			correlationID := correlation.ExtractFromContext(ctx)
			if correlationID != "" {
				span.SetBaggageItem(correlation.FieldName, correlationID)
			} else {
				// If the span contains the correlation_id, but the context doesn't
				// inject it from the span
				correlationID = span.BaggageItem(correlation.FieldName)
				if correlationID != "" {
					ctx = correlation.ContextWithCorrelation(ctx, correlationID)
					r = r.WithContext(ctx)
				}
			}
		}

		h.ServeHTTP(w, r)
	})
}