码迷,mamicode.com
首页 > 其他好文 > 详细

go protobuf 编码与解码

时间:2018-11-16 13:58:06      阅读:360      评论:0      收藏:0      [点我收藏+]

标签:img   alt   for   print   error   highlight   imp   erp   div   

package main

import (
	"encoding/hex"
	"fmt"
	"github.com/golang/protobuf/proto"
	"github.com/golang/protobuf/ptypes"
	"github.com/golang/protobuf/ptypes/any"
	"reflect"
)
import "./protos/protos_pb"

func typeForName(name string) (reflect.Type, error) {
	pt := proto.MessageType(name)
	if pt == nil {
		return nil, fmt.Errorf("unknown type: %q", name)
	}
	st := pt.Elem()

	return st, nil
}

func main() {
	test := &logon.SearchRequest{
		Query:         "",
		PageNumber:    222,
		ResultPerPage: 111,
		Corpus:        logon.SearchRequest_WEB,
	}
	dst, err := proto.Marshal(test)
	if err != nil {
		return
	}
	fmt.Println(dst)
	fmt.Println(hex.EncodeToString(dst))

	// 解析数据 -- 方式一
	test1 := &logon.SearchRequest{}
	proto.Unmarshal(dst, test1)
	fmt.Printf("方式一 :unmarshaled message: %v\n", test1)

	// 方式二
	name := "logon.SearchRequest"
	pt := proto.MessageType(name)
	a := reflect.New(pt.Elem()).Interface().(proto.Message)
	proto.Unmarshal(dst, a)
	fmt.Printf("方式二 :unmarshaled message: %v\n", a)


	// 方式三
	var x ptypes.DynamicAny
	var xa = &any.Any{TypeUrl:"./" + name,Value: dst}
	if err := ptypes.UnmarshalAny(xa, &x); err != nil {
		fmt.Println(err)
		return;
	}
	fmt.Printf("方式三 :unmarshaled message: %v\n", x.Message)

	// 方式四
	x2 := reflect.New(pt.Elem()).Interface().(proto.Message)
	var xa2 = &any.Any{TypeUrl:"./"+name,Value: dst}
	if err := ptypes.UnmarshalAny(xa2, x2); err != nil {
		fmt.Println(err)
		return;
	}
	fmt.Printf("方式四 :unmarshaled message: %v\n", x2)
}

 

syntax = "proto3";

package logon;

message SearchRequest {
    string query = 1;
    int32 page_number = 2;
    int32 result_per_page = 3;
    enum Corpus {
        UNIVERSAL = 0;
        WEB = 1;
        IMAGES = 2;
        LOCAL = 3;
        NEWS = 4;
        PRODUCTS = 5;
        VIDEO = 6;
    }
    Corpus corpus = 4;
}

message SearchResponse {
    string response = 1;
}

 技术分享图片

go protobuf 编码与解码

标签:img   alt   for   print   error   highlight   imp   erp   div   

原文地址:https://www.cnblogs.com/dzqdzq/p/9968863.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!