-
Notifications
You must be signed in to change notification settings - Fork 3
/
meta.go
71 lines (54 loc) · 1.28 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
package meta
import (
"context"
"github.com/iancoleman/strcase"
)
type (
// Converter for meta.
Converter func(string) string
// Map for meta.
Map map[string]string
contextKey string
)
var (
// NoneConverter for meta.
NoneConverter = func(s string) string { return s }
meta = contextKey("meta")
)
// WithAttribute to meta.
func WithAttribute(ctx context.Context, key string, value Valuer) context.Context {
attr := attributes(ctx)
attr[key] = value
return context.WithValue(ctx, meta, attr)
}
// Attribute of meta.
func Attribute(ctx context.Context, key string) Valuer {
return attributes(ctx)[key]
}
// SnakeStrings for meta.
func SnakeStrings(ctx context.Context, prefix string) Map {
return Strings(ctx, prefix, strcase.ToSnake)
}
// CamelStrings for meta.
func CamelStrings(ctx context.Context, prefix string) Map {
return Strings(ctx, prefix, strcase.ToLowerCamel)
}
// Strings for meta.
func Strings(ctx context.Context, prefix string, converter Converter) Map {
as := attributes(ctx)
m := Map{}
for k, v := range as {
s := v.String()
if s != "" {
m[prefix+converter(k)] = s
}
}
return m
}
func attributes(ctx context.Context) map[string]Valuer {
m := ctx.Value(meta)
if m == nil {
return make(map[string]Valuer)
}
return m.(map[string]Valuer)
}