protocol buffers

4 篇文章 0 订阅

protocol buffers 官方文档
本文介绍:解析proto文件生成 go 与 grpc-go 文件的工具安装与使用。

一、工具安装

安装3个工具:protoc、protoc-gen-go、protoc-gen-go-grpc

protoc
protoc 下载地址(选取最新版本即可)

protoc-gen-go
protoc-gen-go 下载地址

protoc-gen-go-grpc
protoc-gen-go-grpc 下载地址

注意:将这些工具放在一个文件夹下(例如 bin),且都需要加入系统环境变量中。linux 可以直接 export $PATH:{文件目录},或者在 ~/.profile 或者 ~/.bashrc 等末尾添加,然后 source 该文件,使其生效。

二、使用

2.1 生成 .pb.go 文件

示例:message.proto

syntax = "proto3";
package test;
option go_package = ".;pb";

message LoginRequest {
    string username = 1;
    string password = 2;
}

message LoginResponse {
    string access_token = 1;
}

命令

protoc --go_out=. message.proto

2.2 生成 _grpc.pb.go 文件

示例:auth_service.proto

syntax = "proto3";

package test;

option go_package = ".;pb";

message LoginRequest {
  string username = 1;
  string password = 2;
}

message LoginResponse {
  string access_token = 1;
}

service AuthService {
  // 一元 GRPC 接口
  rpc Login(LoginRequest) returns (LoginResponse){};
  // 服务端流式 GRPC 接口
  rpc loginServiceStream(LoginRequest) returns (stream LoginResponse){};
  // 客户端流式 GRPC 接口
  rpc LoginClientStaream(stream LoginRequest) returns (LoginResponse){};
  // 双向流式 GRPC 接口
  rpc LoginStream(stream LoginRequest) returns (stream LoginResponse){};
}

命令

 protoc --proto_path=. ./*.proto --go_out=:. --go-grpc_out=:.
  • –proto_path=. :指定proto文件的路径,这里指定的是当前目录。
  • ./*.proto :指定需要解析的proto文件。这里指的是当前目录下所有的 .proto 文件。
  • –go_out=:. :指定 .pb.go 文件的输出路径,这里指的是当前目录。
  • –go-grpc_out=:. :指定 _grpc.pb.go 文件的输出路径,这里指的是当前目录。

三、笔记

1、命令写在 MakeFile 中。
2、引入其他 proto 文件的声明后,在解析的时候应该将该文件一起解析。
3、下载 protoc 工具时,其中的 google 目录中包含了相关原生数据的定义,例如时间戳等。

// ...
import "google/protobuf/timestamp.proto";
message Update {
	google.protobuf.Timestamp updateAt = 1;
	// ...
}

4、如果有 n选1 的情况,可在proto文件中使用 oneof 关键字,或者使用枚举 enum

message People {
  string name = 1;
  oneof sex {
    string boy = 2;
    string girl = 3;
    string unknown = 4;
  }
  // ...
}

or

message People {
  enum Sex {
    string boy = 0;
    string girl = 1;
    string unknown = 2;
  }
  string name = 1;
  Sex sex = 2;
  // ...
}

5、proto 生成网关接口,需要加上 --grpc-gateway_out 选项,具体见链接。

import "google/api/annotations.proto";
service AuthService {
  rpc Login(LoginRequest) returns (LoginResponse) {
    option (google.api.http) = {
      post: "/v1/auth/login"
      body: "*"
    };
  };
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值