3

golang Grpc 中出现 it has a non-exported method and is defined in a different pa...

 3 years ago
source link: https://studygolang.com/articles/32380
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

首先说一下版本

文档日期:20201021

grpc:v1.32.0

protoc: libprotoc 3.9.0

protoc-gen-go: v1.25.0

protoc-gen-go-grpc:v1.0

ps:查看protoc系列的版本命令终端执行 protoc --version

起因

版本更新,正好闲着没事简单复习一下,意外出现了以下错误

it has a non-exported method and is defined in a different package

正文

先看下定义的proto,红色部分是编译器没有找到proto文件,这并不影响我们本文的问题。

c5f386abf5fa547021d7da25bc43dbbc.png
proto文件

通过命令生成文件大概命令如下(如何生成自行百度,不是本文的重点):

protoc -I $gopath/include/googleapis -I . --go_out=. --go-grpc_out=. ./api/login/login.proto

新版生成命令和旧版不一样了,旧命令如下:

protoc -I $gopath/include/googleapis -I . --go_out=plugins=grpc:. ./api/login/login.proto

另外还有一点pb描述和rpc方法之前旧版生成是在一个文件中,目前新版本pb和方法已经分离生成的文件格式特征如下:

ba3c50c009abc906619d52d61e05028f.png
红色的文件是通过命令生成的

然后我们看下刚刚生成的login_grpc.pb.go文件,其中一部分代码片段:

871b4046a79618fceb2994088e25cebd.png

OK到这准备工作基本完毕,下面编写代码,实现LoginServer接口如下代码

6584bd998be106b3cb1c48dc0ca00d9b.png

var _login.LoginServer = &server{} 这句就是判断我们声明server这个结构体是否实现了login.LoginServer接口,很显然它没实现,兜兜转转之后解决方法如下

3bc8182ee2a3d9c984f82e3f98ddc240.png

需要把login.UnimplementedLoginServer 结构体组合(继承)到自己定义的结构体中

ok编译器也没有提示报错。

目前grpc还是在频繁变动更新需要随时留意关注更新,在浏览源代码的时候我们能看到很多代码注释中标注Deprecated:xxx 和 This API is EXPERIMENTAL. 关键字。另外之前跟grpc相关的代码有些已经重命名迁移到新库中,所以有点坑。。。干开发学无止境啊。


有疑问加站长微信联系(非本文作者)

280

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK