go protobuf 安装

是什么

Protobuf 是 Protocol Buffers 的简称,它是 Google 公司开发的一种数据描述语言,并于 2008 年对外开源。Protobuf 刚开源时的定位类似于 XML、JSON 等数据描述语言,通过附带工具生成代码并实现将结构化数据序列化的功能。但是我们更关注的是 Protobuf 作为接口规范的描述语言,可以作为设计安全的跨语言 PRC 接口的基础工具。

怎么做

安装方法一

安装官方的 protoc 工具

点击跳转 或自行搜索:https://github.com/google/protobuf/releases

这里有时候会隐藏起来,点 Show All num assets就会显示

 解压到 $GoPath/bin下. 我这里的路径是 D:\GoPath\bin

 安装针对 Go 语言的代码生成插件

go get github.com/golang/protobuf/protoc-gen-go

安装方法二

因为我这里是用的go mod模式,所以我直接随便在一个有mod文件的项目运行以下命令

运行以下命令后,会直接在 $GOPATH/bin目录下生成exe文件

// 安装proto
go install github.com/golang/protobuf/proto
go instatll github.com/golang/protobuf/protoc-gen-go

// 安装protoc-gen-gofast.exe
go install github.com/gogo/protobuf/protoc-gen-gogofaster@latest

使用示例

syntax = "proto3";

option go_package = "pb";

message UserReq {
  string name = 1;
}
message UserAck {
  int32 id = 1;
  string name = 2;
  int32 age = 3;
  repeated string hobby = 4;
}

service UserInfoService {
  rpc GetUserInfo(UserReq) returns(UserAck) {}
}

 生成指令

// 官方生成
protoc --go_out=. *.proto

// gogo protobuf 生成
protoc --gofast_out=plugins=grpc:. *.proto
protoc --工具类型=生成文件目录 源文件的目录

 

posted @ 2023-10-24 16:35  张永峰z  阅读(106)  评论(0编辑  收藏  举报