Using Protobuf in Golang

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

Installing GOPROTOBUF

1. get protobuf compiler Protoc from https://github.com/google/protobuf/releases( binary version available for download 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

2. obtain the protobuf compiler plug-in protoc-gen-go provided by Goprotobuf(placed under $GOPATH/bin , $GOPATH/bin should be added to the PATH Environment variables so that Protoc can find protoc-gen-go)

This plugin is Protoc used to compile a . proto file is a Golang source file that can be used by this source file to define the messages in the . Proto file.

get github.com/golang/protobuf/protoc-gen-gocd github.com/golang/protobuf/protoc-gen-  /etc/profile Adding $gopath/bin to environment variable source profile

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

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  -  string1  2 [default = 3   4string5;}}


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 Libraries    "Github.com/golang/protobuf/proto"    //path of the Test.pb.go    "Example") Func main () {//Create a message TestTest: = &example. test{//to set the value of a field by using an auxiliary functionLabel:proto. String ("Hello"), Type:proto. Int32 ( -), Optionalgroup:&example. test_optionalgroup{Requiredfield:proto. String ("Good bye"),        },    }    //to encodeData, err: =Proto. Marshal (test)ifErr! =Nil {log. Fatal ("Marshaling Error:", Err)} //to decodeNewtest: = &example. test{} Err=Proto. Unmarshal (data, newtest)ifErr! =Nil {log. Fatal ("unmarshaling Error:", Err)} //Test Results    ifTest. Getlabel ()! =Newtest.getlabel () {log. Fatalf ("data mismatch%q! =%q", Test. Getlabel (), Newtest.getlabel ())}}

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.