天天看点

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

继续阅读