-
Notifications
You must be signed in to change notification settings - Fork 50
/
message_encode_handler.go
53 lines (39 loc) · 1.17 KB
/
message_encode_handler.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
package tracing
import (
"context"
"fmt"
)
type MessageWithTraceEncoder struct {
strategy TraceIdErrorStrategy
}
func NewMessageWithTraceEncoder(strategy TraceIdErrorStrategy) *MessageWithTraceEncoder {
return &MessageWithTraceEncoder{
strategy: strategy,
}
}
func (m MessageWithTraceEncoder) Encode(ctx context.Context, _ interface{}, attributes map[string]string) (context.Context, map[string]string, error) {
var trace *Trace
if span := GetSpanFromContext(ctx); span != nil {
trace = span.GetTrace()
}
if trace == nil {
return ctx, attributes, nil
}
attributes["traceId"] = TraceToString(trace)
return ctx, attributes, nil
}
func (m MessageWithTraceEncoder) Decode(ctx context.Context, _ interface{}, attributes map[string]string) (context.Context, map[string]string, error) {
var ok bool
if _, ok = attributes["traceId"]; !ok {
return ctx, attributes, nil
}
trace, err := StringToTrace(attributes["traceId"])
if err != nil {
err := fmt.Errorf("the traceId attribute is invalid: %w", err)
err = m.strategy.TraceIdInvalid(err)
return ctx, attributes, err
}
ctx = ContextWithTrace(ctx, trace)
delete(attributes, "traceId")
return ctx, attributes, nil
}