forked from cloudevents/sdk-go
/
context.go
52 lines (43 loc) · 1.44 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
package context
import (
"context"
"net/url"
)
// Opaque key type used to store target
type targetKeyType struct{}
var targetKey = targetKeyType{}
// WithTarget returns back a new context with the given target. Target is intended to be transport dependent.
// For http transport, `target` should be a full URL and will be injected into the outbound http request.
func WithTarget(ctx context.Context, target string) context.Context {
return context.WithValue(ctx, targetKey, target)
}
// TargetFrom looks in the given context and returns `target` as a parsed url if found and valid, otherwise nil.
func TargetFrom(ctx context.Context) *url.URL {
c := ctx.Value(targetKey)
if c != nil {
if s, ok := c.(string); ok && s != "" {
if target, err := url.Parse(s); err == nil {
return target
}
}
}
return nil
}
// Opaque key type used to store topic
type topicKeyType struct{}
var topicKey = topicKeyType{}
// WithTopic returns back a new context with the given topic. Topic is intended to be transport dependent.
// For pubsub transport, `topic` should be a Pub/Sub Topic ID.
func WithTopic(ctx context.Context, topic string) context.Context {
return context.WithValue(ctx, topicKey, topic)
}
// TopicFrom looks in the given context and returns `topic` as a string if found and valid, otherwise "".
func TopicFrom(ctx context.Context) string {
c := ctx.Value(topicKey)
if c != nil {
if s, ok := c.(string); ok {
return s
}
}
return ""
}