golang使用protobuf简易教程

参考文档:https://blog.csdn.net/qq_15437667/article/details/78425151

一、安装protobuf

# 去github.com/golang/protobuf下载源码包,
# 拷贝到 $GOPATH/src/github.com/golang/protobuf

$ cd $GOPATH/src/github.com/golang/protobuf
$ go install

# 安装 protobuf-compiler
$ sudo apt-get install protobuf-compiler

二、使用protobuf

1. 编写example.proto示例文件

// example.proto
syntax = "proto2";
package example;

message LD
{
    required uint32 ip = 1;
}

message Set
{
	required uint32 id	=1;
	required string name	=2;
	repeated LD ld_list	=3;
}

2. 编译生成.pb.go文件

protoc --go_out=./ example.proto

生成的 example.pb.go文件

// Code generated by protoc-gen-go. DO NOT EDIT.
// source: example.proto

package example

import proto "github.com/golang/protobuf/proto"
import fmt "fmt"
import math "math"

// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf

// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package

type LD struct {
	Ip                   *uint32  `protobuf:"varint,1,req,name=ip" json:"ip,omitempty"`
	XXX_NoUnkeyedLiteral struct{} `json:"-"`
	XXX_unrecognized     []byte   `json:"-"`
	XXX_sizecache        int32    `json:"-"`
}

func (m *LD) Reset()         { *m = LD{} }
func (m *LD) String() string { return proto.CompactTextString(m) }
func (*LD) ProtoMessage()    {}
func (*LD) Descriptor() ([]byte, []int) {
	return fileDescriptor_example_c8b6363476e787b3, []int{0}
}
func (m *LD) XXX_Unmarshal(b []byte) error {
	return xxx_messageInfo_LD.Unmarshal(m, b)
}
func (m *LD) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
	return xxx_messageInfo_LD.Marshal(b, m, deterministic)
}
func (dst *LD) XXX_Merge(src proto.Message) {
	xxx_messageInfo_LD.Merge(dst, src)
}
func (m *LD) XXX_Size() int {
	return xxx_messageInfo_LD.Size(m)
}
func (m *LD) XXX_DiscardUnknown() {
	xxx_messageInfo_LD.DiscardUnknown(m)
}

var xxx_messageInfo_LD proto.InternalMessageInfo

func (m *LD) GetIp() uint32 {
	if m != nil && m.Ip != nil {
		return *m.Ip
	}
	return 0
}

type Set struct {
	Id                   *uint32  `protobuf:"varint,1,req,name=id" json:"id,omitempty"`
	Name                 *string  `protobuf:"bytes,2,req,name=name" json:"name,omitempty"`
	LdList               []*LD    `protobuf:"bytes,3,rep,name=ld_list" json:"ld_list,omitempty"`
	XXX_NoUnkeyedLiteral struct{} `json:"-"`
	XXX_unrecognized     []byte   `json:"-"`
	XXX_sizecache        int32    `json:"-"`
}

func (m *Set) Reset()         { *m = Set{} }
func (m *Set) String() string { return proto.CompactTextString(m) }
func (*Set) ProtoMessage()    {}
func (*Set) Descriptor() ([]byte, []int) {
	return fileDescriptor_example_c8b6363476e787b3, []int{1}
}
func (m *Set) XXX_Unmarshal(b []byte) error {
	return xxx_messageInfo_Set.Unmarshal(m, b)
}
func (m *Set) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
	return xxx_messageInfo_Set.Marshal(b, m, deterministic)
}
func (dst *Set) XXX_Merge(src proto.Message) {
	xxx_messageInfo_Set.Merge(dst, src)
}
func (m *Set) XXX_Size() int {
	return xxx_messageInfo_Set.Size(m)
}
func (m *Set) XXX_DiscardUnknown() {
	xxx_messageInfo_Set.DiscardUnknown(m)
}

var xxx_messageInfo_Set proto.InternalMessageInfo

func (m *Set) GetId() uint32 {
	if m != nil && m.Id != nil {
		return *m.Id
	}
	return 0
}

func (m *Set) GetName() string {
	if m != nil && m.Name != nil {
		return *m.Name
	}
	return ""
}

func (m *Set) GetLdList() []*LD {
	if m != nil {
		return m.LdList
	}
	return nil
}

func init() {
	proto.RegisterType((*LD)(nil), "example.LD")
	proto.RegisterType((*Set)(nil), "example.Set")
}

func init() { proto.RegisterFile("example.proto", fileDescriptor_example_c8b6363476e787b3) }

var fileDescriptor_example_c8b6363476e787b3 = []byte{
	// 109 bytes of a gzipped FileDescriptorProto
	0x1f, 0x8b, 0x08, 0x00, 0x00, 0x09, 0x6e, 0x88, 0x02, 0xff, 0xe2, 0xe2, 0x4d, 0xad, 0x48, 0xcc,
	0x2d, 0xc8, 0x49, 0xd5, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x62, 0x87, 0x72, 0x95, 0x04, 0xb8,
	0x98, 0x7c, 0x5c, 0x84, 0xb8, 0xb8, 0x98, 0x32, 0x0b, 0x24, 0x18, 0x15, 0x98, 0x34, 0x78, 0x95,
	0x6c, 0xb9, 0x98, 0x83, 0x53, 0x4b, 0xc0, 0x42, 0x29, 0x10, 0x21, 0x21, 0x1e, 0x2e, 0x96, 0xbc,
	0xc4, 0xdc, 0x54, 0x09, 0x26, 0x20, 0x8f, 0x53, 0x48, 0x86, 0x8b, 0x3d, 0x27, 0x25, 0x3e, 0x27,
	0xb3, 0xb8, 0x44, 0x82, 0x59, 0x81, 0x59, 0x83, 0xdb, 0x88, 0x5b, 0x0f, 0x66, 0xb8, 0x8f, 0x0b,
	0x20, 0x00, 0x00, 0xff, 0xff, 0x2d, 0xbd, 0x0b, 0xe7, 0x69, 0x00, 0x00, 0x00,
}

特别注意: 生成的文件中的package是example, 那么文件必须放在example文件夹下! 否则会报错: “can’t load package: package example

三、写一个测试程序

package main

import (
	"fmt"
	t "./example"
	"github.com/golang/protobuf/proto"
)

func main() {
	var hw t.Set
	var ld t.LD

	ld = t.LD {
		Ip: proto.Uint32(666),
	}

	hw = t.Set {
		Id: proto.Uint32(1),
		Name: proto.String("hello"),
	}

	mData, err := proto.Marshal(&hw)

	if err != nil {
		fmt.Println("Error1:", err)
		return
	}

	var umData t.Set
	err = proto.Unmarshal(mData, &umData)

	if err != nil {
		fmt.Println("Error2:", err)
		return
	}

	fmt.Println(*umData.Id, " ", *umData.Name, " ", *ld.Ip)
}

四、编译运行

$ go build main.go
$ ./main
1   hello   666

转载于:https://my.oschina.net/u/3045933/blog/1929275

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值