protobuf生成go代码

684 阅读1分钟

看了一些文档,杂七杂八的,小半天才弄好,记录下。

机器环境:CentOS 6.3

安装清单

  • protoc: 生成代码程序
  • protoc-gen-go: 编译出golang代码插件,protoc中本身没有

安装protoc

下载地址: github.com/protocolbuf… ,选择合适环境的

wget https://github.com/protocolbuffers/protobuf/releases/download/v25.1/protoc-25.1-linux-x86_64.zip

unzip unzipprotoc-25.1-linux-x86_64.zip
sudo cp bin/protoc /usr/bin/

# 最后一行是为了将proto的一些库复制到系统,例如google/protobuf/any.proto,如果不复制,编译如果用了里面的库例如Any,会提示:protobuf google.protobuf.Any not found 。
sudo cp -r include/google /usr/include/

安装protoc-gen-go

go install google.golang.org/protobuf/cmd/protoc-gen-go@latest

使用

# 将当前文件中的所有proto转go
protoc --proto_path=./ --go_out=./ *.proto

# 或者
protoc --proto_path=./ \
--go_out=./ \
--go_opt=Mcomponent.proto=./ \ # 指定包名,Q&A中的1问题,另一种解决方式
component.proto

Q&A:

1.报错 protoc-gen-go: unable to determine Go import path for "xxx"

image.png

在proto文件添加包名(go的包名,随便): option go_package = "free.com/sndbtool";

image.png

2.go文件中中文乱码

原始proto文件中文非utf8编码,转一下,再把原始文件覆盖

iconv -f GBK -t UTF-8 nearline.proto > nearline2.proto
rm nearline.proto
mv nearline2.proto nearline.proto