zoukankan      html  css  js  c++  java
  • go protobuf 编码与解码

    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
    ", 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
    ", 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
    ", 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
    ", 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;
    }
    

     

  • 相关阅读:
    在windows环境中使用varnish
    CENTOS 5.5 64位 编译安装 webbench 1.5网站压力测试工具
    CentOS设置时间
    Tomcat性能优化
    Squid 2.6 2.7 3.0 3.1 以及 varnish 2.1.5 性能对比测试
    Varnish加速网站图片显示
    保护你的Web服务器 iptables防火墙脚本全解读
    纯静态文件环境下的Nginx优化思路
    tomcat报 Context [] startup failed due toprevious errors
    siege工具安装
  • 原文地址:https://www.cnblogs.com/dzqdzq/p/9968863.html
Copyright © 2011-2022 走看看