go使用protobuf
目錄
在go中使用protobuf,有兩個可選用的包goprotobuf(go官方出品)和gogoprotobuf。
gogoprotobuf完全兼容google protobuf,它生成的代碼質量和編解碼性能均比goprotobuf高一些
mac安裝protoc
brew install protobuf
安裝protobuf
go get github.com/golang/protobuf/proto
使用goprotobuf
安裝
go get github.com/golang/protobuf/protoc-gen-go
使用
protoc --go_out=. *.proto
使用gogoprotobuf
安裝gogoprotobuf庫
go get github.com/gogo/protobuf/proto
go get github.com/gogo/protobuf/gogoproto //這個不裝也沒關系
有兩個插件可用
protoc-gen-gogo:和protoc-gen-go生成的文件差不多,性能稍微好一點
protoc-gen-gofast:生成的文件更復雜,性能快5-7倍
安裝使用 protoc-gen-gogo
- go get github.com/gogo/protobuf/protoc-gen-gogo
- 進入到庫的根目錄【比如:cd $GOPATH/pkg/mod/github.com/gogo/protobuf@v1.3.2/protoc-gen-gogo】
- 編譯生成protoc-gen-gogo 【命令:go build】,並把生成的protoc-gen-gogo文件移到 $GOPATH/bin 目錄下方便后續使用
- 使用:protoc --gogo_out=. *.proto
注意:此處如果不走第2,3步,使用時可能會報錯:protoc-gen-gogo: program not found or is not executable
安裝使用 protoc-gen-gofast
- go get github.com/gogo/protobuf/protoc-gen-gofast
- 進入到庫的根目錄【比如:cd $GOPATH/pkg/mod/github.com/gogo/protobuf@v1.3.2/protoc-gen-gofast】
- 編譯生成protoc-gen-gofast 【命令:go build】,並把生成的protoc-gen-gofast 文件移到 $GOPATH/bin 目錄下方便后續使用
- 使用:protoc --gofast_out=. *.proto
注意:此處如果不走第2,3步,使用時可能會報錯:protoc-gen-gofast: program not found or is not executable
