Using Protobuf in Golang

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Installing GOPROTOBUF

from Https://github.com/google/protobuf/releases  get Protobuf  compiler Protoc (downloadable to Windows 

wget Https://github.com/google/protobuf/releases/download/v2.6.1/protobuf-2.6.1.tar.gztar ZXVF PROTOBUF-2.6.1.TAR.GZCD Protobuf-2.6.1./configuremakemake installprotoc-h

 

get Goprotobuf  Protobuf provided  < Span style= "padding:0px; margin:0px; Color:rgb (0,0,255); Width:auto; Height:auto "> compiler plug-in Protoc-gen-go (placed in $GOPATH/bin )

 protoc use, for compiling  .proto file  Golang source file, This source file can be used to define messages in the  .proto file.

Go get github.com/golang/protobuf/protoc-gen-gocd Github.com/golang/protobuf/protoc-gen-gogo buildgo installvi/etc/ Profile add $gopath/bin to the environment variable source profile

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

Go get github.com/golang/protobuf/protocd github.com/golang/protobuf/protogo buildgo Install

Using Goprotobuf
Here is an example to illustrate usage. First create a. proto file Test.proto:

Package Example;enum FOO {X = 17;}; Message Test {Required String label = 1;optional Int32 type = 2 [default=77];repeated Int64 reps = 3;optional Group Option Algroup = 4 {Required String requiredfield = 5;}}


Compile this. proto file:

Protoc--go_out=. *.proto

The protobuf compiler plugin protoc-gen-go provided by GOPROTOBUF is used here through –go_out. At this point we will generate a source file named Test.pb.go.

Before using it, let's look at some of the available interfaces for each PROTOBUF message in Golang:

  1. Each of the PROTOBUF messages corresponds to a golang struct

  2. The domain name word in the message is camel_case in the corresponding Golang structure for CamelCase

  3. There is no setter method in the Golang struct body of the message, it is only necessary to assign a value directly to the struct, and some auxiliary functions may be used when assigning values, for example:

    Msg. Foo = Proto. String ("Hello")
  4. The Getter method exists in the Golang struct body of the message that returns the value of the field and returns a default value if the field is not set value

  5. Non-repeated domains are implemented as a pointer with nil when the pointer indicates that the domain is not set

  6. The repeated domain in the message is implemented as slice

  7. When accessing enumeration values, use the format enumerated type name _ enum name (more content can read the generated source directly)

  8. Use Proto. The Marshal function is encoded using the proto. Unmarshal function for decoding


Now let's write a small program:

package mainimport  (     "Log"     //  Auxiliary library       "Github.com/golang/protobuf/proto"     // test.pb.go  path       "Example") Func main ()  {    //  Create a message  Test     test := &example. test{        //  setting the value of a field using an auxiliary function          label: proto. String ("Hello"),         type:  proto. Int32 (+),         optionalgroup: &example. Test_optionalgroup{            requiredfield:  proto. String ("Good bye"),        },    }     //  encode the     data, err := proto. Marshal (tesT)     if err != nil {         Log. Fatal ("marshaling error: ",  err)     }    //  decode     newtest := &example. Test{}    err = proto. Unmarshal (data, newtest)     if err != nil {         log. Fatal ("unmarshaling error: ",  err)     }    //  test results     if test. Getlabel ()  != newtest.getlabel ()  {        log. Fatalf ("Data mismatch %q != %q",  test. Getlabel (),  newtest.getlabel ())     }}




Reprint: http://my.oschina.net/ifraincoat/blog/510971

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.

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.