How to cast/convert nested Struct to Protobuf?

Viewed 1072

I am working on a personal project & using Go for the first time. I am using structs for operating on the data and for storing the data in a file, I am using proto as the encoder.

In the project, my proto definition looks something like this:

message AssetPairInfo {
    string Altname = 1;
    string AssetClassBase = 2;
    string Base = 3;
    .... Additional fields
}

message AssetPairsResponse {
  AssetPairInfo ADACAD = 1;
  AssetPairInfo ADAETH = 2;
  AssetPairInfo ADAEUR = 3;
  ... Additional fields
}

My struct looks like this:

type AssetPairInfo struct {
    Altname string `json:"altname"`
    AssetClassBase string `json:"aclass_base"`
    Base string `json:"base"`
    ... Additional fields
}

type AssetPairsResponse struct {
    ADACAD   AssetPairInfo
    ADAETH   AssetPairInfo
    ADAEUR   AssetPairInfo
    ... Additional fields
}

I included only 3 definitions from each struct but my structs have more than 70 definitions.. I'm looking for a programatic way to cast the AssetPairsResponse struct to my protobuf. Given the fact my struct and protobuf are sharing the same fields (except the additional generated protobuf fields), it seems like it should be possible to do.

Any idea?

1 Answers

As workaround, if the model (your custom and the proto message) share the same json tag name, you could unmarshal your custom struct and then marshal the proto message. As example:

myModel := model.AssetPairsResponse{
....
}

b, err := json.Marshal(myModel)


myProto := &pb.AssetPairsResponse{}


json.Unmarshal(b, myProto)
Related