0
点赞
收藏
分享

微信扫一扫

golang与protobuf

golang与protobuf_golang
需要配置环境变量
编写test.proto:

package example;

enum FOO { X = 17; };

message Test {
required string label = 1;
optional int32 type = 2 [default=77];
repeated int64 reps = 3;
optional group OptionalGroup = 4 {
required string RequiredField = 5;
}
}

编写完后:​​protoc --go_out=. *.proto​​​编译
golang与protobuf_golang_02
golang的测试代码:

package main

import (
"log"
// 辅助库
"github.com/golang/protobuf/proto"
// test.pb.go 的路径

"foodemo"
"fmt"
)

func main() {
fmt.Println("hello")
// 创建一个消息 Test
test := &example.Test{
// 使用辅助函数设置域的值
Label: proto.String("hello"),
Type: proto.Int32(17),
Optionalgroup: &example.Test_OptionalGroup{
RequiredField: proto.String("good bye"),
},
}

// 进行编码
data, err := proto.Marshal(test)
if err != nil {
log.Fatal("marshaling error: ", err)
}

// 进行解码
newTest := &example.Test{}
err = proto.Unmarshal(data, newTest)
if err != nil {
log.Fatal("unmarshaling error: ", err)
}

// 测试结果
if test.GetLabel() != newTest.GetLabel() {
log.Fatalf("data mismatch %q != %q", test.GetLabel(), newTest.GetLabel())
}else{
fmt.Println("the same")
}
}

golang与protobuf_github_03

官方链接https://github.com/protocolbuffers/protobuf/blob/master/src/README.md

1.检查安装需要用到的编译工具
$ sudo apt-get install autoconf automake libtool curl make g++ unzip
2.生成需要的配置脚本
$ ./autogen.sh
3.编译安装
$ ./configure
$ make
$ make check
$ sudo make install
$ sudo ldconfig # refresh shared library cache.

编译好的插件要放置于 GOPATH/bin下,GOPATH/bin下,GOPATH/bin 应该被加入 PATH 环境变量,以便 protoc 能够找到 protoc-gen-go

go get ​​github.com/golang/protobuf/protoc-gen-go​​​ 进入下载好的目录
go build

获取 goprotobuf 提供的支持库,包含诸如编码(marshaling)、解码(unmarshaling)等功能
go get ​​​github.com/golang/protobuf/proto​​​ 进入下载好的目录
go build
go install


举报

相关推荐

0 条评论