先定義消息類型git
orders.protogithub
syntax = "proto2"; package message; message Orders { required int32 order_id=1; required string title=2; }
在GOPATH建立目錄和編譯這個消息類型輸出到該目錄,包名是messagegolang
mkdir $GOPATH/src/message;protoc --go_out $GOPATH/src/message orders.proto
編寫go文件進行序列化和反序列化剛纔生成的包裏的類型結構體數據ui
package main import "message" import "github.com/golang/protobuf/proto" import "fmt" func main() { orders := &message.Orders{ OrderId: proto.Int32(1), Title: proto.String("第一個訂單"), } //序列化成二進制數據 ordersBytes, _ := proto.Marshal(orders) //反序列化二進制數據 twoOrders := &message.Orders{} proto.Unmarshal(ordersBytes, twoOrders) fmt.Println(twoOrders.GetTitle()) fmt.Println(twoOrders.GetOrderId()) }