go protobuf 编码与解码
Posted dzqdzq
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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; }
以上是关于go protobuf 编码与解码的主要内容,如果未能解决你的问题,请参考以下文章
如何使用 Protobuf 做数据交换 | Linux 中国