di-go/annotation/definition.go
2019-11-11 23:22:27 +09:00

62 lines
1.0 KiB
Go

package annotation
import (
"fmt"
"reflect"
cur "git.loafle.net/commons/util-go/reflect"
)
var annotationRegistry map[string]*AnnotationDefinition
func init() {
annotationRegistry = make(map[string]*AnnotationDefinition, 0)
}
func RegisterAnnotation(t reflect.Type) error {
rt, _, _ := cur.GetTypeInfo(t)
f := getTypeAnnotationField(t)
if nil == f {
return fmt.Errorf("DI: This type[%s] is not Annotation", rt.Name())
}
name, _ := parseAnnotationMeta(f.Tag)
if _, ok := annotationRegistry[name]; ok {
return fmt.Errorf("DI: name[%s] of annotation exist already", name)
}
def := &AnnotationDefinition{
t: t,
rt: rt,
}
annotationRegistry[name] = def
return nil
}
type AnnotationDefinition struct {
t reflect.Type
rt reflect.Type
}
func getTypeAnnotationField(t reflect.Type) *reflect.StructField {
rt, _, _ := cur.GetTypeInfo(t)
if reflect.Struct != rt.Kind() {
return nil
}
for i := 0; i < rt.NumField(); i++ {
f := rt.Field(i)
if f.Anonymous {
if f.Type == TypeAnnotationType {
return &f
}
}
}
return nil
}