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)
	}
}
