-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathprotobuf.go
81 lines (61 loc) · 1.61 KB
/
protobuf.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
77
78
79
80
81
package protobuf
import (
"context"
"log"
"github.com/bufbuild/protocompile"
"google.golang.org/protobuf/encoding/protojson"
"go.k6.io/k6/js/modules"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/reflect/protoreflect"
"google.golang.org/protobuf/types/dynamicpb"
)
func init() {
modules.Register("k6/x/protobuf", new(Protobuf))
}
type Protobuf struct{}
type ProtoFile struct {
messageDesc protoreflect.MessageDescriptor
}
func (p *Protobuf) Load(protoFilePath, lookupType string) ProtoFile {
compiler := protocompile.Compiler{
Resolver: &protocompile.SourceResolver{},
}
files, err := compiler.Compile(context.Background(), protoFilePath)
if err != nil {
log.Fatal(err)
}
if files == nil {
log.Fatal("No files were passed as arguments")
}
if len(files) == 0 {
log.Fatal("Zero files were parsed")
}
return ProtoFile{files[0].Messages().ByName(protoreflect.Name(lookupType))}
}
func (p *ProtoFile) Encode(data string) []byte {
dynamicMessage := dynamicpb.NewMessage(p.messageDesc)
err := protojson.Unmarshal([]byte(data), dynamicMessage)
if err != nil {
log.Fatal(err)
}
encodedBytes, err := proto.Marshal(dynamicMessage)
if err != nil {
log.Fatal(err)
}
return encodedBytes
}
func (p *ProtoFile) Decode(decodedBytes []byte) string {
decodedMessage := dynamicpb.NewMessage(p.messageDesc)
err := proto.Unmarshal(decodedBytes, decodedMessage)
if err != nil {
log.Fatal(err)
}
marshalOptions := protojson.MarshalOptions{
UseProtoNames: true,
}
jsonString, err := marshalOptions.Marshal(decodedMessage)
if err != nil {
log.Fatal(err)
}
return string(jsonString)
}