下载protoc
protoc是protobuf文件(.proto)的编译器,使用protoc工具可以将.proto文件转换为各种编程语言对应的源码,包含数据类型定义和调用接口等。
从https://github.com/protocolbuffers/protobuf/releases下载最新安装包
- Mac protoc-version-osx-x86_64.zip
- Windows protoc-version-win64.zip
解压压缩包后将bin目录下的protoc文件移动到 $GOPATH/bin目录下,注意$GOPATH/bin需要提前添加到环境变量Path目录下。
并将include目录移动到$GOPATH目录下,用以解决如下问题:
google/protobuf/descriptor.proto: File not found.google/api/annotations.proto:20:1: Import "google/protobuf/descriptor.proto" was not found or had errors.
google/api/annotations.proto:28:8: "google.protobuf.MethodOptions" is not defined.
helloworld/helloworld.proto:10:1: Import "google/api/annotations.proto" was not found or had errors.
google/protobuf/descriptor.proto: File not found.
google/api/annotations.proto:20:1: Import "google/protobuf/descriptor.proto" was not found or had errors.
google/api/annotations.proto:28:8: "google.protobuf.MethodOptions" is not defined.
helloworld/helloworld.proto:10:1: Import "google/api/annotations.proto" was not found or had errors.
# go
export GOPATH=$HOME/go
export PATH=$PATH:$GOPATH/bin
安装 go protobuf 插件
go install google.golang.org/protobuf/cmd/protoc-gen-go@latest
测试生成文件
protoc -I=$SRC_DIR --go_out=$DST_DIR $SRC_DIR/helloworld.proto
安装gRPC
go install google.golang.org/grpc@latest
go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest
测试生成文件
protoc -I=$SRC_DIR --go_out=$DST_DIR --go-grpc_out=$DST_DIR $SRC_DIR/helloworld.proto
安装 grpc-gateway
go install github.com/grpc-ecosystem/grpc-gateway/v2/protoc-gen-grpc-gateway
go install github.com/grpc-ecosystem/grpc-gateway/v2/protoc-gen-openapiv2
测试生成文件
protoc -I=$SRC_DIR --grpc-gateway_out=$DST_DIR --grpc-gateway_opt logtostderr=true --grpc-gateway_opt paths=import --grpc-gateway_opt generate_unbound_methods=true $SRC_DIR/helloworld.proto