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 correlation_test
import (
"context"
"fmt"
"log"
"net/http"
"gitlab.com/gitlab-org/labkit/correlation"
)
func ExampleExtractFromContext_forLogging() {
ctx := context.Background()
correlationID := correlation.ExtractFromContext(ctx)
log.Printf("event occurred. cid=%v", correlationID)
}
func ExampleInjectCorrelationID() {
http.ListenAndServe(":8080",
correlation.InjectCorrelationID(
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
clientName := correlation.ExtractClientNameFromContext(r.Context())
fmt.Fprintf(w, clientName)
})))
}
func ExampleNewInstrumentedRoundTripper() {
// correlation.NewInstrumentedRoundTripper will set the appropriate headers
// on any outbound requests
httpTransport := correlation.NewInstrumentedRoundTripper(http.DefaultTransport)
httpClient := &http.Client{
Transport: httpTransport,
}
request, err := http.NewRequest("GET", "https://example.gitlab.com/api/v4/projects", nil)
if err != nil {
log.Fatalf("unable to send request: %v", err)
}
// Importantly, we need to set the context on the request
ctx := correlation.ContextWithClientName(
context.Background(),
"clientname",
)
request = request.WithContext(ctx)
_, err = httpClient.Do(request)
if err != nil {
log.Fatalf("unable to read response: %v", err)
}
}
|