怎么在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. Flex自定义组件开发之日周月日期选择日历控件

    原文:Flex自定义组件开发之日周月日期选择日历控件         使用过DateField的我们都知道,DateField 控件是用于显示日期的文本字段,字段右侧带有日历图标.当用户在控件边框内的 ...

  2. C++学习笔记32 断言函数

    首先,让我们来看看百度百科上"断言函数"定义说明: 1定义fr=aladdin#" class="nslog:1019" title="编辑 ...

  3. typecheck()简析

    #define typecheck(type,x) \ ({ type __dummy; \ typeof(x) __dummy2; \ (void)(&__dummy == &__d ...

  4. ArcGIS Runtime SDKs v10.2.4最新(Android、iOS、OSX和.NET)

    ArcGIS Runtime SDKs v10.2.4最新,它包含:Android.iOS.OS X和.NET四大平台,用户和开发人员可以登录Esri最新的SDK安装包.或者通过云盘下载(http:/ ...

  5. Android 2.3 版本中链接边框问题解决

    在做移动互联网开发的过程中,同样需要考虑到移动终端(如手机.平板)的不同版本浏览器兼容问题,在Android 2.3 版本的默认浏览器中有一个bug-会自动给所有链接文本在点击操作过程中加黄色或绿色边 ...

  6. Asp.net vNext 学习1

    Asp.net vNext 学习之路(一) 概述 asp.net vNext 也叫 asp.net 5.0,意思是微软推出的下一个版本的asp.net.可以说是微软对asp.net的一个比较重大的重新 ...

  7. bat启动/停止oracle服务

    原文:bat启动/停止oracle服务 自己的电脑比较慢,尤其装了oracle10g后,服务开启和关闭用bat文件操作省事点 开启服务 @echo offnet start OracleService ...

  8. Introduction to gaussian filter 高斯滤波器

    Introduction to gaussian filter 我尝试尽可能低门槛的介绍这些好玩的东东-这里只须要正态分布函数作为基础就可以開始玩图像的高斯滤波了. Don't panic ! 在通常 ...

  9. MongoDB的C#驱动

    MongoDB的C#驱动基本使用 MongoDB的官方C#驱动可以通过这个链接得到.链接提供了.msi和.zip两种方式获取驱动dll文件. 通过这篇文章来介绍C#驱动的基本数据库连接,增删改查操作. ...

  10. SQL Server 性能调优 之运行计划(Execution Plan)调优

    运行计划中的三种 Join 策略 SQL Server 存在三种 Join 策略:Hash Join,Merge Join,Nested Loop Join. Hash Join:用来处理没有排过序/ ...