-
Notifications
You must be signed in to change notification settings - Fork 31
/
meta.go
76 lines (70 loc) · 1.93 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
package v1alpha1
import (
"context"
"fmt"
"net/http"
"time"
)
var (
// MetaID is a unique ID for the message.
// Required.
// https://github.com/cloudevents/spec/blob/master/spec.md#id
MetaID = "dataflow-id"
// MetaSource is the source of the messages as a Unique Resource Identifier (URI).
// Required.
// https://github.com/cloudevents/spec/blob/master/spec.md#source-1
MetaSource = "dataflow-source"
// MetaTime is the time of the message. As meta-data, this might be different to the event-time (which might be within the message).
// For example, it might be the last-modified time of a file, but the file itself was created at another time.
// Optional.
// https://github.com/cloudevents/spec/blob/master/spec.md#time
MetaTime = "dataflow-time"
)
func ContextWithMeta(ctx context.Context, source, id string, time time.Time) context.Context {
return context.WithValue(
context.WithValue(
context.WithValue(
ctx,
MetaSource,
source,
),
MetaID,
id,
),
MetaTime,
time,
)
}
func MetaFromContext(ctx context.Context) (source, id string, t time.Time, err error) {
source, ok := ctx.Value(MetaSource).(string)
if !ok {
return "", "", time.Time{}, fmt.Errorf("failed to get source from context")
}
id, ok = ctx.Value(MetaID).(string)
if !ok {
return "", "", time.Time{}, fmt.Errorf("failed to get id from context")
}
t, ok = ctx.Value(MetaTime).(time.Time)
if !ok {
return "", "", time.Time{}, fmt.Errorf("failed to get time from context")
}
return source, id, t, nil
}
func MetaInject(ctx context.Context, h http.Header) error {
source, id, t, err := MetaFromContext(ctx)
if err != nil {
return err
}
h.Add(MetaSource, source)
h.Add(MetaID, id)
h.Add(MetaTime, t.Format(time.RFC3339))
return nil
}
func MetaExtract(ctx context.Context, h http.Header) context.Context {
t, _ := time.Parse(time.RFC3339, h.Get(MetaTime))
return ContextWithMeta(ctx,
h.Get(MetaSource),
h.Get(MetaID),
t,
)
}