-
Notifications
You must be signed in to change notification settings - Fork 0
/
inject.go
284 lines (243 loc) · 7.29 KB
/
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
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
// Copyright 2021 Flamego. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
// Package inject provides utilities for mapping and injecting dependencies in
// various ways.
package inject
import (
"fmt"
"reflect"
)
// Injector represents an interface for mapping and injecting dependencies into
// structs and function arguments.
type Injector interface {
Applicator
Invoker
TypeMapper
Provider
// SetParent sets the parent of the injector. If the injector cannot find a
// dependency in its Type map it will check its parent before returning an
// error.
SetParent(Injector)
GetParent() Injector
}
type Provider interface {
Provide(interface{}) error
}
// Applicator represents an interface for mapping dependencies to a struct.
type Applicator interface {
// Apply maps dependencies in the Type map to each field in the struct that is
// tagged with "inject". Returns an error if the injection fails.
Apply(interface{}) error
}
// Invoker represents an interface for calling functions via reflection.
type Invoker interface {
// Invoke attempts to call the `interface{}` provided as a function, providing
// dependencies for function arguments based on Type. Returns a slice of
// reflect.Value representing the returned values of the function. Returns an
// error if the injection fails.
Invoke(interface{}) ([]reflect.Value, error)
}
// FastInvoker represents an interface in order to avoid the calling function
// via reflection.
type FastInvoker interface {
// Invoke attempts to call the `interface{}` provided as interface method,
// providing dependencies for function arguments based on Type. Returns a slice
// of reflect.Value representing the returned values of the function. Returns an
// error if the injection fails.
Invoke([]interface{}) ([]reflect.Value, error)
}
// IsFastInvoker returns true if the `handler` implements FastInvoker.
func IsFastInvoker(handler interface{}) bool {
_, ok := handler.(FastInvoker)
return ok
}
// TypeMapper represents an interface for mapping `interface{}` values based on
// type.
type TypeMapper interface {
// Map maps the `interface{}` values based on their immediate type from
// reflect.TypeOf.
Map(...interface{}) TypeMapper
// MapTo maps the `interface{}` value based on the pointer of an Interface
// provided. This is really only useful for mapping a value as an interface, as
// interfaces cannot at this time be referenced directly without a pointer.
MapTo(interface{}, interface{}) TypeMapper
// Set provides a possibility to directly insert a mapping based on type and
// value. This makes it possible to directly map type arguments not possible to
// instantiate with reflect like unidirectional channels.
Set(reflect.Type, reflect.Value) TypeMapper
// Value returns the reflect.Value that is mapped to the reflect.Type. It
// returns a zeroed reflect.Value if the Type has not been mapped.
Value(reflect.Type) reflect.Value
}
type injector struct {
values map[reflect.Type]reflect.Value
parent Injector
}
func (inj *injector) GetParent() Injector {
return inj.parent
}
// InterfaceOf dereferences a pointer to an Interface type. It panics if value
// is not a pointer to an interface.
func InterfaceOf(value interface{}) reflect.Type {
t := reflect.TypeOf(value)
for t.Kind() == reflect.Ptr {
t = t.Elem()
}
if t.Kind() != reflect.Interface {
panic("called inject.InterfaceOf with a value that is not a pointer to an interface. (*MyInterface)(nil)")
}
return t
}
var _i = New()
func Default() Injector {
return _i
}
// New returns a new Injector.
func New() Injector {
return &injector{
values: make(map[reflect.Type]reflect.Value),
}
}
// Invoke attempts to call the interface{} provided as a function,
// providing dependencies for function arguments based on Type.
// Returns a slice of reflect.Value representing the returned values of the function.
// Returns an error if the injection fails.
// It panics if f is not a function
func (inj *injector) Invoke(f interface{}) ([]reflect.Value, error) {
t := reflect.TypeOf(f)
switch v := f.(type) {
case FastInvoker:
return inj.fastInvoke(v, t, t.NumIn())
default:
return inj.callInvoke(f, t, t.NumIn())
}
}
func (inj *injector) fastInvoke(f FastInvoker, t reflect.Type, numIn int) ([]reflect.Value, error) {
var in []interface{}
if numIn > 0 {
in = make([]interface{}, numIn) // Panic if t is not kind of Func
var argType reflect.Type
var val reflect.Value
for i := 0; i < numIn; i++ {
argType = t.In(i)
val = inj.Value(argType)
if !val.IsValid() {
return nil, fmt.Errorf("value not found for type %v", argType)
}
in[i] = val.Interface()
}
}
return f.Invoke(in)
}
func (inj *injector) callInvoke(f interface{}, t reflect.Type, numIn int) ([]reflect.Value, error) {
var in []reflect.Value
if numIn > 0 {
in = make([]reflect.Value, numIn)
var argType reflect.Type
var val reflect.Value
for i := 0; i < numIn; i++ {
argType = t.In(i)
val = inj.Value(argType)
if !val.IsValid() {
return nil, fmt.Errorf("value not found for type %v", argType)
}
in[i] = val
}
}
return reflect.ValueOf(f).Call(in), nil
}
func (inj *injector) Apply(val interface{}) error {
v := reflect.ValueOf(val)
for v.Kind() == reflect.Ptr {
v = v.Elem()
}
if v.Kind() != reflect.Struct {
return nil // Should not panic here ?
}
t := v.Type()
for i := 0; i < v.NumField(); i++ {
f := v.Field(i)
structField := t.Field(i)
_, ok := structField.Tag.Lookup("inject")
if f.CanSet() && ok {
ft := f.Type()
v := inj.Value(ft)
if !v.IsValid() {
return fmt.Errorf("value not found for type %v", ft)
}
f.Set(v)
}
}
return nil
}
func MapTo[T any](this Injector, val any) TypeMapper {
return this.MapTo(val, (*T)(nil))
}
func Provide[T any](this Injector) T {
var a = new(T)
this.Provide(a)
return *a
}
func (inj *injector) Provide(val any) error {
if val == nil {
return fmt.Errorf("val cannot be nil")
}
v := reflect.ValueOf(val)
t0 := v.Type()
for v.Kind() == reflect.Ptr {
v = v.Elem()
}
t := v.Type()
//if v.Kind() != reflect.Struct {
// return fmt.Errorf("value should be Pointer: %s", v.String()) // Should not panic here ?
//}
v1 := inj.Value(t)
if !v1.IsValid() {
v2 := inj.Value(t0)
if !v2.IsValid() {
return fmt.Errorf("value not found for type %v", t)
}
v.Set(v2.Elem())
} else {
v.Set(v1)
}
return nil
}
func (inj *injector) Map(values ...interface{}) TypeMapper {
for _, val := range values {
inj.values[reflect.TypeOf(val)] = reflect.ValueOf(val)
}
return inj
}
func (inj *injector) MapTo(val, ifacePtr interface{}) TypeMapper {
inj.values[InterfaceOf(ifacePtr)] = reflect.ValueOf(val)
return inj
}
func (inj *injector) Set(typ reflect.Type, val reflect.Value) TypeMapper {
inj.values[typ] = val
return inj
}
func (inj *injector) Value(t reflect.Type) reflect.Value {
val := inj.values[t]
if val.IsValid() {
return val
}
// No concrete types found, try to find implementors if t is an interface.
if t.Kind() == reflect.Interface {
for k, v := range inj.values {
if k.Implements(t) {
val = v
break
}
}
}
// Still no type found, try to look it up on the parent
if !val.IsValid() && inj.parent != nil {
val = inj.parent.Value(t)
}
return val
}
func (inj *injector) SetParent(parent Injector) {
inj.parent = parent
}