一见

Windows 上配置 Go 的 gRPC 编译环境

1、Windows 上查看环境变量方法

以查看 GOPATH 为例。

  • 普通命令行查看 GOPATH:
echo %GOPATH%
  • PowerShell 上查看 GOPATH:
echo $env:GOROOT

2、安装 protoc

https://github.com/google/protobuf/releases 下载 protoc。以 protoc-3.13.0-win64.zip 为例,解压后将 bin 所在的完整目录(如“C:\Program Files\protoc-3.13.0-win64\bin”)加入到系统环境变量 PATH 中,目的是能找到 bin 目录中的 protoc 。
注意 protoc 并不包含 Go 版本的 proto 文件编译器插件,需要另外安装。此外,Go 版本的 gRPC 依赖的 protoc 的版本不能低于 3.0。

3、安装 gRPC

进入 GOROOT 或 GOPATH 的 src\google.golang.org 目录(以 GOROOT 为例,比如“C:\Go\src”),执行:

git clone https://github.com/grpc/grpc-go

成功后将 grpc-go 文件夹重命名为 grpc,完整路径如下:

C:\$GOROOT\src\google.golang.org\grpc

如果是 GOPATH 下的,则为:

C:\$GOPATH\src\google.golang.org\grpc

4、安装 genproto

同样在 src\google.golang.org 目录下,执行:

git clone https://github.com/google/go-genproto

成功后将 go-genproto 重命名为 genproto,完整路径如下:

C:\$GOROOT\src\google.golang.org\genproto

如果是 GOPATH 下的,则为:

C:\$GOPATH\src\google.golang.org\genproto

5、设置 Go 代理环境

go env -w GOPROXY=https://goproxy.cn,direct

如果不设置,则会因为网络不通在执行“go get”时失败,错误信息:

A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.

6、安装 proto

go get -u github.com/golang/protobuf/proto

7、安装编译插件 protoc-gen-go

protoc-gen-go 是 Go 版本的 proto 文件编译器插件,安装方法:

go get -u github.com/golang/protobuf/protoc-gen-go

成功后,可在目录 $GOPATH/bin 下看到 protoc-gen-go.exe。
需将 $GOPATH/bin 加入到系统环境变量 PATH 中,否则执行 protoc 编译时将报如下这样的错误:

'protoc-gen-go' 不是内部或外部命令,也不是可运行的程序或批处理文件。
--go_out: protoc-gen-go: Plugin failed with status code 1.

8、下载依赖包

创建目录 C:$GOROOT\src\golang.org\x,然后进入 x 目录,执行以下两步操作:

git clone https://github.com/golang/net.git
git clone https://github.com/golang/text.git

9、测试验证

切换到目录(依赖 gRPC 安装在目录 GOROOT 还是目录 GOPATH):

C:\$GOROOT\src\google.golang.org\grpc\examples\helloworld

或(如果 gRPC 安装在目录 GOPATH)

C:\$GOPATH\src\google.golang.org\grpc\examples\helloworld

编译子目录 helloworld 下的 helloworld.proto 生成 Go 代码文件 helloworld.pb.go:

protoc -I .\helloworld helloworld.proto --go_out=plugins=grpc:"c:\go\src"

上面的“-I”用于指定 proto 文件所在目录。如果没有报错,则可在子目录 helloworld 下找到编译生成的文件 helloworld.pb.go,编译环境即已搭建好。

注意“plugins=grpc:”后的值受“.proto”文件中的 go_package 值影响,两者共同组成生成的“.pb.go”文件所在目录。如果“.proto”文件中没有指定 go_package,则只受“plugins=grpc:”后的值的影响。

posted on 2020-09-17 17:22  -见  阅读(2376)  评论(0编辑  收藏  举报

导航