首先安装protoc
tar zxvf protobuf-all-3.13.0.tar.gz
cd protobuf-all-3.13.0
sudo make
sudo make install
//如果git clone不出现ssl error
go env -w GO111MODULE=""
go env -w GOSUMDB=off
go env -w GOPROXY=https://goproxy.cn,direct
go get github.com/golang/protobuf/proto
go get github.com/golang/protobuf/protoc-gen-go
go install
或者
cd src
mkdir google.golang.org
cd google.golang.org
git clone https://github.com/protocolbuffers/protobuf-go.git
或者 git clone git@github.com:protocolbuffers/protobuf-go.git protobuf
cd protobuf/protoc
go install
cd protobuf/cmd/protoc-gen-go
go install
再复制一份到github.com/golang
mkdir -p github.com/golang
cp -r /root/go/src/google.golang.org/protobuf ./github.com/golang
并且在GOPATH src创建一个google.golang.org/protobuf的文件夹
将刚才gitclone的protobuf-go放在google.golang.org/protobuf,重命名文件夹为protobuf
go install:主要用来生成库和工具。一是编译包文件(无main包),将编译后的包文件放到 pkg 目录下($GOPATH/pkg)。二是编译生成可执行文件(有main包),将可执行文件放到 bin 目录($GOPATH/bin)。
安装protoc和protoc-gen-go
cd protobuf/protoc
go install
cd protobuf/cmd/protoc-gen-go
go install
cd bin,发现多了protoc-gen-go
测试
testmsg.proto
syntax = "proto3";
package test;
option go_package = ".;test";
enum Sex{
Male = 0;
Female = 1;
}
message Student{
int32 id = 1;
string name = 2;
Sex sex = 3;
}
接着生成pb.go文件
protoc --go_out=. testmsg.proto
将这个pb.go文件cp到gopath下
[gdut17@localhost test]$ pwd
/home/gdut17/go/src/test
gdut17@localhost test]$ cp /home/gdut17/work/go/protobuf/testmsg.pb.go ./
测试代码testmsg.go
package main
import (
"test"
"fmt"
"google.golang.org/protobuf/proto"
)
func main() {
s := &test.Student{
Id: 1,
Name: "Mike",
Sex: test.Sex_Female,
}
fmt.Println(s) // id:1 name:"Mike" sex:Female
data, _ := proto.Marshal(s)
fmt.Println(data) // [8 1 18 4 77 105 107 101 24 1]
ss := new(test.Student)
err := proto.Unmarshal(data, ss)
if err == nil {
fmt.Println(ss) // id:1 name:"Mike" sex:Female
}
}
结果:
[gdut17@localhost protobuf]$ go build testmsg.go
[gdut17@localhost protobuf]$ ./testmsg
id:1 name:"Mike" sex:Female
[8 1 18 4 77 105 107 101 24 1]
id:1 name:"Mike" sex:Female
参考
https://blog.youkuaiyun.com/thisinnocence/article/details/84963854
https://blog.youkuaiyun.com/qq_36532540/article/details/107861643
https://blog.youkuaiyun.com/weixin_44448273/article/details/105571483
本文介绍了在Linux CentOS系统中如何安装和使用protobuf,包括安装protoc,设置GOPATH,克隆并放置protobuf-go源码,安装protoc-gen-go,创建并编译proto文件,以及生成和使用pb.go代码。参考了多个优快云博客文章。
1745

被折叠的 条评论
为什么被折叠?



