-
Notifications
You must be signed in to change notification settings - Fork 3
/
meta.go
61 lines (45 loc) · 1.27 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
package meta
import (
"context"
"github.com/iancoleman/strcase"
)
// Converter for meta.
type Converter func(string) string
// NoneConverter for meta.
var NoneConverter = func(s string) string { return s }
type contextKey string
var 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[string]string {
return Strings(ctx, prefix, strcase.ToSnake)
}
// CamelStrings for meta.
func CamelStrings(ctx context.Context, prefix string) map[string]string {
return Strings(ctx, prefix, strcase.ToLowerCamel)
}
// Strings for meta.
func Strings(ctx context.Context, prefix string, converter Converter) map[string]string {
as := attributes(ctx)
ss := make(map[string]string, len(as))
for k, v := range as {
ss[prefix+converter(k)] = v.String()
}
return ss
}
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)
}