Using Google Protocol Buffer in Go/golang language

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

How to use Google protocol buffer in the go language?

Now the trend is a button to do, as with Ubuntu installation software

Go get code.google.com/p/goprotobuf/{proto,protoc-gen-go}

Go install Code.google.com/p/goprotobuf/proto

Done, can be found under the $GO _path/bin protoc-gen-go This program, then can be practical protoc-gen-go to GO language proto file automatic generation.

go1.0 used: protoc-gen-go--go_out=. Hellowrold.proto

go1.1 Direct Utility The following commands

Protoc--go_out=. Hellowrold.proto

Proto file:

Package LM;
Message HelloWorld
{
Required Int32 id = 1; // ID
Required stringstr = 2; // Str
Optional int32 opt = 3; // Optional Field

}

Package LM; Therefore must be placed in the LM directory (refer to the proto specification), use the command to generate files under LM

Protoc-gen-go--go_out=. Hellowrold.proto

Automatically survived the Helloworld.go file:

// Code generated by protoc-gen-go.
// Source:helloworld.proto
// Do not edit!

Package LM

Import Proto " Code.google.com/p/goprotobuf/proto "
Import JSON " Encoding/json "
Import Math " Math "

// Reference Proto, JSON, and math imports to suppress error if they is not otherwise used.
var_ = Proto. Marshal
var_ = &json. syntaxerror{}
var_ = Math. Inf

Type Helloworld struct{
Id *int32 ' protobuf: " Varint,1,req,name=id "Json: " Id,omitempty "`
STR * string' Protobuf: " Bytes,2,req,name=str "Json: " Str,omitempty "`
Opt *int32 ' protobuf: " varint,3,opt,name=opt "Json: " Opt,omitempty "`
xxx_unrecognized [] byte' JSON: " - "`
}

Func ( This*helloworld) Reset () {* This= helloworld{}}
Func ( This*helloworld) String () string{ returnProto.compacttextstring ( This) }
Func (*helloworld) Protomessage () {}

Func ( This*helloworld) GetId () int32 {
if This! = Nil && This. Id! = Nil {
return* This. Id
}
return 0
}

Func ( This*helloworld) Getstr () string{
if This! = Nil && This. Str! = Nil {
return* This. Str
}
return ""
}

Func ( This*helloworld) GetOpt () int32 {
if This! = Nil && This. Opt! = Nil {
return* This. Opt
}
return 0
}

Func init () {

}

You can see that there are no functions such as set_xx, Serializetoostream in C + + (you can see different methods from the code below).

Writer file:

Package Main

Import Proto " Code.google.com/p/goprotobuf/proto "
Import (
" ./LM "
" FMT "
" OS "
)

Func Main () {

Msg: = &lm. helloworld{
Id:proto. Int32 ( 101),
Str:proto. String ( " Hello "),
} // MSG init

Path: = string( " ./log.txt ")
F, err: = OS. Create (PATH)
ifErr! = Nil {
Fmt. Printf ( " failed:%s\n ", err)
return
}

Defer F.close ()
Buffer, err: = Proto. Marshal (msg) // Serializetoostream
F.write (buffer)

}

Reader file:

Package Main

Import Proto " Code.google.com/p/goprotobuf/proto "
Import (
" ./LM "
" FMT "
" io "
" OS "
)

Func checkerror (err error) {
ifErr! = Nil {
Fmt. Println (Err. Error ())
Os. Exit (- 1)
}
}

Func Main () {
Path: = string( " ./log.txt ")
File, err: = OS. Open (PATH)
ifErr! = Nil {
Fmt. Printf ( " failed:%s\n ", err)
return
}

Defer file. Close ()
FI, Err: = file. Stat ()
CheckError (ERR)
Buffer: = make ([] byte, FI. Size ())
_, err = Io. Readfull (file, buffer) // Read all content
CheckError (ERR)
Msg: = &lm. helloworld{}
Err = Proto. Unmarshal (buffer, msg) // unserialize
CheckError (ERR)
Fmt. Printf ( " read:%s\n ", Msg. String ())

}

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.