可以在一个 proto 中 引入另一个proto
C:\Users\86173\GolandProject\Study\Seven\B.proto
syntax = "proto3";
import "Base.proto";
option go_package = "Study/Seven/B;Bbp";
message Request {
string Data = 1;
}
service Hello {
rpc Talk(ARequest) returns(AResponse);
}
C:\Users\86173\GolandProject\Study\Seven\Base.proto
syntax = "proto3";
option go_package = "Study/Seven/Base;Basepb";
message ARequest{
string Data = 1;
}
message AResponse{
string Data = 1;
}
执行shell脚本
function createProto(){
API_PATH=$1
PROTO_NAME=$2
PROTO_PATH=$3
mkdir -p $API_PATH
protoc -I=$PROTO_PATH --go_out=paths=source_relative:$API_PATH $PROTO_NAME.proto
}
createProto ./Seven/Base Base ./Seven
createProto ./Seven/B B ./Seven
最终结果,我们在B.proto中使用了Base.proto的message。
注意Bpb引入Basepb最终靠的是Base.proto中定义的option go_package,我们生成的pb位置也要和go_package相对应
使用google自带的 proto
定义proto,这里引入了google自带的empty(以empty作为例子)
C:\Users\86173\GolandProject\Study\Seven\C\C.pb.go
syntax = "proto3";
import "google/protobuf/empty.proto";
option go_package = "Study/Seven/C;Cbp";
service http {
rpc ping(google.protobuf.Empty) returns (google.protobuf.Empty);
}
生成代码
protoc -I=./Seven --go_out=plugins=grpc,paths=source_relative:./Seven/C C.proto
使用
empty.proto 生成的位置在 "google.golang.org/protobuf/types/known/emptypb"
可以自己通过查看C.pb.go文件来找到其具体所在位置,将其引入。
package main
import (
Cbp "Study/Seven/C"
"context"
"google.golang.org/grpc"
"google.golang.org/protobuf/types/known/emptypb"
"net"
)
type Service struct {
}
func (s *Service) Ping(ctx context.Context, empty *emptypb.Empty) (*emptypb.Empty, error) {
panic("implement me")
}
func main() {
server := grpc.NewServer()
Cbp.RegisterHttpServer(server, &Service{})
listen, _ := net.Listen("tcp", ":8083")
server.Serve(listen)
}