Go語言使用Protocol Buffer的小例子

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。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





相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.