-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgocon.go
More file actions
81 lines (63 loc) · 1.58 KB
/
gocon.go
File metadata and controls
81 lines (63 loc) · 1.58 KB
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
72
73
74
75
76
77
78
79
80
81
package gocon
import (
"context"
"reflect"
"strings"
)
func typeOf[T any]() reflect.Type {
return reflect.TypeOf((*T)(nil)).Elem()
}
func keyOf(rt reflect.Type) string {
if rt.Kind() == reflect.Pointer {
return "*" + keyOf(rt.Elem())
}
name := rt.String()
path := rt.PkgPath()
parts := strings.Split(path, "/")
pkg := parts[len(parts)-1]
if strings.HasPrefix(name, pkg+".") {
return path + strings.TrimPrefix(name, pkg)
}
return path + "." + name
}
func KeyOf[T any]() string {
return keyOf(typeOf[T]())
}
func Resolve[T any](ctx context.Context, c Container, key string) (T, error) {
def, err := c.Get(key)
if err != nil {
var zero T
return zero, err
}
return resolveAs[T](ctx, c, def)
}
func ResolveTagged[I any](ctx context.Context, c Container, tag string) ([]I, error) {
defs, err := c.GetTagged(tag)
if err != nil {
return nil, err
}
values := make([]I, 0, len(defs))
for _, def := range defs {
v, err := resolveAs[I](ctx, c, def)
if err != nil {
return nil, err
}
values = append(values, v)
}
return values, nil
}
func GetFrom[T any](ctx context.Context, c Container) (T, error) {
return Resolve[T](ctx, c, KeyOf[T]())
}
func Get[T any](ctx context.Context) (T, error) {
return GetFrom[T](ctx, FromContext(ctx))
}
func GetBy[T any](ctx context.Context, key string) (T, error) {
return Resolve[T](ctx, FromContext(ctx), key)
}
func GetTagged[I any](ctx context.Context, tag string) ([]I, error) {
return ResolveTagged[I](ctx, FromContext(ctx), tag)
}
func Set(ctx context.Context, def *Definition) error {
return FromContext(ctx).Set(def)
}