一、安裝protoc
因爲最近疫情原因,在家裏的系統開發,使用的是windows 公司使用的ubutnu
所以從新安裝了一遍開發環境
這裏記下 protobuf安裝過成。
過程中遇到了一些報錯,都是安裝protoc 使用 protobuf報的錯誤。
下面粘貼出來比如找不到下面這些錯誤信息。
go get 找不到 google.golang.org/protobuf
是…\github.com\golang\protobuf\proto\buffer.go:文件缺少google.golang.org/protobuf/encoding/prototext包
其他報錯也類似
解決辦法:
首先在官方網站下載插件包 protoc-3.12.1-win64.zip
1. 安裝編譯器protoc
下載地址:https://github.com/google/protobuf/releases
window:
下載: protoc-3.3.0-win32.zip
解壓,把bin目錄下的protoc.exe複製到GOPATH/bin下,GOPATH/bin加入環境變量。
當然也可放在其他目錄,需加入環境變量,能讓系統找到protoc.exe
linux:
下載:protoc-3.3.0-linux-x86_64.zip 或 protoc-3.3.0-linux-x86_32.zip
解壓,把bin目錄下的protoc複製到GOPATH/bin下,GOPATH/bin加入環境變量。
如果喜歡編譯安裝的,也可下載源碼自行安裝,最後將可執行文件加入環境變量。
檢驗是否安裝成功:protoc --version 或 protoc --help(使用說明)
2. 安裝編譯器插件protoc-gen-go (protoc-gen-go用於生成Go語言代碼)
進入GOPATH目錄,並運行
> go get -u github.com/golang/protobuf/protoc-gen-go
> cd github.com/golang/protobuf/protoc-gen-go
> go build
> go install
如果第二步驟報錯那就看提示的什麼錯誤,並解決它。有的人可能是上邊的文件目錄啊什麼的會放錯。
$GOPATH/bin中會生成protoc-gen-go.exe
這時候就是這樣的:
這時候重新編譯項目,發現可以正常運行了就。
二、使用protobuf
新建文件
syntax="proto3"; //版本號
package pro; //包名
enum ClassName{ //枚舉
class1=0; //標號 必須從 0開始
class2=1;
class3=2;
}
message Student{ //消息,對應於Go的結構體
string name=1; //1:標號,唯一 即可(相當於數據庫中的Id,不一定要從1 ,2的順序依次排列。)
int32 age=2; //必須指定整型的範圍,如int32,int64
string address=3;
ClassName cn=4;
}
message Students{
repeated Student person=1; // repeated 修飾,相當於Go中切片
string school=2;
}
然後在文件的目錄下執行命令:
protoc --go_out=. test.proto
這個時候就會看到多出來了一個文件 叫做 test.pb.go
這個時候就開始寫測試例子了,新建main.go
package main
import (
"GoKnowledge/pro"
"fmt"
"github.com/golang/protobuf/proto"
)
func main(){
s1:=&pro.Student{} //第一個學生信息
s1.Name="jz01"
s1.Age=23
s1.Address="cq"
s1.Cn=pro.ClassName_class2 //枚舉類型賦值
ss:=&pro.Students{}
ss.Person=append(ss.Person,s1) //將第一個學生信息添加到Students對應的切片中
s2:=&pro.Student{} //第二個學生信息
s2.Name="jz02"
s2.Age=25
s2.Address="cd"
s2.Cn=pro.ClassName_class3
ss.Person=append(ss.Person,s2)//將第二個學生信息添加到Students對應的切片中
ss.School="cqu"
fmt.Println("Students信息爲:",ss)
// Marshal takes a protocol buffer message
// and encodes it into the wire format, returning the data.
buffer, _ := proto.Marshal(ss)
fmt.Println("序列化之後的信息爲:",buffer)
// Use UnmarshalMerge to preserve and append to existing data.
data:=&pro.Students{}
proto.Unmarshal(buffer,data)
fmt.Println("反序列化之後的信息爲:",data)
}
運行起來打印:
API server listening at: 127.0.0.1:51937
Students信息爲: person:{name:"jz01" age:23 address:"cq" cn:class2} person:{name:"jz02" age:25 address:"cd" cn:class3} school:"cqu"
序列化之後的信息爲: [10 14 10 4 106 122 48 49 16 23 26 2 99 113 32 1 10 14 10 4 106 122 48 50 16 25 26 2 99 100 32 2 18 3 99 113 117]
反序列化之後的信息爲: person:{name:"jz01" age:23 address:"cq" cn:class2} person:{name:"jz02" age:25 address:"cd" cn:class3} school:"cqu"
Debugger finished with exit code 0
OK,到此一個從安裝到使用的例子,成功了。歡迎大家試試吧!