天天看點

go protobuf 編碼與解碼使用

 引入子產品 "google.golang.org/protobuf/proto"

  導入 xxx.pb.go檔案

go protobuf 編碼與解碼使用

執行個體化proto資料結構 

//執行個體化proto資料結構
  rpc := &RPCInfo{
    Cid:     *proto.String("123457"),
    Fn:      *proto.String("hello"),
    ReplyTo: *proto.String("232244"),
    Track:   *proto.String("track"),
    Expired: *proto.Int64(time.Now().UnixNano() / 1000000),
    Reply:   *proto.Bool(true),
  }
  rpc.ArgsType = []string{"s", "s"}
  rpc.Args = [][]byte{[]byte("hello"), []byte("world")}
  rpc.Caller = "caller"
  rpc.Hostname = "localhost"      
//編碼
data, err := proto.Marshal(rpc)      
//解碼
newRPC := &RPCInfo{}
err = proto.Unmarshal(data, newRPC)      
package main

import (
  "fmt"
  "time"

  "google.golang.org/protobuf/proto"
)

func main() {
//執行個體化proto資料結構
  rpc := &RPCInfo{
    Cid:     *proto.String("123457"),
    Fn:      *proto.String("hello"),
    ReplyTo: *proto.String("232244"),
    Track:   *proto.String("track"),
    Expired: *proto.Int64(time.Now().UnixNano() / 1000000),
    Reply:   *proto.Bool(true),
  }
  rpc.ArgsType = []string{"s", "s"}
  rpc.Args = [][]byte{[]byte("hello"), []byte("world")}
  rpc.Caller = "caller"
  rpc.Hostname = "localhost"

  //編碼
  data, err := proto.Marshal(rpc)

  fmt.Println("編碼:---> ", data)

  if err != nil {
    fmt.Println("Marshal error:", err)
  }

  //解碼
  newRPC := &RPCInfo{}
  err = proto.Unmarshal(data, newRPC)
  fmt.Println("解碼:---> ", newRPC)

  if err != nil {
    fmt.Println("Unmarshal error:", err)
  }

  if rpc.ReplyTo != newRPC.GetReplyTo() {
    fmt.Println("rpc.ReplyTo != newRPC.GetReplyTo", err)
  }
}      

繼續閱讀