golang中protocolbuff的使用

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

protocolbuff是Google推出的開源序列化協議,幾乎支援市面上所有主流語言。用作伺服器與伺服器或者用戶端與伺服器的網路傳輸協議再合適不過了。簡單寫個demo。
項目結構:

ProtocolBuff    ----Makefile    ----src           ----github.com/golang/protobuf           ----main           ----protocol

配置協議:
protocol/protocol.proto

package protocol;enum ItemType{        USERITEM  = 1;        EQUIPMENT = 2;};message ItemInfo{        optional int32 ID = 1;        optional int32 Type = 2;        optional string Name = 3;        optional int32 Amount = 4;};

執行protoc --go_out=./ protocol.proto自動產生protocol.pb.go,組建目錄為目前的目錄。protoc支援產生多種語言,具體用protoc -h查看。

main/main.go

package mainimport (    "github.com/golang/protobuf/proto"    "fmt"    "protocol")func main() {    item := protocol.ItemInfo{        ID : proto.Int32(10),        Type : proto.Int32(1),        Name : proto.String("item_0"),        Amount: proto.Int32(99),    }    data := EncodeMsg(&item)//封包    fmt.Printf("Encode Data %v \n", data)    res := DecodeMsg(data)//解包    fmt.Printf("Decode Data %v \n", res.String())}func EncodeMsg(pb proto.Message) []byte{    data, err := proto.Marshal(pb)    if err != nil{        fmt.Errorf("%v \n",err.Error())    }    return data}func DecodeMsg(data []byte)  (result protocol.ItemInfo){    proto.Unmarshal(data, &result)    return}

Makefile

GOPATH := $(shell pwd)all:        GOPATH=${GOPATH} go install main

make以後,bin目錄下會產生可執行檔main,執行得到結果:
Encode Data [8 10 16 1 26 6 105 116 101 109 95 48 32 99]
Decode Data ID:10 Type:1 Name:"item_0" Amount:99

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.