[原]在 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/
 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM