go use protobuf

First install go: not to say, feel free to Baidu, or my reference, https://blog.csdn.net/u013755520/article/details/89031598 have installed go to the end;

Installation protobuf go and call interface, refer to my: https://blog.csdn.net/u013755520/article/details/91375830  ;

protobuf effect, a serialized object, the [] byte becomes: obj {Type} various properties; this object can be any type;

Analogy: https://blog.csdn.net/u013755520/article/details/90546726    binary packet, the [] byte becomes {uint32 uint32 [] byte} objects, only the basic type of the object;

protobuf and bianry packet belong to the scope of the encoding.


1.protobuf grammar

1.1 Message Type

 

1.2 Data Type

 

2. Use protobuf

2.1 in accordance with the syntax for writing xx.proto files in a directory such as proto / under

syntax = "proto3";
package pb;

message Person {
    string name = 1;
    int32 age = 2;
    repeated string emails = 3;
    repeated string phones = 4;
}

message PhoneNumber {
    string number = 1;
    PhoneType type = 2;
}
enum PhoneType {
    MOBILE = 0;
    HOME = 1;
    WORK = 2;
}

2.2 compiler: cd to the proto / directory, execute the following command

protoc --go_out=./   *.proto

It will be in the current directory, according to the files in the current directory xx.proto generate xx.pd.go file; this file each go structure, have achieved proto.Message interfaces, but I do not know why in goland You are not actually suggesting? ? ? To be studied

2.3 xx.pb.go file in the program

That is, directly in the program, as in the structure pb.go good open space, it can be directly through proto.Marshal [] byte is converted into the obj pb.go;

Conversely, directly in the program can be put on by proto.Unmashal pb.go obj is converted to [] of byte

package main

import (
	"fmt"
	"github.com/micro/protobuf/proto"
	pb "rpc/proto"
)

func main(){
	person := &pb.Person{
		Name:"yz",
		Age:11,
		Emails:[]string{"[email protected]","[email protected]"},
		Phones:[]*pb.PhoneNumber{
			&pb.PhoneNumber{
				Number:"123456",
				Type:pb.PhoneType_HOME,
			},
			&pb.PhoneNumber{
				Number:"123456",
				Type:pb.PhoneType_MOBILE,
			},
			&pb.PhoneNumber{
				Number:"123456",
				Type:pb.PhoneType_WORK,
			},
		},
	}

	//marshal:  obj---[]byte
	data,err := proto.Marshal(person)
	if err != nil {
		fmt.Println(err)
	}

	//unmarshal : []byte---obj
	newPersonObj := &pb.Person{}
	err = proto.Unmarshal(data,newPersonObj)
	if err != nil {
		fmt.Println(err)
	}

	fmt.Println(newPersonObj)
}

 

 

 

Guess you like

Origin blog.csdn.net/u013755520/article/details/91580273
Recommended