f5/metamgr.go
aozhiwei 16f6ac3f01 1
2020-09-03 13:39:04 +08:00

113 lines
2.5 KiB
Go

package f5
import (
"os"
"bufio"
"strings"
"reflect"
"fmt"
"github.com/golang/protobuf/proto"
"github.com/golang/protobuf/jsonpb"
)
type MetaClass struct {
FileName string
Idx int
RawMeta interface{}
WrapMeta interface{}
PrimKey string
}
type MetaMgr struct {
metaClasses *[]MetaClass
rawList []interface{}
wrapList []interface{}
wrapIdHash []map[int32]interface{}
wrapNameHash []map[string]interface{}
}
func (this *MetaMgr) Init() {
}
func (this *MetaMgr) UnInit() {
}
func (this *MetaMgr) RegisterMetaClasses(metaClasses *[]MetaClass) {
this.metaClasses = metaClasses
}
func (this *MetaMgr) Load() {
this.rawList = make([]interface{}, len(*this.metaClasses))
this.wrapList = make([]interface{}, len(*this.metaClasses))
for key, val := range *this.metaClasses {
f, _ := os.Open(val.FileName)
data, _ := bufio.NewReader(f).ReadString(0)
data = "{\"values\":" + data
data += "}"
u := jsonpb.Unmarshaler{AllowUnknownFields: true}
msgType := reflect.TypeOf(val.RawMeta).Elem()
msg := reflect.New(msgType)
msgPb := msg.Interface().(proto.Message)
err := u.Unmarshal(strings.NewReader(data), msgPb)
if err != nil {
fmt.Println(err)
}
wrapMsgType := reflect.TypeOf(val.WrapMeta)
wrapMsgList := reflect.MakeSlice(reflect.SliceOf(wrapMsgType), 0, 100)
this.rawList[key] = msg
this.wrapList[key] = wrapMsgList
this.wrapMeta(msg, wrapMsgList)
}
}
func (this *MetaMgr) wrapMeta(rawMeta reflect.Value, wrapMetaList reflect.Value) {
values := rawMeta.Elem().FieldByName("Values")
for i := 0; i < values.Len(); i++ {
val := values.Index(i)
clsName := reflect.TypeOf(val.Elem().Interface()).Name()
wrapMeta := reflect.New(reflect.TypeOf(wrapMetaList.Interface()).Elem().Elem())
serverInfo := wrapMeta.Elem().FieldByName(clsName)
serverInfo.Set(val)
wrapMetaList = reflect.Append(wrapMetaList, wrapMeta)
}
fmt.Println(wrapMetaList)
}
func (this *MetaMgr) GetMetaById(idx int, id int32) interface{} {
if idx >=0 && idx < len(this.wrapIdHash) {
idHash := this.wrapIdHash[idx]
if v, ok := idHash[id]; ok {
return v
} else {
return nil
}
}
return nil
}
func (this *MetaMgr) GetMetaByName(idx int, name string) interface{} {
if idx >=0 && idx < len(this.wrapNameHash) {
nameHash := this.wrapNameHash[idx]
if v, ok := nameHash[name]; ok {
return v
} else {
return nil
}
}
return nil
}
func (this *MetaMgr) GetMetaList(idx int) interface{} {
if idx >=0 && idx < len(this.wrapList) {
return this.wrapList[idx]
}
return nil
}