gitlab.com/gitlab-org/labkit@v1.21.0/correlation/examples_test.go (about)

     1  package correlation_test
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"log"
     7  	"net/http"
     8  
     9  	"gitlab.com/gitlab-org/labkit/correlation"
    10  )
    11  
    12  func ExampleExtractFromContext_forLogging() {
    13  	ctx := context.Background()
    14  	correlationID := correlation.ExtractFromContext(ctx)
    15  	log.Printf("event occurred. cid=%v", correlationID)
    16  }
    17  
    18  func ExampleInjectCorrelationID() {
    19  	http.ListenAndServe(":8080",
    20  		correlation.InjectCorrelationID(
    21  			http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    22  				clientName := correlation.ExtractClientNameFromContext(r.Context())
    23  				fmt.Fprintf(w, clientName)
    24  			})))
    25  }
    26  
    27  func ExampleNewInstrumentedRoundTripper() {
    28  	// correlation.NewInstrumentedRoundTripper will set the appropriate headers
    29  	// on any outbound requests
    30  	httpTransport := correlation.NewInstrumentedRoundTripper(http.DefaultTransport)
    31  	httpClient := &http.Client{
    32  		Transport: httpTransport,
    33  	}
    34  
    35  	request, err := http.NewRequest("GET", "https://example.gitlab.com/api/v4/projects", nil)
    36  	if err != nil {
    37  		log.Fatalf("unable to send request: %v", err)
    38  	}
    39  
    40  	// Importantly, we need to set the context on the request
    41  	ctx := correlation.ContextWithClientName(
    42  		context.Background(),
    43  		"clientname",
    44  	)
    45  	request = request.WithContext(ctx)
    46  	_, err = httpClient.Do(request)
    47  	if err != nil {
    48  		log.Fatalf("unable to read response: %v", err)
    49  	}
    50  }