Home >Backend Development >Golang >Is `google.protobuf.Struct` the Optimal Choice for Sending Dynamic JSON via gRPC?

Is `google.protobuf.Struct` the Optimal Choice for Sending Dynamic JSON via gRPC?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-11 13:55:11669browse

Is `google.protobuf.Struct` the Optimal Choice for Sending Dynamic JSON via gRPC?

Is "google/protobuf/struct.proto" the Best Way to Send Dynamic JSON over GRPC?

Utilizing the google.protobuf.Struct type provides an efficient solution for transmitting dynamic JSON data over GRPC. Consider the following User.proto file:

syntax = "proto3";
package messages;
import "google/protobuf/struct.proto";

service UserService {
    rpc SendJson (SendJsonRequest) returns (SendJsonResponse) {}
}

message SendJsonRequest {
    string UserID = 1;
    google.protobuf.Struct Details = 2;
}

message SendJsonResponse {
    string Response = 1;
}

Anuj's Solution:

While functional, this approach is somewhat convoluted:

var item = &structpb.Struct{
    Fields: map[string]*structpb.Value{
        "name": &structpb.Value{
            Kind: &structpb.Value_StringValue{
                StringValue: "Anuj",
            },
        },
        "age": &structpb.Value{
            Kind: &structpb.Value_StringValue{
                StringValue: "Anuj",
            },
        },
    },
}

Luke's Solution:

This method is more concise but involves multiple conversions:

m := map[string]interface{}{
  "foo":"bar",
  "baz":123,
}
b, err := json.Marshal(m)
s := &structpb.Struct{}
err = protojson.Unmarshal(b, s)

Recommended Solution:

The most straightforward and efficient approach is to utilize the built-in functions provided by the structpb package:

m := map[string]interface{}{
    "name": "Anuj",
    "age":  23,
}

details, err := structpb.NewStruct(m) // Check for errors as per documentation
if err != nil {
    panic(err)
}

userGetRequest := &pb.SendJsonRequest{
    UserID: "A123",
    Details: details,
}

Remember to adhere to the conversion rules specified in the structpb documentation to avoid errors.

The above is the detailed content of Is `google.protobuf.Struct` the Optimal Choice for Sending Dynamic JSON via gRPC?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn