在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
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; }
|
请发表评论