-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmeta.go
79 lines (60 loc) · 1.72 KB
/
meta.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
package meta
import (
"context"
"github.com/alexfalkowski/go-service/nsq"
"github.com/alexfalkowski/go-service/transport/meta"
"github.com/google/uuid"
)
// NewConsumer for meta.
func NewConsumer(h nsq.Consumer) *Consumer {
return &Consumer{Consumer: h}
}
// Consumer for meta.
type Consumer struct {
nsq.Consumer
}
func (h *Consumer) Consume(ctx context.Context, message *nsq.Message) error {
ctx = meta.WithUserAgent(ctx, extractUserAgent(ctx, message.Headers))
requestID := extractRequestID(ctx, message.Headers)
if requestID == "" {
requestID = uuid.New().String()
}
ctx = meta.WithRequestID(ctx, requestID)
return h.Consumer.Consume(ctx, message)
}
// NewProducer for meta.
func NewProducer(userAgent string, p nsq.Producer) *Producer {
return &Producer{userAgent: userAgent, Producer: p}
}
// Producer for meta.
type Producer struct {
userAgent string
nsq.Producer
}
func (p *Producer) Produce(ctx context.Context, topic string, message *nsq.Message) error {
userAgent := meta.UserAgent(ctx)
if userAgent == "" {
userAgent = p.userAgent
}
message.Headers["user-agent"] = userAgent
ctx = meta.WithUserAgent(ctx, userAgent)
requestID := meta.RequestID(ctx)
if requestID == "" {
requestID = uuid.New().String()
}
message.Headers["request-id"] = requestID
ctx = meta.WithRequestID(ctx, requestID)
return p.Producer.Produce(ctx, topic, message)
}
func extractUserAgent(ctx context.Context, headers nsq.Headers) string {
if userAgent := headers["user-agent"]; userAgent != "" {
return userAgent
}
return meta.UserAgent(ctx)
}
func extractRequestID(ctx context.Context, headers nsq.Headers) string {
if requestID := headers["request-id"]; requestID != "" {
return requestID
}
return meta.RequestID(ctx)
}