這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。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-7import ("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.UserStatusstatus = pfmsg.UserStatus_ONLINEuserInfo := &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