首页 > 其他 > 详细

tarsgo为protoc-gen-go添加tarsrpc插件

时间:2020-05-17 00:58:52      阅读:227      评论:0      收藏:0      [点我收藏+]

tarsgo对Protobuf的支持是直接编写protoc-gen-go的插件,类似gRPC插件。
我们下面就利用tarsgo写的tarsrpc这个插件,一步步生成protoc-gen-go

首先我们引用《Go语言高级编程》中的介绍:
Protobuf的protoc编译器是通过插件机制实现对不同语言的支持。比如protoc命令出现--xxx_out格式的参数,那么protoc将首先查询是否有内置的xxx插件,如果没有内置的xxx插件那么将继续查询当前系统中是否存在protoc-gen-xxx命名的可执行程序,最终通过查询到的插件生成代码。对于Go语言的protoc-gen-go插件来说,里面又实现了一层静态插件系统。比如protoc-gen-go内置了一个gRPC插件,用户可以通过--go_out=plugins=grpc参数来生成gRPC相关代码,否则只会针对message生成相关代码。

参考gRPC插件的代码,可以发现generator.RegisterPlugin函数可以用来注册插件。插件是一个generator.Plugin接口:

// A Plugin provides functionality to add to the output during
// Go code generation, such as to produce RPC stubs.
type Plugin interface {
    // Name identifies the plugin.
    Name() string
    // Init is called once after data structures are built but before
    // code generation begins.
    Init(g *Generator)
    // Generate produces the code generated by the plugin for this file,
    // except for the imports, by calling the generator‘s methods P, In,
    // and Out.
    Generate(file *FileDescriptor)
    // GenerateImports produces the import declarations for this file.
    // It is called after Generate.
    GenerateImports(file *FileDescriptor)
}

第一步,我们将protobuf拉下来,地址如下:

https://github.com/golang/protobuf

第二步,goland打开,简单设置一下代理
技术分享图片
第三步,复制tarsrpc这个插件,地址如下:

https://github.com/TarsCloud/TarsGo/tree/master/tars/tools/pb2tarsgo/protoc-gen-go

将下面的tarsrpc文件夹复制到protobuf下protoc-gen-go这个目录中。
技术分享图片
复制好的目录结构如下:
技术分享图片

第三步,修改main.go文件中case,使其支持tarsrpc,引用tarsrpc文件
技术分享图片
技术分享图片

第四步,生成protoc-gen-go.exe

cd protoc-gen-go
go build .

技术分享图片
最后,我们得到了protoc-gen-go.exe,可以将这个程序放入$GOPATH/bin(go下面的bin目录)中使用。

参考资料:
《Go语言高级编程》
https://chai2010.cn/advanced-go-programming-book/ch4-rpc/ch4-02-pb-intro.html
《自定义 golang protobuf plugin》
https://blog.csdn.net/wanmei002/article/details/106097849/

tarsgo为protoc-gen-go添加tarsrpc插件

原文:https://www.cnblogs.com/cnlihao/p/12903160.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!