protoc 工具安装
安装地址
https://github.com/protocolbuffers/protobuf/releases/tag/v3.15.2
安装方式
windows 下载 https://github.com/protocolbuffers/protobuf/releases/download/v3.15.2/protoc-3.15.2-win64.zip
解压后把protoc.exe复制到gopath的bin目录下,或者新建目录加入环境变量
查看版本
D:wwwgogreet>protoc --version
libprotoc 3.15.1
安装 protoc-gen-go
go get github.com/golang/protobuf/protoc-gen-go
使用protoc转换
protoc hello.proto --go_out=.
生成hello.pb.go 在当前目录
pb protocbuff
protoc语法
- 编辑hello.proto
syntax = "proto3"; // 版本
option go_package = ".;hello";
message HelloRequest{
int32 id = 1;
string name = 2;
int32 age = 3;
}
-
执行命令
protoc hello.proto --go_out=.
-
go调用试试
package main import ( "fmt" "github.com/golang/protobuf/proto" "zero/testHello" ) func main() { name := make([]string,0) name = append(name, "hello") he := testHello.HelloRequest{Id: 1,Name:name,Age: 10} fmt.Println(he.GetName()) fmt.Println(he.GetAge()) fmt.Println(he.Id) fmt.Println(&he) b,_ := proto.Marshal(&he) fmt.Println(b) he2 := testHello.HelloRequest{} proto.Unmarshal(b,&he2) fmt.Println(he2.GetName()) }
-
运行结果
GOROOT=E:Go #gosetup GOPATH=C:UsersAdministratorgo #gosetup E:Goingo.exe build -o C:UsersAdministratorAppDataLocalTemp\___go_build_zero.exe zero #gosetup C:UsersAdministratorAppDataLocalTemp\___go_build_zero.exe #gosetup [hello] 10 1 id:1 name:"hello" age:10 [8 1 18 5 104 101 108 108 111 24 10] [hello] Process finished with exit code 0
-
生成带grpc服务的
protoc user.proto --go_out=plugins=grpc:.