-
Notifications
You must be signed in to change notification settings - Fork 435
/
headers.go
96 lines (83 loc) · 2.54 KB
/
headers.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
// Unless explicitly stated otherwise all files in this repository are licensed
// under the Apache License Version 2.0.
// This product includes software developed at Datadog (https://www.datadoghq.com/).
// Copyright 2016-2020 Datadog, Inc.
package sarama
import (
"gopkg.in/DataDog/dd-trace-go.v1/ddtrace/tracer"
"github.com/Shopify/sarama"
)
// A ProducerMessageCarrier injects and extracts traces from a sarama.ProducerMessage.
type ProducerMessageCarrier struct {
msg *sarama.ProducerMessage
}
var _ interface {
tracer.TextMapReader
tracer.TextMapWriter
} = (*ProducerMessageCarrier)(nil)
// ForeachKey iterates over every header.
func (c ProducerMessageCarrier) ForeachKey(handler func(key, val string) error) error {
for _, h := range c.msg.Headers {
err := handler(string(h.Key), string(h.Value))
if err != nil {
return err
}
}
return nil
}
// Set sets a header.
func (c ProducerMessageCarrier) Set(key, val string) {
// ensure uniqueness of keys
for i := 0; i < len(c.msg.Headers); i++ {
if string(c.msg.Headers[i].Key) == key {
c.msg.Headers = append(c.msg.Headers[:i], c.msg.Headers[i+1:]...)
i--
}
}
c.msg.Headers = append(c.msg.Headers, sarama.RecordHeader{
Key: []byte(key),
Value: []byte(val),
})
}
// NewProducerMessageCarrier creates a new ProducerMessageCarrier.
func NewProducerMessageCarrier(msg *sarama.ProducerMessage) ProducerMessageCarrier {
return ProducerMessageCarrier{msg}
}
// A ConsumerMessageCarrier injects and extracts traces from a sarama.ConsumerMessage.
type ConsumerMessageCarrier struct {
msg *sarama.ConsumerMessage
}
var _ interface {
tracer.TextMapReader
tracer.TextMapWriter
} = (*ConsumerMessageCarrier)(nil)
// NewConsumerMessageCarrier creates a new ConsumerMessageCarrier.
func NewConsumerMessageCarrier(msg *sarama.ConsumerMessage) ConsumerMessageCarrier {
return ConsumerMessageCarrier{msg}
}
// ForeachKey iterates over every header.
func (c ConsumerMessageCarrier) ForeachKey(handler func(key, val string) error) error {
for _, h := range c.msg.Headers {
if h != nil {
err := handler(string(h.Key), string(h.Value))
if err != nil {
return err
}
}
}
return nil
}
// Set sets a header.
func (c ConsumerMessageCarrier) Set(key, val string) {
// ensure uniqueness of keys
for i := 0; i < len(c.msg.Headers); i++ {
if c.msg.Headers[i] != nil && string(c.msg.Headers[i].Key) == key {
c.msg.Headers = append(c.msg.Headers[:i], c.msg.Headers[i+1:]...)
i--
}
}
c.msg.Headers = append(c.msg.Headers, &sarama.RecordHeader{
Key: []byte(key),
Value: []byte(val),
})
}