Protocol Buffer - 引入其他文件编译

Protocol Buffer - 引入其他文件编译

目录结构

demo/
├── my
│   └── a.proto
└── other
    └── b.proto

目的

在 b.proto 中引入 a.proto 定义 的 Message

a.proto内容

syntax = "proto3";
//go_package go 文件输出目录
option go_package="./my"; 

service HelloServiceDef{
  rpc sayHello(HelloRequest) returns(HelloResponse){}
}

message HelloRequest{
  string name = 1;
}

message HelloResponse{
  string message = 1;
}

b.protocol 文件内容

syntax = "proto3";
option go_package="./other";  // proto3 语法 需要带 ./

import  "my/a.proto";

message Other{
  //HelloRequest 来自 my/a.proto 的定义
  HelloRequest request = 1;
}

编译

# 进入 demo 目录
[root@blue proto]# cd demo/
[root@blue demo]# protoc -I .  --go_out=./ ./other/b.proto 
[root@blue demo]# tree
.
├── my
│   └── a.proto
└── other
    ├── b.pb.go  # 编译成功!!
    └── b.proto

语法:

  • -I / --proto_path: 指定了要去哪个目录中搜索import中导入的和要编译为.go的proto文件,可以加载多个
  • --go_out : 指定了生成的go文件的目录
  • ./other/b.proto: 需要编译的文件