在syncthing中自定义交互协议

背景

syncthing是一个著名的文件同步工具,其使用BEP(Block Exchange Procotol)协议来进行交互,在其源码中,/proto/lib/protocol/bep.proto定义了其用到的报文协议格式,其实际编译的文件却是/lib/protocol/bep.pb.go,在某项工作中,需要自定义一些协议以支持新增的功能

protoc

如果直接编辑/lib/protocol/bep.pb.go,编辑器会提示"不要编辑此文件,这是一个被生成的文件",很明显,该文件是/proto/lib/protocol/bep.proto通过某种方法生成的,该方法就是protoc

方法

在/proto/generate.go内,写有一些明显的提示

//go:generate go run scripts/protofmt.go .

// First generate extensions using standard proto compiler.
//go:generate protoc -I ../ -I . --gogofast_out=Mgoogle/protobuf/descriptor.proto=github.com/gogo/protobuf/protoc-gen-gogo/descriptor,paths=source_relative:ext ext.proto

// Then build our vanity compiler that uses the new extensions
//go:generate go build -o scripts/protoc-gen-gosyncthing scripts/protoc_plugin.go

// Inception, go generate calls the script itself that then deals with generation.
// This is only done because go:generate does not support wildcards in paths.
//go:generate go run generate.go lib/protocol lib/config lib/fs lib/db lib/discover

很明显,需要protoc的支持,安装过程可以参考这里

结论

除了go run generate.go lib/protocol需要每次修改后使用外,其他命令可以在修改/proto/lib/protocol/bep.proto后不需要调用