forked from hidevopsio/hiboot
/
injecttag.go
79 lines (70 loc) · 2.35 KB
/
injecttag.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
// Copyright 2018 John Deng (hi.devops.io@gmail.com).
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package inject
import (
"hidevops.io/hiboot/pkg/factory"
"hidevops.io/hiboot/pkg/log"
"hidevops.io/hiboot/pkg/utils/io"
"hidevops.io/hiboot/pkg/utils/mapstruct"
"hidevops.io/hiboot/pkg/utils/str"
"reflect"
)
type injectTag struct {
BaseTag
}
func init() {
AddTag(new(injectTag))
}
func getInstance(cf factory.InstantiateFactory, pkgName, name string) (retVal interface{}) {
name = pkgName + "." + str.ToLowerCamel(name)
retVal = cf.GetInstance(name)
return
}
func (t *injectTag) Decode(object reflect.Value, field reflect.StructField, tag string) (retVal interface{}) {
properties := t.ParseProperties(tag)
// first, find if object is already instantiated
if field.Type.Kind() == reflect.Ptr || field.Type.Kind() == reflect.Interface {
// if object is not exist, then instantiate new object
// parse tag and instantiate filed
ft := field.Type
if ft.Kind() == reflect.Ptr {
ft = ft.Elem()
}
pkgName := io.DirName(ft.PkgPath())
// get the user specific instance first
if tag != "" {
retVal = getInstance(t.instantiateFactory, pkgName, tag)
}
// else to find with the field name if above is not found
if retVal == nil {
retVal = getInstance(t.instantiateFactory, pkgName, field.Name)
}
// else to find with the type name if above is not found
if retVal == nil {
retVal = getInstance(t.instantiateFactory, pkgName, ft.Name())
}
// else create new instance at runtime
if retVal == nil && field.Type.Kind() != reflect.Interface {
o := reflect.New(ft)
retVal = o.Interface()
}
// inject field value
// TODO: do we need this feature?
if properties.Count() != 0 {
mapstruct.Decode(retVal, properties.Items())
}
}
log.Debugf("inject tag: %v ==> %v %v: %v", tag, field.Name, field.Type, retVal)
return retVal
}