-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
70 lines (62 loc) · 1.34 KB
/
main.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
package main
import (
"fmt"
"os"
pb "github.com/mhdianrush/go-buffer-protocol-products/pb"
"github.com/sirupsen/logrus"
"google.golang.org/protobuf/proto"
)
var logger = logrus.New()
func main() {
file, err := os.OpenFile("application.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
if err != nil {
logger.Println(err.Error())
}
logger.SetOutput(file)
logger.Println("Running")
// encode
products := &pb.Products{
Data: []*pb.Product{
{
Id: 1,
Name: "Iphone 13 Pro Max",
Price: 15000000,
Stock: 100,
Category: &pb.Category{
Id: 1,
Name: "Mobile Phone",
},
},
{
Id: 2,
Name: "Macbook Pro M1 2020",
Price: 16000000,
Stock: 100,
Category: &pb.Category{
Id: 2,
Name: "Laptop",
},
},
},
}
data, err := proto.Marshal(products)
if err != nil {
logger.Println(err)
}
// compact binary wire format
fmt.Println(data)
// decode
decodeProducts := &pb.Products{}
if err = proto.Unmarshal(data, decodeProducts); err != nil {
logger.Println(err)
}
fmt.Println(decodeProducts)
for _, product := range decodeProducts.GetData() {
fmt.Println(product.GetId())
fmt.Println(product.GetName())
fmt.Println(product.GetPrice())
fmt.Println(product.GetStock())
fmt.Println(product.GetCategory().GetId())
fmt.Println(product.GetCategory().GetName())
}
}