-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathinjector.go
More file actions
67 lines (60 loc) · 1.64 KB
/
injector.go
File metadata and controls
67 lines (60 loc) · 1.64 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
package kinitx
import (
"reflect"
"github.com/go-kata/kdone"
"github.com/go-kata/kerror"
"github.com/go-kata/kinit"
)
// Injector represents a functor that provides an object to use directly instead of it creation.
type Injector struct {
// t specifies the type of an object that is provided by this injector.
t reflect.Type
// object specifies the provided object.
object reflect.Value
}
// NewInjector returns a new injector.
//
// The argument x must not be nil.
func NewInjector(x interface{}) (*Injector, error) {
if x == nil {
return nil, kerror.New(kerror.EViolation, "value expected, nil given")
}
return &Injector{
t: reflect.TypeOf(x),
object: reflect.ValueOf(x),
}, nil
}
// MustNewInjector is a variant of the NewInjector that panics on error.
func MustNewInjector(x interface{}) *Injector {
i, err := NewInjector(x)
if err != nil {
panic(err)
}
return i
}
// Parameters implements the kinit.Functor interface.
func (i *Injector) Parameters() []reflect.Type {
if i == nil {
return nil
}
return []reflect.Type{runtimeType}
}
// Call implements the kinit.Functor interface.
func (i *Injector) Call(a ...reflect.Value) ([]kinit.Functor, error) {
if i == nil {
return nil, nil
}
if len(a) != 1 {
return nil, kerror.Newf(kerror.EViolation,
"%s injector expects %d argument(s), %d given", i.t, 1, len(a))
}
if a[0].Type() != runtimeType {
return nil, kerror.Newf(kerror.EViolation,
"%s injector expects argument %d to be of %s type, %s given",
i.t, 1, runtimeType, a[0].Type())
}
if err := a[0].Interface().(*kinit.Runtime).Put(i.t, i.object, kdone.Noop); err != nil {
return nil, err
}
return nil, nil
}