Protobuf is an efficient data format, platform-independent, language-independent, extensible for RPC systems and continuous data storage systems.
Protobuf is introduced
Protobuf is short for Protocol Buffer, which is an efficient platform-independent, language-independent and extensible data format developed by Google in 2008. Currently, Protobuf is a description language of interface specification and can be used as the basic tool of RPC interface of Go language.
Protobuf use
Protobuf is a language-independent data protocol, so we need to write IDL files and then use specialized tools to generate language-specific code to achieve data serialization and deserialization process.
The general development process is as follows: 1. IDL preparation; 2. Serialization and deserialization
Protobuf grammar
Protobuf3 syntax guide
Compiler installation
ptotoc
The protobuf protocol compiler is written in c++. Download the corresponding version of the protoc compiler according to your operating system: github.com/protocolbuf… Decompress the package and copy it to the GOPATH/bin directory.
protoc-gen-go
Install tools that generate Go language code
go get -u github.com/golang/protobuf/protoc-gen-go
Copy the code
Write IDL code
Create a new file named person.proto in the protobuf_demo/address directory as follows:
Syntax = "proto3"; // Package name, using protoc to generate go file package address; // GenderType // Enumeration type the first field must be 0. Enum GenderType {SECRET = 0; FEMALE = 1; MALE = 2; } // message Person {int64 id = 1; string name = 2; GenderType gender = 3; string number = 4; } // Message ContactBook {repeated Person persons = 1; }Copy the code
Generate go language code
Run the following command in the protobuf_demo/address directory.
address $ protoc --go_out=. ./person.proto
Copy the code
At this point, a person.pb.go file is generated in the current directory, which is used in our GO language code. In the protobuf_demo/main.go file:
package main import ( "fmt" "io/ioutil" "github.com/golang/protobuf/proto" "github.com/Q1mi/studygo/code_demo/protobuf_demo/address" ) // protobuf demo func main() { var cb address.ContactBook p1 GenderType_MALE := address.Person{Name: "little prince ", Gender: address.GenderType_MALE, Number: = address.Person{Name:" little prince ", Gender: address. "7878778",} FMT.Println(p1) cb.Persons = append(cb.Persons, &p1), err := Marshal(&p1) if err! = nil { fmt.Printf("marshal failed,err:%v\n", err) return } ioutil.WriteFile("./proto.dat", data, 0644) data2, err := ioutil.ReadFile("./proto.dat") if err ! = nil { fmt.Printf("read file failed, err:%v\n", err) return } var p2 address.Person proto.Unmarshal(data2, &p2) fmt.Println(p2) }Copy the code
The above is a brief introduction of Protobuf, if you want to know more, welcome to pay attention to “Go keyboard man” public number, exchange and study together!
Previous Article:
First knowledge of gRPC