一、protobuf配置git
(1)https://github.com/protocolbuffers/protobuf/releasesgithub
(2)選擇適合的版本:protoc-3.8.0-win64.zipgolang
(3)解壓後將文件 protoc.exe 所在目錄添加到環境變量 Pathspa
(4)檢查protobuf版本,CMD命令窗口執行:protoc --versionblog
二、proto文件處理ip
(1)獲取相關庫get
go get -u github.com/golang/protobuf/protoc-gen-gostring
(2)編寫test.proto文件it
//指定版本 syntax = "proto3"; //包名 package pb; //課程 message Course{ int32 id = 1; string name = 2; } //學生 message Student{ int32 id = 1; string name = 2; repeated Course courses = 3; }
(3)生成文件命令:protoc --go_out=. test.protoio
命令執行完,會在test.proto同級目錄下生成test.pb.go文件
三、使用
package main import ( "fmt" "log" "test/protobuf/pb" "github.com/golang/protobuf/proto" ) func main() { course1 := pb.Course{ Id: *proto.Int32(1), Name: *proto.String("Golang"), } course2 := pb.Course{ Id: *proto.Int32(2), Name: *proto.String("Python3"), } stu := pb.Student{ Id: *proto.Int32(1), Name: *proto.String("篤志弘毅"), Courses: []*pb.Course{&course1, &course2}, } //序列化 data, err := proto.Marshal(&stu) if err != nil { log.Fatalln("proto.Marshal err:", err) } fmt.Println(data) //反序列化 var stuNew pb.Student err = proto.Unmarshal(data, &stuNew) if err != nil { log.Fatalln("proto.Unmarshal err:", err) } fmt.Println(stuNew) } // 輸出 // [8 1 18 12 231 172 131 229 191 151 229 188 152 230 175 133 26 10 8 1 18 6 71 111 108 97 110 103 26 11 8 2 18 7 80 121 116 104 111 110 51] // {1 篤志弘毅 [id:1 name:"Golang" id:2 name:"Python3" ] {} [] 0}