Golang 安装Protobuf

来源:互联网 发布:java项目架构图 编辑:程序博客网 时间:2024/05/17 22:29

gRpc 发布了1.0版,想来试试看,发现新电脑没有装protobuf,之前装的完了记过程,又重新网上搜了一下做个记录,我的系统是ubuntu15.10


获取 Protobuf 编译器 protoc

我是从github上直接下载的源码编译的,下载地址https://github.com/google/protobuf/releases/tag/v3.0.2,下载后按照文档上的说明操作:

1.检查安装需要用到的编译工具$ sudo apt-get install autoconf automake libtool curl make g++ unzip 2.生成需要的配置脚本$ ./autogen.sh3.编译安装$ ./configure$ make$ make check$ sudo make install$ sudo ldconfig # refresh shared library cache.

获取 goprotobuf 提供的 Protobuf 编译器插件 protoc-gen-go

编译好的插件要放置于 GOPATH/binGOPATH/bin 应该被加入 PATH 环境变量,以便 protoc 能够找到 protoc-gen-go

go get github.com/golang/protobuf/protoc-gen-go进入下载好的目录go build

获取 goprotobuf 提供的支持库,包含诸如编码(marshaling)、解码(unmarshaling)等功能

go get github.com/golang/protobuf/proto进入下载好的目录go buildgo install

测试一下生成pb.go文件

//随便找一个.proto文件package example;enum FOO { X = 17; };message Test {required string label = 1;optional int32 type = 2 [default=77];repeated int64 reps = 3;optional group OptionalGroup = 4 {required string RequiredField = 5;}}

编译在.proto同级目录执行,这里通过 –go_out 来使用 goprotobuf 提供的 Protobuf 编译器插件 protoc-gen-go。这时候我们会生成一个名为 *.pb.go 的源文件

protoc –go_out=. *.proto

补充一下,看过grpc中的例子同学可能会发现除了定义的request和respose以外,在helloworld.pb.go的文档中还生成了,相应client和server的api,后来查了一下是插件protoc-gen-go中做了支持,命令如下:

protoc --go_out=plugins=grpc,import_path=mypackage:. *.proto

import_path为对应需要的package的路径到包名

0 0