Golang proto 小技巧

可以在一个 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);
}
生成代码
# 从当前目录下Seven 找到 C.proto 生成结构体和服务方法放在 /Seven/C 目录下
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) {
	//TODO implement me
	panic("implement me")
}

func main() {
	server := grpc.NewServer()
	Cbp.RegisterHttpServer(server, &Service{})
	listen, _ := net.Listen("tcp", ":8083")
	server.Serve(listen)
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值