-
Notifications
You must be signed in to change notification settings - Fork 460
/
descriptors.go
40 lines (33 loc) · 1.09 KB
/
descriptors.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
package docgenerator
import (
"reflect"
"strings"
"github.com/golang/protobuf/proto"
"github.com/topfreegames/pitaya/constants"
)
// ProtoDescriptors returns the descriptor for a given message name or .proto file
func ProtoDescriptors(protoName string) ([]byte, error) {
if strings.HasSuffix(protoName, ".proto") {
descriptor := proto.FileDescriptor(protoName)
if descriptor == nil {
return nil, constants.ErrProtodescriptor
}
return descriptor, nil
}
if strings.HasPrefix(protoName, "types.") {
protoName = strings.Replace(protoName, "types.", "google.protobuf.", 1)
}
protoReflectTypePointer := proto.MessageType(protoName)
if protoReflectTypePointer == nil {
return nil, constants.ErrProtodescriptor
}
protoReflectType := protoReflectTypePointer.Elem()
protoValue := reflect.New(protoReflectType)
descriptorMethod, ok := protoReflectTypePointer.MethodByName("Descriptor")
if !ok {
return nil, constants.ErrProtodescriptor
}
descriptorValue := descriptorMethod.Func.Call([]reflect.Value{protoValue})
protoDescriptor := descriptorValue[0].Bytes()
return protoDescriptor, nil
}