golang protobuf 的序列化和反序列化

1、通过proto文件生成go代码

hello.proto

syntax = "proto3";
package prototest;

message Test {
    int32 num = 1;
    string msf = 2;
}

hello.pb.go

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

/*
Package prototest is a generated protocol buffer package.

It is generated from these files:
    hello.proto

It has these top-level messages:
    Test
*/
package prototest

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 Test struct {
    Num int32  `protobuf:"varint,1,opt,name=num" json:"num,omitempty"`
    Msf string `protobuf:"bytes,2,opt,name=msf" json:"msf,omitempty"`
}

func (m *Test) Reset()                    { *m = Test{} }
func (m *Test) String() string            { return proto.CompactTextString(m) }
func (*Test) ProtoMessage()               {}
func (*Test) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} }

func (m *Test) GetNum() int32 {
    if m != nil {
        return m.Num
    }
    return 0
}

func (m *Test) GetMsf() string {
    if m != nil {
        return m.Msf
    }
    return ""
}

func init() {
    proto.RegisterType((*Test)(nil), "prototest.Test")
}

func init() { proto.RegisterFile("hello.proto", fileDescriptor0) }

var fileDescriptor0 = []byte{
    // 85 bytes of a gzipped FileDescriptorProto
    0x1f, 0x8b, 0x08, 0x00, 0x00, 0x09, 0x6e, 0x88, 0x02, 0xff, 0xe2, 0xe2, 0xce, 0x48, 0xcd, 0xc9,
    0xc9, 0xd7, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0xe2, 0x04, 0x53, 0x25, 0xa9, 0xc5, 0x25, 0x4a,
    0x5a, 0x5c, 0x2c, 0x21, 0x40, 0x5a, 0x48, 0x80, 0x8b, 0x39, 0xaf, 0x34, 0x57, 0x82, 0x51, 0x81,
    0x51, 0x83, 0x35, 0x08, 0xc4, 0x04, 0x89, 0xe4, 0x16, 0xa7, 0x49, 0x30, 0x01, 0x45, 0x38, 0x83,
    0x40, 0xcc, 0x24, 0x36, 0xb0, 0x36, 0x63, 0x40, 0x00, 0x00, 0x00, 0xff, 0xff, 0xc5, 0x3d, 0x96,
    0x7b, 0x4c, 0x00, 0x00, 0x00,
}

2、main函数

package main

import (
    "demo/prototest"
    "github.com/gogo/protobuf/proto"
    "fmt"
)

func main(){
    obj := &prototest.Test{1,"jack"}
    data,_ := proto.Marshal(obj)

    unObj := &prototest.Test{}
    proto.Unmarshal(data, unObj)
    fmt.Println(unObj)
}

运行结果

num:1 msf:"jack" 

Process finished with exit code 0

你可能感兴趣的:(go,protobuf,协议)