How to use protobuf in golang

Installation

1
2
go get google.golang.org/protobuf
go get google.golang.org/protobuf/cmd/protoc-gen-go

How to use

Golang 裡是沒有 enum 的功能,這時候用 protobuf 是個蠻好的解法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# bonus.proto
syntax = "proto3";
package bonus;
option go_package = "github.com/blackhorseya/red-packet/internal/pkg/entity/bonus";

enum Status {
UNKNOWN = 1;
ENABLED = 2;
DISABLED = 3;
}

message Packet {
string id = 1;
int64 amount = 2;
}

透過 Makefile 去產生 code

1
2
3
.PHONY: gen-pb
gen-pb:
@protoc --go_out=plugins=grpc,paths=source_relative:. ./internal/pkg/entity/**/*.proto