golang protobuf 安装使用

前端之家收集整理的这篇文章主要介绍了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://www.f2er.com/go/189766.html

猜你在找的Go相关文章