Newer
Older
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
package util
import (
"fmt"
"github.com/golang/protobuf/proto"
"io/ioutil"
)
/*
Copycat source: https://dev.to/techschoolguru/go-generate-serialize-protobuf-message-4m7a
*/
// Write writes protocol buffer message to binary file
func Write(message proto.Message, filename string) error {
data, err := proto.Marshal(message)
if err != nil {
return fmt.Errorf("cannot marshal proto message to binary: %w", err)
}
err = ioutil.WriteFile(filename, data, 0644)
if err != nil {
return fmt.Errorf("cannot write binary data to file: %w", err)
}
return nil
}
func Read(filename string, message proto.Message) error {
data, err := ioutil.ReadFile(filename)
if err != nil {
return fmt.Errorf("cannot read binary data from file: %w", err)
}
err = proto.Unmarshal(data, message)
if err != nil {
return fmt.Errorf("cannot unmarshal binary to proto message: %w", err)
}
return nil
}