美文网首页
protoc go插件编写之一 (protoc 插件的原理)

protoc go插件编写之一 (protoc 插件的原理)

作者: 癞痢头 | 来源:发表于2021-03-04 16:30 被阅读0次

protoc的golang自动代码生成, 源码文件【google.golang.org/protobuf/types/pluginpb/plugin.pb.go】中有如下的一段文档,很好的解释了protoc插件的工作,和使用过程。

// protoc (aka the Protocol Compiler) can be extended via plugins.  A plugin is
// just a program that reads a CodeGeneratorRequest from stdin and writes a
// CodeGeneratorResponse to stdout.
//
// Plugins written using C++ can use google/protobuf/compiler/plugin.h instead
// of dealing with the raw protocol defined here.
//
// A plugin executable needs only to be placed somewhere in the path.  The
// plugin should be named "protoc-gen-${NAME}", and will then be used when the
// flag "--${NAME}_out" is passed to protoc.

// Code generated by protoc-gen-go. DO NOT EDIT.
// source: google/protobuf/compiler/plugin.proto

这段话翻译过来大致如下:

protoc可以通过插件扩展。插件的工作原理是从标准输入中读取 CodeGeneratorRequest, 处理后生成CodeGeneratorResponse ,并写入标准输出中。

插件必须按照 protoc-gen-{NAME} 格式命名,在使用protoc中将, --{NAME}_out 当作参数传给protoc, 就会起作用。

实际调用过程中,可以把生成的插件文件放在环境变量PATH中,也可直接通过--plugin=[ plugin-name=plugin-path, ....] 传给protoc

protoc --plugin=protoc-gen-NAME=path/to/mybinary --NAME_out=OUT_DIR

这样, protoc就知道要使用 protoc-gen-NAME, 并输出文件到 OUT_DIR 中去了

相关文章

网友评论

      本文标题:protoc go插件编写之一 (protoc 插件的原理)

      本文链接:https://www.haomeiwen.com/subject/mwykqltx.html