-
Notifications
You must be signed in to change notification settings - Fork 224
/
context.go
39 lines (30 loc) · 919 Bytes
/
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
package appconfig
import "context"
type contextKeyType int
const (
_ contextKeyType = iota
configContextKey
nameContextKey
)
// WithConfig derives a context that carries cfg from ctx.
func WithConfig(ctx context.Context, cfg *Config) context.Context {
return context.WithValue(ctx, configContextKey, cfg)
}
// ConfigFromContext returns the Config ctx carries.
func ConfigFromContext(ctx context.Context) *Config {
if cfg, ok := ctx.Value(configContextKey).(*Config); ok {
return cfg
}
return nil
}
// WithName derives a context that carries the given app name from ctx.
func WithName(ctx context.Context, name string) context.Context {
return context.WithValue(ctx, nameContextKey, name)
}
// NameFromContext returns the app name ctx carries or an empty string.
func NameFromContext(ctx context.Context) string {
if name, ok := ctx.Value(nameContextKey).(string); ok {
return name
}
return ""
}