go语言学习--protobuf的学习
|
最近在学习中遇到了protobuf,哇喔竟然不知道,马上进行了学习,protobuf也是数据解析的方式,平时使用最多的是json和xml,那么好了,对比下他们的区别,并且附上protobuf的使用。 数据交互xml、json、protobuf格式比较 1、json: 一般的web项目中,最流行的主要还是json。因为浏览器对于json数据支持非常好,有很多内建的函数支持。? 相对于其它protobuf更具有优势? 结论:? ? 使用 ? ? WIN7 + Go1.9.2+protobuf3.5.1 ?? 1.首先定义一个用于测试的proto文件test.proto,内容如下: Syntax = "proto3"; package example; message Test { string strTest = 1; double dTest = 2; repeated int64 i64RepsTest = 3; } 2.需要下载两个exe来生成对应的go文件 ①https://github.com/google/protobuf/releases下载protoc-3.5.1-win32.zip文件,解压得到protoc.exe ②使用 ③将protoc.exe、protoc-gen-go.exe和test.proto拷贝到同一个文件夹中 ④protoc.exe --go_out=. test.proto,生成对应的go代码文件test.pb.go ? 3.下面使用代码 ①使用 ②将生成的test.pb.go拷贝到项目中(这里必须注意,因为使用了package example,所以必须在项目中新建example文件夹再拷贝进去) ③在项目中使用protobuf库,以及引入Test import (
"github.com/golang/protobuf/proto"
"../example" //这里根据项目结构决定example的位置
)
? ④测试代码(在这里测试了中文字符串,double数据以及int64的数据)
marshalTest := &example.Test{
*proto.String("test_string中文test"),*proto.Float64(2.34),[]int64{123456789123,4,5}}
data,err := proto.Marshal(marshalTest)
if err != nil {
fmt.Println("proto.Marshal err : ",err)
}
unmarshalTest := &example.Test{}
err = proto.Unmarshal(data,unmarshalTest)
if err != nil {
fmt.Println("proto.Unmarshal err : ",err)
}
fmt.Println("strTest = ",unmarshalTest.GetStrTest())
fmt.Println("doubleTest = ",unmarshalTest.GetDTest())
for _,v := range unmarshalTest.GetI64RepsTest() {
fmt.Println("int64 reps = ",v)
}
输出的结果
以上。 ? 参考博文:《golang使用protobuf》 ? (编辑:北几岛) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |


