怎么在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. C语言学习_查找三分之二

    查找三分之二: #include <stdio.h> #define M 10 int main(void) { int front, near, mid1, mid2; int n; i ...

  2. UVA - 10014 - Simple calculations (经典的数学推导题!!)

    UVA - 10014 Simple calculations Time Limit: 3000MS Memory Limit: Unknown 64bit IO Format: %lld & ...

  3. [Java] 一、对象的创建 & 销毁

    *1.考虑静态工厂方法(static factory method)代替构造器?!优势?不足? 服务提供者架构: 1.服务接口(Service Interface) -- 提供者实现的: 2.提供者注 ...

  4. poj 2828 Buy Tickets(树状数组 | 线段树)

    题目链接:poj 2828 Buy Tickets 题目大意:给定N,表示有个人,给定每一个人站入的位置,以及这个人的权值,如今按队列的顺序输出每一个人的权值. 解题思路:第K大元素,非常巧妙,将人入 ...

  5. easyui datagrid 单元格编辑 自动聚焦 、全选

    $.extend($.fn.datagrid.methods, { editCell: function (jq, param) { return jq.each(function () { var ...

  6. [Unity3D]Unity3D连衣裙实现游戏开发系统

    大家好,我是秦培.欢迎关注我的博客,我的博客地址">blog.csdn.net/qinyuanpei. 不知从什么时候開始,国产RPG单机游戏開始出现换装,仙剑系列中第一部实现了换装的 ...

  7. unity多边形uv地图

    我曾经写过一篇文章,不规则图形uv地图.(http://blog.csdn.net/itolfn/article/details/17240131)我用三角算法.但是,这种方法已经不完全,有一个指明: ...

  8. JS判断字符串是否全为中文

    //第一种代码(全为中文则返回"true",不全为中文则返回"false"): <script language="javascript&quo ...

  9. 转载:善待Redis中的数据

    Redis是我们数据的保管者,我们可以随时存随时取,大的小的,重要的不重要的,它都毫无怨言的帮我们保存着,甚至有些时候,我们变得很懒,存东西进去的时候顺便还贴张纸:"过了一个星期就帮我扔了吧 ...

  10. CSS3 Media Queries 详细介绍与使用方法

    Media Queries 就是要在支援CSS3 的浏览器中才能正常工作,IE8 以下不支持. 而Media Queries 的套用方法千变万化,要套用在什么样的装置中,都可以自己来定义. 到底什么是 ...