怎么在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. linux 3.4.103 内核移植到 S3C6410 开发板 移植失败 (问题总结,日本再战!)

    linux 3.4.103 内核移植到 S3C6410 开发板 这个星期差点儿就搭在这里面了,一開始感觉非常不值得,移植这样的浪费时间的事情.想立刻搞定,然后安安静静看书 & coding. ...

  2. document.domain跨域

    原文:[转载]document.domain跨域 document.domain 用来得到当前网页的域名. 比如在地址栏里输入: javascript:alert(document.domain); ...

  3. CodeForces 425E Sereja and Sets

    意甲冠军: 集S它包括了很多间隔[l,r]  和1<=l<=r<=n  f(S)个不相交的区间  问给出n和f(S)  有几种可能的S集合 思路: dp好题  至于为啥是dp-  我 ...

  4. Activity的LaunchMode情景思考

    此链接:http://blog.csdn.net/xiaodongrush/article/details/28597855 1. 有哪几种类型?分别有什么用? http://developer.an ...

  5. C#操作Xml:XSLT语法 在.net中使用XSLT转换xml文档示例

    XSL即可扩展的样式表文件. 可以格式化xml的显示,也可以将xml转换成需要的另一种格式. 学习XSL必须熟悉XPath.XSL和XPath一样简单强大,容易学习. 1. XSL既然可以格式化xml ...

  6. ROOT android 原理。 基于(zergRush)

    出自: http://bbs.gfan.com/android-2996211-1-1.html 须要ROOT的同学请去上面的地址下载. a.控制手机创建个暂时目录,然后把zergRush脚本写入此目 ...

  7. MAC使用小技巧(二)

    一.Safari-->广告数量不足 --原因:DNS被拦截,被恶意推送广告. ----------------------------- [ 思路 ] 修改hosts文件 $ cd /etc $ ...

  8. 在Windows系统中安装集成的PHP开发环境

    原文:在Windows系统中安装集成的PHP开发环境 刚想学php的,又不会配置复杂php的环境,可以使用集成的,目前网上提供常用的PHP集成环境主要有AppServ.phpStudy.WAMP和XA ...

  9. OR导致笛卡尔积

    近期监控数据库,发现以下语句跑得很慢,原来运行计划走了导致笛卡尔积,来看以下语句: SQL> explain plan for 2 SELECT COUNT(*) 3 FROM "GD ...

  10. 红米1S Mokee4.4.4 本人编译版耳机线控改动调音量以及上下曲方法

    改动的文件为,用Re管理器编辑: system/usr/keylayout/msm8226-tapan-snd-card_Button_Jack.kl 默认的耳机线控的上下键是切换上下曲功能,因此此文 ...