go使用protobuf(以及封装JSON2PB、PB2JSON)
GO Protobuf    2019-08-26 14:12:37    148    0    0
admin   GO Protobuf
  1. package main
  2.  
  3. import (
  4.    "github.com/golang/protobuf/proto"
  5.    "git.dllhook.com/protobuf_test/proto"
  6.    "log"
  7.    "fmt"
  8.    "encoding/json"
  9. )
  10.  
  11. func JSON2PB(form_json_str string, to_pb proto.Message) error {
  12.    // json字符串转pb
  13.    return json.Unmarshal([]byte(form_json_str), &to_pb)
  14. }
  15.  
  16. func PB2JSON(from_pb proto.Message, to_json_str string) error {
  17.    // pb转json字符串
  18.    json_str, err := json.Marshal(from_pb)
  19.    if err == nil {
  20.       to_json_str = string(json_str)
  21.    }
  22.  
  23.    return err
  24. }
  25.  
  26. func main() {
  27.    ///////////////////////////////////////////////////////////////////////////////////////////
  28.    /* -- 直接对pb赋值
  29.    deviceInfo := example.DeviceInfo{
  30.       DeviceName: proto.String("PiaoYun iPhone"),
  31.       DeviceType: proto.String("iPhone"),
  32.       SystemVersion: proto.String("9.0.2"),
  33.    }
  34.    */
  35.  
  36.    // json转pb
  37.    json_str := `{"DeviceName":"PiaoYun iPhone","DeviceType":"iPhone","SystemVersion":"9.0.2"}`
  38.    var deviceInfo www_dllhook_com.DeviceInfo
  39.    err := JSON2PB(json_str, &deviceInfo)
  40.    fmt.Println(err)
  41.    ///////////////////////////////////////////////////////////////////////////////////////////
  42.  
  43.    // 编码
  44.    data, err := proto.Marshal(&deviceInfo)
  45.    if err != nil {
  46.       log.Fatal("marshaling error: ", err)
  47.    }
  48.    fmt.Println(data)
  49.    // 调试输出
  50.    fmt.Println(proto.MarshalTextString(&deviceInfo))
  51.  
  52.    // 解码
  53.    newDeviceInfo := &www_dllhook_com.DeviceInfo{}
  54.    err = proto.Unmarshal(data, newDeviceInfo)
  55.    if err != nil {
  56.       log.Fatal("unmarshaling error: ", err)
  57.    }
  58.    fmt.Println(newDeviceInfo)
  59.  
  60.    // pb转json字符串
  61.    err = PB2JSON(newDeviceInfo, json_str)
  62.    fmt.Println(err)
  63.    fmt.Println(json_str)
  64. }
  1. syntax="proto2"
  2.  
  3. package www_dllhook_com;
  4.  
  5. message DeviceInfo {
  6.    optional string DeviceName    = 1;
  7.    optional string DeviceType    = 2;
  8.    optional string SystemVersion = 3;
  9.  
  10. }

上一篇: PHP7 使用 protobuf,以及protobuf简介

下一篇: 在职场上,优秀的管理都是怎样做的?

148
登录 后评论.
没有帐号? 现在注册.
0 评论
Table of content