-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinject.go
49 lines (41 loc) · 888 Bytes
/
inject.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
package inject
import (
"sync"
)
var (
lock = &sync.Mutex{}
funcs = make([]Func, 0, 20)
)
type (
Func func(Injector) error
)
// Injector is the interface that New must implement.
type Injector interface {
Register(key string, value any)
Load(key string) (value any, ok bool)
Delete(key string)
Range(f func(key, value any) bool)
Inject(val any)
}
// Register register the Func instance.
func Register(injectFunc Func) {
lock.Lock()
defer lock.Unlock()
funcs = append(funcs, injectFunc)
}
// New returns the Injector instance. If the Injector instance is nil, it will be initialized.
func New(injector Injector) Injector {
lock.Lock()
for _, f := range funcs {
err := f(injector)
if err != nil {
panic(err)
}
}
lock.Unlock()
injector.Range(func(_, value any) bool {
injector.Inject(value) // inject the value field
return true
})
return injector
}