Go using Protobuffer Proto3

Source: Internet
Author: User

This is a creation in Article, where the information may have evolved or changed.

1, get protobuf compiler Protoc, with C + + generic; can be downloaded to a binary file in git


2 . Get the protobuf compiler plugin provided by Goprotobuf Protoc-gen-go

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

Add the directory where the protoc-gen-go binary executor resides to the environment variable, or copy the binaries directly to the directory where the PROTOC resides


3. get The support library provided by GOPROTOBUF, including functions such as encoding (marshaling), decoding (unmarshaling), etc.

get github.com/golang/protobuf/Proto


4. Test protocol Msg.proto:

Syntax = "Proto3";p ackage Im;   Message HelloWorld   {        int32     id = 1;  ID          string    str = 2;  Str         int32     opt = 3;  Optional field   }

5. protocol files get Go file

Protoc--go_out=. Msg.proto


The contents of Msg.pb.go are as follows (it can be seen that each field Proto2 in the original method is removed, and now Proto3 is directly accessed):

Code generated by protoc-gen-go.//source:msg.proto//does not edit!/*package Im be a generated protocol buffer package. It is generated from these files:msg.protoIt have these top-level messages:helloworld*/package imimport proto "github.com/g Olang/protobuf/proto "Import FMT" FMT "Import Math" math "//Reference imports to suppress errors if they is not otherwise u Sed.var _ = Proto. Marshalvar _ = fmt. Errorfvar _ = Math. inf//This was a compile-time assertion to ensure that this generated file//was compatible with the proto package it is Bei Ng compiled against.//A compilation error At the 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{//-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, 0 X17, 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, 0  Xd4, 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. File storage

Plan A, into the current project, using the import "./im" Reference:

Create a new IM directory under the current project directory (because the protocol package is called IM)

Copy the generated msg.pb.go file to this IM directory


Plan B, into the PKG Library of Go, using the import "Im" reference:

Create a new IM directory under the PKG/SRC directory of Go (because the protocol package is called IM)

Copy the generated msg.pb.go file to this IM directory


7.

Go Test Code Mainpb.go:

Package Mainimport ("Log"//Auxiliary Library "Github.com/golang/protobuf/proto"///X.pb.go path "./im") func main () { Create a message Test: = &im.helloworld{//Use an auxiliary function to set the value of the field Str: "hello!",//id:321, Opt:12 ,} test. Id = 3244//Encode data, err: = Proto. Marshal (test) if err! = Nil {log. Fatal ("Marshaling Error:", err)}//To decode 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)//testing results if test. String ()! = newtest.string () {log. Fatalf ("Data mismatch%q! =%q", test. String (), newtest.string ())}}


Go Run mainpb.go

Operation Result:
2016/09/08 16:27:52 id:321;opt:1234;str:hello!;


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

Tags Index: