golang使用protobuf

本文详细介绍了如何在Golang中集成protobuf,包括安装protobuf编译工具和Golang支持库,以及进行初步的测试验证。
摘要由CSDN通过智能技术生成

安装protobuf编译工具

下载最新版
https://github.com/golang/protobuf
官方网站 https://developers.google.com/protocol-buffers/docs/proto3
解压后 执行
./autogen.sh
    如碰到没有支持的程序,安装之
./configure
make
make install

安装golang支持库

下载 https://github.com/golang/protobuf
在项目src目录中建目录
    github.com/golang/protobuf/
将下载的protobuf全部copy到此目录
cd到此目录执行
    make
将编译出protoc-gen-go可执行程序,此程序提供给protobuf编译工具使用

测试

在代码目录中创建一个放置proto文件的文件夹,如 protocfg
创建.proto文件 配置protobuf数据结构如
syntax = "proto3";
package prototest;

enum FOO { X = 0; };

message Test {
	string label = 1;
	int32 type = 2 ;
	int64 reps = 19;
}
在此目录执行
/usr/local/bin/protoc --plugin={补齐}bin/protoc-gen-go --go_out=. test.proto
将会生成 test.bp.go  此文件在go程序中使用:
package main

import (
	"demo/prototest"
	"fmt"
	"libs/plog"

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

func Test() {
	fmt.Println("begin TestLog ...")
	//proto.Bool(false)

	test := &prototest.Test{Label: "hello", Type: 17, Reps: 34}
	data, err := proto.Marshal(test)
	if err != nil {
		plog.Println(plog.Warning, "demo", err.Error())
	} else {
		unTest := &prototest.Test{}
		err := proto.Unmarshal(data, unTest)
		if err == nil {
			fmt.Println("undata ", unTest.Label, unTest.Reps, unTest.Type)
		}
	}
	fmt.Println("data", data)
}

func main() {
	Test()
}








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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值