This is a creation in Article, where the information may have evolved or changed.
1. Download Protobuf compiler Protoc
Address:
Https://github.com/google/protobuf/releases
Window
Download: Protoc-3.3.0-win32.zip
Unzip, copy the Protoc.exe under the bin directory to Gopath/bin, Gopath/bin add the environment variable.
Of course can be placed in other directories, need to add environment variables, can let the system find Protoc.exe
Linux:
Download: Protoc-3.3.0-linux-x86_64.zip or Protoc-3.3.0-linux-x86_32.zip
Unzip, copy the Protoc under the bin directory to Gopath/bin, Gopath/bin add the environment variable.
If you like to compile and install, you can also download the source code to install itself, and finally add the executable to the environment variables.
2. Get Protobuf Compiler plugin Protoc-gen-go
Enter the Gopath directory
Run
> Go get-u github.com/golang/protobuf/protoc-gen-go
If successful, the Protoc-gen-go.exe file is generated under Gopath/bin
3. Create a Test.proto file
Specify version//note Proto3 and Proto2 are somewhat different syntax = "PROTO3";//package name, when a go file is generated by Protoc, the first field of the kit test;//phone type//enum type must be 0enum Phonetype { HOME = 0; Work = 1;} Cell phone message phone { Phonetype type = 1; string number = 2;} Human message Person { //followed by a number indicating the identification number int32 id = 1; String name = 2; Repeated indicates repeatable //can have multiple phones repeated phone phones = 3;} Contact Book message Contactbook { repeated person persons = 1;}
4. Run the following command
> Protoc--go_out=. *.proto
Will generate a test.pb.go file, the specific contents of the file I will not.
5. Using Protobuf in the Go language
Package Main;import ("Github.com/golang/protobuf/proto" "Protobuf/test" "Io/ioutil" "OS" "FMT") Func write () {p1: = & Test. Person{id: 1,name: "Xiao Zhang", phones: []*test. Phone{{test. Phonetype_home, "111111111"},{test. Phonetype_work, "222222222"},},};p 2: = &test. Person{id: 2,name: "Xiao Wang", phones: []*test. Phone{{test. Phonetype_home, "333333333"},{test. Phonetype_work, "444444444"},},};//create Address Book: = &test. Contactbook{};book. Persons = Append (book. Persons, p1); Persons = Append (book. Persons, p2);//encoded data, _: = Proto. Marshal (book);//write data to file Ioutil. WriteFile ("./test.txt", data, OS.) Modeperm);} Func read () {//Read file data, _: = Ioutil. ReadFile ("./test.txt"); Book: = &test. contactbook{};//decoding 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 ();}