-
安装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.
-
安装编译器的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
-
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=%vn",copy_user);
} (编辑:李大同)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|