-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontext.go
38 lines (29 loc) · 1.1 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
package servicectx
import (
"context"
"net/http"
)
// Utility functions for passing properties between `http.Header` and `context.Context`
type contextKey string
const contextKeyOptions = contextKey("servicectx")
// FromContext returns properties from context.
// If there are no properties in the context, an empty usable instance is returned.
func FromContext(ctx context.Context) Properties {
props, ok := ctx.Value(contextKeyOptions).(Properties)
if ok {
return props
}
return New()
}
// InjectIntoContext adds properties to the context
func (p Properties) InjectIntoContext(ctx context.Context) context.Context {
return context.WithValue(ctx, contextKeyOptions, p)
}
// InjectIntoContextFromRequest parses properties from request and adds them into context
func InjectIntoContextFromRequest(ctx context.Context, req *http.Request) context.Context {
return FromRequest(req).InjectIntoContext(ctx)
}
// InjectIntoHeadersFromContext adds properties from context into http.Header
func InjectIntoHeadersFromContext(ctx context.Context, header http.Header) {
FromContext(ctx).InjectIntoHeaders(header)
}