1. Download Protoc
- can go to https://github.com/google/protobuf/releases download the source code to compile their own
- or https://github.com/google/protobuf/releases to download a compiled binary file
2. Installing Protoc-gen-go
go get github.com/golang/protobuf/protoc-gen-go
After installation, you will find Protoc-gen-go.exe under $gopath/bin.
3. Generate protocol code using Protoc.exe and Protoc-gen-go.exe
protoc --proto_path=./proto --go_out=./src_gen/go/ scoreserver/score_info.proto
Note that when used, Protoc.exe and Protoc-gen-go.exe are placed in the same directory, or both paths are placed in the environment variable path
4. Installing the PROTOBUF Library
go get github.com/golang/protobuf/proto
5. Test code
syntax = "proto2";package score_server;/** * @brief base_score_info */message base_score_info_t{ optional int32 win_count = 1; // 玩家胜局局数 optional int32 lose_count = 2; // 玩家负局局数 optional int32 exception_count = 3; // 玩家异常局局数 optional int32 kill_count = 4; // 总人头数 optional int32 death_count = 5; // 总死亡数 optional int32 assist_count = 6; // 总总助攻数 optional int64 rating = 7; // 评价积分}
Pb_test Project Main.gopackage mainimport ("FMT" "Proto/scoreserver" "Github.com/golang/protobuf/proto") func Main () {score_info: = &score_server. basescoreinfot{} score_info. Wincount = New (Int32) *score_info. Wincount = 1 Score_info. Losecount = New (Int32) *score_info. Losecount = 2 Score_info. Exceptioncount = New (Int32) *score_info. Exceptioncount = 3 Score_info. Killcount = New (Int32) *score_info. Killcount = 4 Score_info. Deathcount = New (Int32) *score_info. Deathcount = 5 Score_info. Assistcount = New (Int32) *score_info. Assistcount = 6 Score_info. Rating = new (Int64) *score_info. Rating = 1800 FMT. Printf ("Original data{%s}\n", Score_info. String ())//Encode data, err: = Proto. Marshal (score_info) if err! = Nil {fmt. Printf ("Proto encode error[%s]\n", err. Error ()) return}//decode score_info_1: = &score_server. basescoreinfot{} err = Proto. Unmarshal (data, score_info_1) if err! = Nil { Fmt. Printf ("Proto decode error[%s]\n", err. Error ()) return} *score_info_1.rating = Fmt. Printf ("After Decode:{%s}\n", Score_info_1.string ())}
Code Run Result:
original data{win_count:1 lose_count:2 exception_count:3 kill_count:4 death_count:5 assist_count:6 rating:1800 }after decode:{win_count:1 lose_count:2 exception_count:3 kill_count:4 death_count:5 assist_count:6 rating:2000 }