go 使用protobuffer proto3

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

1、擷取 Protobuf 編譯器 protoc,跟C++通用的;可以在git下載到二進位檔案


2、擷取 goprotobuf 提供的 Protobuf 編譯器外掛程式 protoc-gen-go

go get github.com/golang/protobuf/protoc-gen-go

將protoc-gen-go二進位執行程式所在的目錄加入到環境變數,或者直接將二進位檔案拷貝到 protoc 所在的目錄


3.擷取 goprotobuf 提供的支援庫,包含諸如編碼(marshaling)、解碼(unmarshaling)等功能

go get github.com/golang/protobuf/proto


4、測試協議 msg.proto:

syntax = "proto3";package Im;   message helloworld   {        int32     id = 1;  // ID          string    str = 2;  // str         int32     opt = 3;  //optional field   }

5、協議檔案得到go檔案

protoc --go_out=. msg.proto


msg.pb.go 的內容如下(可以看出proto2中原有的每個欄位讀取的方法去掉了,現在proto3是直接存取):

// Code generated by protoc-gen-go.// source: msg.proto// DO NOT EDIT!/*Package Im is a generated protocol buffer package.It is generated from these files:msg.protoIt has these top-level messages:Helloworld*/package Imimport proto "github.com/golang/protobuf/proto"import fmt "fmt"import math "math"// Reference imports to suppress errors if they are not otherwise used.var _ = proto.Marshalvar _ = fmt.Errorfvar _ = math.Inf// This is a compile-time assertion to ensure that this generated file// is compatible with the proto package it is being compiled against.// A compilation error at this line likely means your copy of the// proto package needs to be updated.const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto packagetype Helloworld struct {Id  int32  `protobuf:"varint,1,opt,name=id" json:"id,omitempty"`Str string `protobuf:"bytes,2,opt,name=str" json:"str,omitempty"`Opt int32  `protobuf:"varint,3,opt,name=opt" json:"opt,omitempty"`}func (m *Helloworld) Reset()                    { *m = Helloworld{} }func (m *Helloworld) String() string            { return proto.CompactTextString(m) }func (*Helloworld) ProtoMessage()               {}func (*Helloworld) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} }func init() {proto.RegisterType((*Helloworld)(nil), "Im.helloworld")}func init() { proto.RegisterFile("msg.proto", fileDescriptor0) }var fileDescriptor0 = []byte{// 92 bytes of a gzipped FileDescriptorProto0x1f, 0x8b, 0x08, 0x00, 0x00, 0x09, 0x6e, 0x88, 0x02, 0xff, 0xe2, 0xe2, 0xcc, 0x2d, 0x4e, 0xd7,0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x62, 0xf2, 0xcc, 0x55, 0x32, 0xe2, 0xe2, 0xca, 0x48, 0xcd,0xc9, 0xc9, 0x2f, 0xcf, 0x2f, 0xca, 0x49, 0x11, 0xe2, 0xe2, 0x62, 0xca, 0x4c, 0x91, 0x60, 0x54,0x60, 0xd4, 0x60, 0x15, 0xe2, 0xe6, 0x62, 0x2e, 0x2e, 0x29, 0x92, 0x60, 0x52, 0x60, 0xd4, 0xe0,0x04, 0x71, 0xf2, 0x0b, 0x4a, 0x24, 0x98, 0x41, 0x32, 0x49, 0x6c, 0x60, 0xed, 0xc6, 0x80, 0x00,0x00, 0x00, 0xff, 0xff, 0xc8, 0x9e, 0x4a, 0x79, 0x4b, 0x00, 0x00, 0x00,}



6、檔案入庫

方案A,入當前工程,使用 import  "./Im"引用:

當前工程目錄下建立一個Im的目錄(因為協議package 名叫Im)

將產生的msg.pb.go 檔案拷貝到此Im目錄中


方案B,入go的pkg庫,使用  import  "Im"引用:

到go的pkg/src目錄下建立一個Im的目錄(因為協議package 名叫Im)

將產生的msg.pb.go 檔案拷貝到此Im目錄中


7、

go測試代碼 mainpb.go:

package mainimport (    "log"    // 輔助庫    "github.com/golang/protobuf/proto"    // x.pb.go 的路徑    "./Im")func main() {    // 建立一個訊息      test := &Im.Helloworld{        // 使用輔助函數設定域的值        Str: "hello!" ,      //  Id:  321,        Opt: 1234,    }    test.Id = 3244    // 進行編碼    data, err := proto.Marshal(test)    if err != nil {        log.Fatal("marshaling error: ", err)    }    // 進行解碼    newTest := &Im.Helloworld{}    err = proto.Unmarshal(data, newTest)    if err != nil {        log.Fatal("unmarshaling error: ", err)    }    log.Printf("id:%d;opt:%d;str:%s;",newTest.Id,newTest.Opt,newTest.Str)    // 測試結果    if test.String() != newTest.String() {        log.Fatalf("data mismatch %q != %q", test.String(), newTest.String())    }}


go run mainpb.go

運行結果:
2016/09/08 16:27:52 id:321;opt:1234;str:hello!;


聯繫我們

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