Answer the question
In order to leave comments, you need to log in
Google Protobuf - how to determine the type of incoming message?
I'm learning protobuf, I ran into such a disaster. Let's say we have this .proto:
syntax = "proto3";
package example;
message Kaboom {
uint64 data = 1;
}
message Oops {
uint64 data = 1;
}
Answer the question
In order to leave comments, you need to log in
generally speaking, you can do it through the message wrapper, but it seems like it’s more correct to do it through Oneof, you can study an example on go here . message type selection is strings
// Use a type switch to determine which oneof was set.
switch u := test.Union.(type) {
case *pb.Test_Number: // u.Number contains the number.
case *pb.Test_Name: // u.Name contains the string.
}
You can make a `kind` field.
syntax = "proto3";
package entity;
message Entity {
// Kinds:
//
// * kaboom
// * oops
string kind = 1;
message Kaboom { uint64 data = 1; }
message Oops { uint64 data = 1; }
Kaboom kaboom = 2;
Oops oops = 3;
}
package main
import (
"github.com/golang/protobuf/proto"
"pathtopkg/entity"
)
func main() {
var e entity.Entity
err := proto.Unmarshal(buf, &e)
if err != nil {
panic(err)
}
switch e.Kind {
case "kaboom":
// Kaboom
case "oops":
// Oops
default:
panic("Invalid kind")
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question