/
context.go
70 lines (58 loc) · 1.86 KB
/
context.go
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
58
59
60
61
62
63
64
65
66
67
68
69
70
package core
import (
"context"
)
type contextKey int
// Known contextKey key values
const (
requestIDKey contextKey = iota + 1
correlationIDKey
causationIDKey
)
// GetRequestID returns the RequestID from the context or a blank if not set
func GetRequestID(ctx context.Context) string {
requestID := ctx.Value(requestIDKey)
if requestID == nil {
return ""
}
return requestID.(string)
}
// GetCorrelationID returns the CorrelationID from the context or a blank if not set
//
// In a long line of events, commands and messages this ID will match the original RequestID
func GetCorrelationID(ctx context.Context) string {
correlationID := ctx.Value(correlationIDKey)
if correlationID == nil {
return GetRequestID(ctx)
}
return correlationID.(string)
}
// GetCausationID returns the CausationID from the context or a blank if not set
//
// In a long line of events, commands and messages this ID will match the previous RequestID
func GetCausationID(ctx context.Context) string {
causationID := ctx.Value(causationIDKey)
if causationID == nil {
return GetRequestID(ctx)
}
return causationID.(string)
}
// SetRequestContext sets the Request, Correlation, and Causation IDs on the context
//
// Correlation and Causation IDs will use the RequestID if blank ID values are provided
func SetRequestContext(ctx context.Context, requestID, correlationID, causationID string) context.Context {
ctx = context.WithValue(ctx, requestIDKey, requestID)
// CorrelationIDs point back to the first request
if correlationID == "" {
ctx = context.WithValue(ctx, correlationIDKey, requestID)
} else {
ctx = context.WithValue(ctx, correlationIDKey, correlationID)
}
// CausationIDs point back to the previous request
if causationID == "" {
ctx = context.WithValue(ctx, causationIDKey, requestID)
} else {
ctx = context.WithValue(ctx, causationIDKey, causationID)
}
return ctx
}