golang protobuf 安装使用

  1. 安装protoc

    git clone https://github.com/google/protobuf.git

    cd protobuf

    sudo apt-get install autoconf automake libtool curl make g++ unzip

    ./autogen.sh

    ./configure

    make

    make check

    sudo make install

    sudo ldconfig # refresh shared library cache.

  2. 安装编译器的golang插件

    //protoc-gen-go默认安装在:$GOBIN或$GOPATH/bin,方便protoc通过$PATH查找protoc-gen-go

    //$GOPATH=/data/golang

    go get -u github.com/golang/protobuf/protoc-gen-go

  3. protobuf使用

    mkdir -p /data/golang/shared/proto

    cd /data/golang/shared/proto

    编辑test.proto, 用于网络协议数据组织

    test.proto:

    syntax = "proto3";

    package tutorial;

    message Person { string name = 1; int32 id = 2; // Unique ID number for this person. string email = 3;

    enum PhoneType { MOBILE = 0; HOME = 1; WORK = 2; }

    message PhoneNumber { string number = 1; PhoneType type = 2; }

    repeated PhoneNumber phones = 4; }

    // Our address book file is just one of these. message AddressBook { repeated Person people = 1; }

    protoc --go_out=/data/golang/src/test/proto-test test.proto

    建立工程, 引入产生golang代码的网络协议(test.pb.go).

例子:

package main

import (

"fmt"

im "test/proto-test"

proto "github.com/golang/protobuf/proto"

)

func main() {

/*  
var user *im.Person = &im.Person{
    Name: *proto.String("jack"),
    Id: *proto.Int32(100),
    Email: *proto.String("365@163.com"),
};  
*/  
var user *im.Person = &im.Person{
    Name: "meng",
    Id: 100,
    Email: "123@163.com",
};  
//编码
fmt.Println(user.String());
buffer,_ := proto.Marshal(user);
fmt.Println(buffer);

//解码
var copy_user = &im.Person{};
proto.Unmarshal(buffer, copy_user);
fmt.Printf("copy_user=%v\n", copy_user);

}

转载于:https://my.oschina.net/u/988780/blog/676665

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值