[Go] 使用protobuf進行序列化和反序列化


先定義消息類型

orders.proto

syntax = "proto2";
package message;
message Orders {
required int32 order_id=1;
required string title=2;
}

在GOPATH創建目錄和編譯這個消息類型輸出到該目錄,包名是message

mkdir $GOPATH/src/message;protoc --go_out $GOPATH/src/message orders.proto 

編寫go文件進行序列化和反序列化剛才生成的包里的類型結構體數據

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())

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM