1, download protobuf compiler protoc
address:https:
//github.com/google/protobuf/releases
window:
Download: protoc-3.3.0-win32.zip
unzip, copy protoc.exe in the bin directory to GOPATH / bin, GOPATH / bin added to the environment variable.
Of course, also be placed in other directories, environment variables must be added, allowing the system to find protoc.exe
Linux:
Download: protoc-3.3.0-linux-x86_64.zip or protoc-3.3.0-linux-x86_32.zip
decompression, the protoc in the bin directory to the GOPATH / bin, GOPATH / bin added to the environment variable.
If you like to compile and install, and can also download the source code to install itself, and finally the executable file to the environment variable.
2, get protobuf compiler plugins protoc-gen-go
into the directory GOPATH
run>
go
get -u github.com/golang/protobuf/protoc-gen-
go
If successful, it will generate protoc-gen-go.exe files in GOPATH / bin
3, create a file test.proto
// specified version
// Note the wording proto3 and proto2 somewhat different
syntax = "proto3";
// package name, is generated when go through protoc file
Package Penalty for the Test;
// phone type
// enum type must be the first field 0
enum {PhoneType
the HOME = 0;
WORK =. 1;
}
// Mobile
Message phone {
PhoneType type =. 1;
String number = 2;
}
// al
Message the person {
// number after the identification number indicates
Int32 ID =. 1;
String 2 = name;
// rEPEATED represents repeat
// there may be multiple phone
rEPEATED phone pHONES =. 3;
}
// Information Directory
Message ContactBook {
rEPEATED the Person = persons. 1;
}
4. run the following commands
. protoc --go_out = * .proto
Test.pb.go will generate a file, the specific contents of the documents I will not screenshot.
5, using protobuf go in languages
package main;
import (
"github.com/golang/protobuf/proto"
"go_dev/kongji/proto/test"
"io/ioutil"
"os"
"fmt"
)
func write() {
p1 := &test.Person{
Id: 1,
Name: "小张",
Phones: []*test.Phone{
{test.PhoneType_HOME, "111111111"},
{test.PhoneType_WORK, "222222222"},
},
};
p2 := &test.Person{
Id: 2,
Name: "小王",
Phones: []*test.Phone{
{test.PhoneType_HOME, "333333333"},
{test.PhoneType_WORK, "444444444"} // create an address book };
}
Book: = {} & test.ContactBook;
book.Persons = the append (book.Persons, P1);
book.Persons = the append (book.Persons, P2);
// data encoded
data, _: = proto.Marshal (book ) ;
// write the file data
ioutil.WriteFile ( "./ test.txt", data, os.ModePerm);
}
FUNC read () {
// read the data file
data, _: = ioutil.ReadFile ( " . /test.txt ");
Book: & test.ContactBook = {};
// decoded data
proto.Unmarshal (data, Book);
for _, V: = Range book.Persons {
fmt.Println (V.ID, V. name);
for _, VV: = Range v.Phones {
fmt.Println (vv.Type, vv.Number);
}
}
}
FUNC main () {
Write ();
read();
}