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. 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.gz  tar zxvf protobuf -2.6 . Span style= "Color:rgb (128,0,128)" >1  .tar.gzcd protobuf -2.6 . 1   /configuremakemake installprotoc -H 

2. get Goprotobuf  protobuf  provided compiler plugin Protoc-gen-go (placed in $GOPATH/bin  should be added path  environment variable so protoc )

This plugin is  protoc used for compiling  .proto Files for  golang source files, This source file allows you to use messages that are defined in the

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;enumFOO {X = -; }; Message Test {RequiredstringLabel =1; optional Int32 type=2[default= the];repeated Int64 Reps=3; optional group Optionalgroup=4{RequiredstringRequiredfield =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 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.