怎么在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/

在 go/golang语言中使用 google Protocol Buffer的更多相关文章

  1. 前端后台以及游戏中使用Google Protocol Buffer详解

    前端后台以及游戏中使用Google Protocol Buffer详解 0.什么是protoBuf protoBuf是一种灵活高效的独立于语言平台的结构化数据表示方法,与XML相比,protoBuf更 ...

  2. Google Protocol Buffer 的使用和原理[转]

    本文转自: http://www.ibm.com/developerworks/cn/linux/l-cn-gpb/ Protocol Buffers 是一种轻便高效的结构化数据存储格式,可以用于结构 ...

  3. Google Protocol Buffer的安装与.proto文件的定义

    什么是protocol Buffer呢? Google Protocol Buffer( 简称 Protobuf) 是 Google 公司内部的混合语言数据标准. 我理解的就是:它是一种轻便高效的结构 ...

  4. Google Protocol Buffer 的使用和原理

    Google Protocol Buffer 的使用和原理 Protocol Buffers 是一种轻便高效的结构化数据存储格式,可以用于结构化数据串行化,很适合做数据存储或 RPC 数据交换格式.它 ...

  5. Google Protocol Buffer 协议

    1. Protocol Buffers 简介 Protocol Buffers (ProtocolBuffer/ protobuf )是Google公司开发的一种数据描述语言,类似于XML能够将结构化 ...

  6. 【Google Protocol Buffer】Google Protocol Buffer

    http://www.ibm.com/developerworks/cn/linux/l-cn-gpb/ Google Protocol Buffer 的使用和原理 Protocol Buffers ...

  7. Google Protocol Buffer的安装与.proto文件的定义(转)

    转自(https://www.cnblogs.com/yinheyi/p/6080244.html) 什么是protocol Buffer呢? Google Protocol Buffer( 简称 P ...

  8. 转Google Protocol Buffer 的使用和原理

    Google Protocol Buffer 的使用和原理 Protocol Buffers 是一种轻便高效的结构化数据存储格式,可以用于结构化数据串行化,很适合做数据存储或 RPC 数据交换格式.它 ...

  9. Google Protocol Buffer 的使用(一)

    一.什么是Google Protocol Buffer下面是官网给的解释:Protocol buffers are a language-neutral, platform-neutral exten ...

随机推荐

  1. A + B Again 2057 有符号的64进位的运算

    Problem Description There must be many A + B problems in our HDOJ , now a new one is coming.Give you ...

  2. rdlc报告vs2008编辑正常,在vs2012在对错误的编辑

    最近我们的系统开发的工具vs2008升级到2012,由于系统是非常的报告是由rdlc发展.今天 有需要修改的报告满足需求.直接使用vs2012正确rdlc报告编辑,结果本次变动后.报表都报错. 后来我 ...

  3. Delegate,Action,Func,Predicate的使用与区别

    C#4.0推出后,类似Linq,Lamda表达式等许多新的程序写法层次不穷.与之相关的Delegate,Action,Func,Predicate的使用和区别也常常让大家迷惑,此处就结合实际的应用,对 ...

  4. 【百度地图API】建立全国银行位置查询系统(二)——怎样为地图添加控件

    原文:[百度地图API]建立全国银行位置查询系统(二)--怎样为地图添加控件 <摘要>你将在第二章中学会以下知识: 使用手写代码的利器——notepad++: 如何为地图添加控件——鱼骨. ...

  5. HDU 1251 统计拼图 Trie解决问题的方法

    基本上找到一个标准前缀的问题是,只需要insert和search它功能. 这里的主要变化是我n该记录方法,这里n国旗代表的不是叶节点,但是话的标志这条道路后的数字. 然后找到需要找到一个词的前缀,假如 ...

  6. nolock引发

      Sql Server之旅——终点站 nolock引发的三级事件的一些思考   曾今有件事情让我记忆犹新,那年刚来携程不久,马上就被安排写一个接口,供企鹅公司调用他们员工的差旅信息,然后我就三下五除 ...

  7. ApacheBench(ab)使用简介

    网站性能压力测试是服务器网站性能调优过程中必不可缺少的一环.只有让服务器处在高压情况下,才能真正体现出软件.硬件等各种设置不当所暴露出的问题. 性能测试工具目前最常见的有以下几种:ab.http_lo ...

  8. jmgraph前端画图组件(html5版)

    原文:jmgraph前端画图组件(html5版)      jmgraph是一个基于html5的WEB前端画图组件.        前端画图对象控件化,支持鼠标和健盘事件响应,可对单个控件样式设定,支 ...

  9. Git 一些常见的命令

    git branch 查看本地所有分支 git status 查看当前状态 git commit 提交 git branch -a 查看所有的分支 git branch -r 查看远程所有分支 git ...

  10. Warning: Cannot modify header information - headers already sent by (output started at

    一般来说在header函数前不能输出html内容,类似的还有setcookie() 和 session 函数,这些函数需要在输出流中增加消息头部信息.如果在header()执行之前有echo等语句,当 ...