File: context.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 (57 lines) | stat: -rw-r--r-- 1,664 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
51
52
53
54
55
56
57
package correlation

import (
	"context"
)

type ctxKey int

const (
	keyCorrelationID ctxKey = iota
	keyClientName
)

func extractFromContextByKey(ctx context.Context, key ctxKey) string {
	value := ctx.Value(key)

	str, ok := value.(string)
	if !ok {
		return ""
	}

	return str
}

// ExtractFromContext extracts the CollectionID from the provided context.
// Returns an empty string if it's unable to extract the CorrelationID for
// any reason.
func ExtractFromContext(ctx context.Context) string {
	return extractFromContextByKey(ctx, keyCorrelationID)
}

// ExtractFromContextOrGenerate extracts the CollectionID from the provided context or generates a random id if
// context does not contain one.
func ExtractFromContextOrGenerate(ctx context.Context) string {
	id := ExtractFromContext(ctx)
	if id == "" {
		id = SafeRandomID()
	}
	return id
}

// ContextWithCorrelation will create a new context containing the provided Correlation-ID value.
// This can be extracted using ExtractFromContext.
func ContextWithCorrelation(ctx context.Context, correlationID string) context.Context {
	return context.WithValue(ctx, keyCorrelationID, correlationID)
}

// ExtractClientNameFromContext extracts client name from incoming context.
// It will return an empty string if client name does not exist in the context.
func ExtractClientNameFromContext(ctx context.Context) string {
	return extractFromContextByKey(ctx, keyClientName)
}

// ContextWithClientName will create a new context containing client_name metadata.
func ContextWithClientName(ctx context.Context, clientName string) context.Context {
	return context.WithValue(ctx, keyClientName, clientName)
}