-
Notifications
You must be signed in to change notification settings - Fork 0
/
interface.go
101 lines (79 loc) · 1.82 KB
/
interface.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package factory
import (
"context"
"fmt"
"github.com/expgo/sync"
"reflect"
"strings"
)
type iInterface struct {
once sync.Once
obj any
initFunc func() any
_name string
lock sync.Mutex
cci *contextCachedItem
}
func _interfaceWithType(vt reflect.Type) *iInterface {
result := &iInterface{
once: sync.NewOnce(),
lock: sync.NewMutex(),
}
result.cci = &contextCachedItem{}
result.cci._type = vt
result.cci.getter = func(ctx context.Context) any {
return result.getWithContext(ctx)
}
return result
}
func Interface[T any]() *iInterface {
return _interfaceWithType(reflect.TypeOf((*T)(nil)).Elem()).setType()
}
func NamedInterface[T any](name string) *iInterface {
return _interfaceWithType(reflect.TypeOf((*T)(nil)).Elem()).Name(name)
}
func (s *iInterface) setType() *iInterface {
_context.setByType(s.cci._type, s.cci)
return s
}
func (s *iInterface) Name(name string) *iInterface {
s.lock.Lock()
defer s.lock.Unlock()
name = strings.TrimSpace(name)
if len(name) == 0 {
panic("name must not be empty")
}
if len(s._name) == 0 {
_context.setByName(name, s.cci)
s._name = name
} else {
panic("name already set")
}
return s
}
func (s *iInterface) SetInitFunc(initFunc func() any) *iInterface {
s.lock.Lock()
defer s.lock.Unlock()
s.initFunc = initFunc
return s
}
func (s *iInterface) getWithContext(ctx context.Context) any {
timeout := getContextTimeout(ctx)
err := s.once.DoTimeout(timeout, func() error {
if s.initFunc != nil {
s.obj = s.initFunc()
} else {
panic("initFunc must be set")
}
return nil
})
if err != nil {
panic(fmt.Errorf("init interface %s, timeout: %s err: %+v", s.cci._type.String(), timeout, err))
}
return s.obj
}
func IGetter[T any](s *iInterface) func() T {
return func() T {
return s.getWithContext(getTimeoutContext(Opts.Timeout)).(T)
}
}