标签:protocol buffer protobuf protocolbuffer go语言 golang
Protocol Buffer与Golang出自同门。Golang对其的支持包在https://github.com/golang/protobuf 下。弄个小例子.
1. 创建proto文件usermsg.proto
package pfmsg; option java_package = "com.example.pfmsg"; option java_outer_classname = "UserMessage"; enum UserStatus { OFFLINE = 0; ONLINE = 1; } message UserInfo { required int32 id = 1; optional string name = 2; optional UserStatus status = 3 [default = OFFLINE]; }2.用protoc生成相关文件:
protoc --go_out=. usermsg.proto
可得usermsg.pb.go文件.
3. 用Golang调用.pb.go文件测试一下:
package main //Protocol Buffer例子 //author: Xiong Chuan Liang //date: 2015-3-7 import ( "fmt" "github.com/golang/protobuf/proto" "pfmsg" ) func main() { //编码 data, err := Marshal() if err != nil { fmt.Println("Marshal() error: ", err) } fmt.Println("Marshal:\n", data) //解码 Unmarshal(data) } func Marshal() ([]byte, error) { var status pfmsg.UserStatus status = pfmsg.UserStatus_ONLINE userInfo := &pfmsg.UserInfo{ Id: proto.Int32(10), Name: proto.String("XCL"), Status: &status, } return proto.Marshal(userInfo) } func Unmarshal(data []byte) { userInfo := &pfmsg.UserInfo{} err := proto.Unmarshal(data, userInfo) if err != nil { fmt.Println("Unmarshal() error: ", err) } fmt.Println("Unmarshal()\n userInfo:", userInfo) } /* 运行结果: Marshal: [8 10 18 3 88 67 76 24 1] Unmarshal() userInfo: id:10 name:"XCL" status:ONLINE */可以看到, Protocol Buffer与Golang两者相处蛮愉快的。
Java的可用" protoc --java_out=. usermsg.proto"生成java_package指定的目录及java_outer_classname 对应的文件,与Golang做对应测试,在这就不弄了.
MAIL: xcl_168@aliyun.com
BLOG:http://blog.csdn.net/xcl168
标签:protocol buffer protobuf protocolbuffer go语言 golang
原文地址:http://blog.csdn.net/xcl168/article/details/44119725