File: examples_test.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 (50 lines) | stat: -rw-r--r-- 1,324 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
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)
	}
}