forked from Clement-Jean/proto-go-course
-
Notifications
You must be signed in to change notification settings - Fork 0
/
file.go
40 lines (32 loc) · 730 Bytes
/
file.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 main
import (
"fmt"
"io/ioutil"
"log"
"google.golang.org/protobuf/proto"
)
func writeToFile(fname string, pb proto.Message) error {
out, err := proto.Marshal(pb)
if err != nil {
log.Fatalln("Can't serialise to bytes", err)
return err
}
if err = ioutil.WriteFile(fname, out, 0644); err != nil {
log.Fatalln("Can't write to file", err)
return err
}
fmt.Println("Data has been written!")
return nil
}
func readFromFile(fname string, pb proto.Message) error {
in, err := ioutil.ReadFile(fname)
if err != nil {
log.Fatalln("Can't read from file", err)
return err
}
if err = proto.Unmarshal(in, pb); err != nil {
log.Fatalln("Can't deserialise from file", err)
return err
}
return nil
}