[原]在 go/golang语言中使用 google Protocol Buffer

怎么在go语言中实用google protocol Buffer呢?

现在的潮流趋势就是一键搞定,跟ubuntu安装软件一样

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

go install code.google.com/p/goprotobuf/proto

搞定,可以在 $GO_PATH/bin下找到 protoc-gen-go 这个程序,那么就可以实用protoc-gen-go 进行go语言的proto文件的自动生成了。

go1.0 使用: protoc-gen-go --go_out=. hellowrold.proto

go1.1 直接实用以下命令

protoc --go_out=. hellowrold.proto

proto文件:

package lm;

message helloworld

{

required int32 id = 1; // ID

required string str = 2; // str

optional int32 opt = 3; //optional field

}

package lm; 因此必须放到lm目录下(参考proto规范) ,在lm下面使用命令生成文件

protoc-gen-go --go_out=. hellowrold.proto

自动生存了helloworld.go文件:

// 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 are 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 { return proto.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() {

}

可以看到没有c++里面的set_xx、SerializeToOstream 之类的函数(可从下面的代码看到不同的方法)。

writer文件:

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)

if err != nil {

fmt.Printf("failed: %s\n", err)

return

}

defer f.Close()

buffer, err := proto.Marshal(msg) //SerializeToOstream

f.Write(buffer)

}

reader文件:

package main

import proto "code.google.com/p/goprotobuf/proto"

import (

"./lm"

"fmt"

"io"

"os"

)

func CheckError(err error) {

if err != nil {

fmt.Println(err.Error())

os.Exit(-1)

}

}

func main() {

path := string("./log.txt")

file, err := os.Open(path)

if err != 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())

}

请尊重劳动成果,转载请保留原文链接:http://www.cnblogs.com/zhangqingping/