-
Notifications
You must be signed in to change notification settings - Fork 0
/
type.go
50 lines (43 loc) · 1.13 KB
/
type.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
package loader
import (
"errors"
"reflect"
"github.com/golang/protobuf/proto"
)
func NewTypedSettings(message proto.Message) *TypedSettings {
if message == nil {
return nil
}
settings, _ := proto.Marshal(message)
return &TypedSettings{
Type: GetType(message),
Settings: settings,
}
}
func GetType(message proto.Message) string {
return proto.MessageName(message)
}
func GetInstance(messageType string) (interface{}, error) {
mType := proto.MessageType(messageType).Elem()
if mType == nil {
return nil, errors.New("Unknown type: " + messageType)
}
return reflect.New(mType).Interface(), nil
}
func (this *TypedSettings) Load(message proto.Message) error {
targetType := GetType(message)
if targetType != this.Type {
return errors.New("Have type " + this.Type + ", but retrieved for " + targetType)
}
return proto.Unmarshal(this.Settings, message)
}
func (this *TypedSettings) GetInstance() (interface{}, error) {
instance, err := GetInstance(this.Type)
if err != nil {
return nil, err
}
if err := proto.Unmarshal(this.Settings, instance.(proto.Message)); err != nil {
return nil, err
}
return instance, nil
}