# grpc-go go的gRPC框架 https://github.com/grpc/grpc-go # protobuf protobuf协议编译器 https://github.com/protocolbuffers/protobuf/tags ## golang 编译器插件 https://github.com/golang/protobuf 对于Golang来说,称为protoc-gen-go。 不过在这儿有个小小的坑,github.com/golang/protobuf/protoc-gen-go和google.golang.org/protobuf/cmd/protoc-gen-go是不同的。 区别在于前者是旧版本,后者是google接管后的新版本,他们之间的API是不同的,也就是说用于生成的命令,以及生成的文件都是不一样的。 因为目前的gRPC-go源码中的example用的是后者的生成方式,为了与时俱进,本文也采取最新的方式。 你需要安装两个库: ```bash go install google.golang.org/protobuf/cmd/protoc-gen-go@latest go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest ``` 在网上的一些教程中,有这样的生成方式: `protoc --go_out=plugins=grpc:. helloworld.proto` 这种生成方式,使用的就是github版本的protoc-gen-go,而目前这个项目已经由Google接管了。 并且,如果使用这种生成方式的话,并不会生成上图中的xxx_grpc.pb.go与xxx.pb.go两个文件,只会生成xxx.pb.go这种文件。 此外,你也可能遇到这种错误: ```bash protoc-gen-go-grpc: program not found or is not executable Please specify a program using absolute path or make sure the program is available in your PATH system variable --go-grpc_out: protoc-gen-go-grpc: Plugin failed with status code 1. ``` 这是因为你没有安装protoc-gen-go-grpc这个插件,这个问题在本文中应该不会出现。 你还可能会遇到这种问题: ```bash --go_out: protoc-gen-go: plugins are not supported; use 'protoc --go-grpc_out=...' to generate gRPC ``` 这是因为你安装的是更新版本的protoc-gen-go,但是你却用了旧版本的生成命令。 但是这两种方法都是可以完成目标的,只不过api不太一样。本文是基于Google版本的protoc-gen-go进行示范。 至于其他更详细的资料,你可以在这里看到:https://github.com/protocolbuffers/protobuf-go/releases/tag/v1.20.0#v1.20-generated-code ## protobuf 协议文档 protobuf 协议文档 https://protobuf.dev/getting-started/gotutorial ## 使用到的命令 `protoc --go_out=../services --go-grpc_out=../services prod.proto` # grpc-gateway ```bash go install github.com/grpc-ecosystem/grpc-gateway/v2/protoc-gen-grpc-gateway@latest go install github.com/grpc-ecosystem/grpc-gateway/v2/protoc-gen-openapiv2@latest go install google.golang.org/protobuf/cmd/protoc-gen-go@latest go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest ``` ```bash protoc -I . --grpc-gateway_out ../services prod.proto ```