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";
package 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
// DO NOT EDIT!
/*
Package Im is a generated protocol buffer package.
It is generated from these files:
	msg.proto
It has these top-level messages:
	Helloworld
*/
package Im
import 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.Marshal
var _ = fmt.Errorf
var _ = 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 package
type 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 FileDescriptorProto
	0x1f, 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. 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 main

import (
     "log"
     // auxiliary library
     "github.com/golang/protobuf/proto"
     // path of x.pb.go
     "./Im"
)

func main () {
     // create a message
      test: = & Im.Helloworld {
         // Set the value of the field using a helper function
         Str: "hello!",
       // Id: 321,
         Opt: 1234,
     }

     test.Id = 3244

     // encode
     data, err: = proto.Marshal (test)
     if err! = nil {
         log.Fatal ("marshaling error:", err)
     }

     // 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)

     // Test 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.

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.