-
-
Notifications
You must be signed in to change notification settings - Fork 78
/
proto_resolver.go
76 lines (63 loc) · 2.26 KB
/
proto_resolver.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
package proto_decoder
import (
"fmt"
"github.com/bradleyjkemp/grpc-tools/internal"
"github.com/bradleyjkemp/grpc-tools/internal/proto_descriptor"
"github.com/golang/protobuf/ptypes/empty"
"github.com/jhump/protoreflect/desc"
"github.com/jhump/protoreflect/desc/builder"
"strings"
)
type descriptorResolver struct {
methodDescriptors map[string]*desc.MethodDescriptor
}
func (d *descriptorResolver) resolveEncoded(fullMethod string, message *internal.Message) (*desc.MessageDescriptor, error) {
return d.resolve(fullMethod, message.MessageOrigin)
}
func (d *descriptorResolver) resolveDecoded(fullMethod string, message *internal.Message) (*desc.MessageDescriptor, error) {
return d.resolve(fullMethod, message.MessageOrigin)
}
func (d *descriptorResolver) resolve(fullMethod string, direction internal.MessageOrigin) (*desc.MessageDescriptor, error) {
if descriptor, ok := d.methodDescriptors[fullMethod]; ok {
switch direction {
case internal.ClientMessage:
return descriptor.GetInputType(), nil
case internal.ServerMessage:
return descriptor.GetOutputType(), nil
}
}
return nil, fmt.Errorf("method not known")
}
func NewFileResolver(protoFileRoots ...string) (*descriptorResolver, error) {
descs, err := proto_descriptor.LoadProtoDirectories(protoFileRoots...)
if err != nil {
return nil, err
}
return &descriptorResolver{
descs,
}, nil
}
func NewDescriptorResolver(protoFileDescriptors ...string) (*descriptorResolver, error) {
descs, err := proto_descriptor.LoadProtoDescriptors(protoFileDescriptors...)
if err != nil {
return nil, err
}
return &descriptorResolver{
descs,
}, nil
}
var messageName = strings.NewReplacer(
"/", "_",
".", "_",
)
type emptyResolver struct{}
func (e emptyResolver) resolveEncoded(fullMethod string, message *internal.Message) (*desc.MessageDescriptor, error) {
// Create a new file so that all messages are associated with a file
fb := builder.NewFile("") // "" == generate unique filename
mb := builder.NewMessage(fmt.Sprintf("%s_%s", messageName.Replace(fullMethod), message.MessageOrigin))
fb.AddMessage(mb)
return mb.Build()
}
func (e emptyResolver) resolveDecoded(fullMethod string, message *internal.Message) (*desc.MessageDescriptor, error) {
return desc.LoadMessageDescriptorForMessage(&empty.Empty{})
}