Protocol-buffers with golang
1.Install protoc
use apt
sudo apt install protoc
or download release from github direct, here i use ubuntu, for other platform, visit protocol
wget https://github.com/protocolbuffers/protobuf/releases/download/v3.19.4/protoc-3.19.4-linux-x86_64.zip -o ${HOME}/.local/bin
2.install protoc-gen-go
go install google.golang.org/protobuf/cmd/protoc-gen-go@latest
go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest
3.write example code
1syntax = "proto3";
2
3option go_package = "proto/ecommerce";
4package ecommerce;
5
6message ProductID { string value = 1; }
7
8message Product {
9 string id = 1;
10 string name = 2;
11 string description = 3;
12}
13
14service ProductInfo {
15 rpc addProduct(Product) returns (ProductID);
16 rpc getProduct(ProductID) returns (Product);
17}
and put this in a proto folder
4.Gen proto for golang and grpc
1protoc --go_out=. --go_opt=paths=source_relative \
2 --go-grpc_out=. --go-grpc_opt=paths=source_relative proto/product_info.proto
Explains of this options
- go_out define where to put your code
- go_opt define go_out options paths=import mean create the full import path of option go_package in your proto file, and paths=source_relative will ignore this
- module in go_opt will sub the prefix of you go_package option
Now you can use it in you project
Just a record, i'm still learning