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
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 that Proto3 and Proto2 are somewhat different.Syntax ="Proto3"; //package name, when the go file is generated by ProtocPackage test;//Phone Type//Enum Type the first field must be 0enumPhonetype {HOME=0; work=1;} //Mobile Phonemessage Phone {phonetype type=1; stringNumber =2;} //peoplemessage Person {//the number that follows indicates the identification numberInt32 id =1; stringName =2; //repeated indicates repeatable//can have multiple phonesRepeated Phone phones =3;} //Contact Bookmessage 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"}, }, }; P2:= &test. person{Id:2, Name:"Xiao Wang", phones: []*test. phone{{test. Phonetype_home,"333333333"}, {test. Phonetype_work,"444444444"}, }, }; //Create Address BookBook: = &test. contactbook{}; Book. Persons=Append (book. Persons, p1); Book. Persons=Append (book. Persons, p2); //coded DataData, _: =Proto. Marshal (book); //writing data to a fileIoutil. WriteFile ("./test.txt", data, OS. Modeperm);} Func read () {//Read file DataData, _: = Ioutil. ReadFile ("./test.txt"); Book:= &test. contactbook{}; //Decoding DataProto. 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 ();}
Original address: https://www.cnblogs.com/jkko123/p/7161843.html