Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create variable of type Map[string]interface{} in gRPC protoc buffer golang

Tags:

go

grpc

protoc

I'm using grpc golang to communicate between client and server application. Below is the code for protoc buffer.

syntax = "proto3";
package Trail;

service TrailFunc {
  rpc HelloWorld (Request) returns (Reply) {}
}

// The request message containing the user's name.
message Request {
  map<string,string> inputVar = 1;
}
// The response message containing the greetings
message Reply {
  string outputVar = 1;
}

I need to create a field inputVar of type map[string]interface{} inside message data structure instead of map[string]string. How can I achieve it? Thanks in advance.

like image 269
Radhika.S Avatar asked Oct 26 '16 10:10

Radhika.S


People also ask

Does gRPC use Protobuf?

Protocol buffers, or Protobuf, is Google's serialization/deserialization protocol that enables the easy definition of services and auto-generation of client libraries. gRPC uses this protocol as their Interface Definition Language (IDL) and serialization toolset.

What is protoc gRPC?

protobuff is a data representation like json this is also by google in fact they have some thousands of proto file are generated in their production projects. grpc. gRPC is an open-source framework developed by google. It allows us to create Request & Response for RPC and handle rest by the framework.

How do I create a .proto file?

You can use any text editor to create a . proto file. If you'd like to have syntax highlighting there are also editors that would give you that. I use IntelliJ but a quick Google search found an Eclipse plugin which appears to be free: https://code.google.com/p/protobuf-dt/.


2 Answers

proto3 has type Any

import "google/protobuf/any.proto";

message ErrorStatus {
  string message = 1;
  repeated google.protobuf.Any details = 2;
}

but if you look at its implementation, it is simply as

message Any {
  string type_url = 1;
  bytes value = 2;
}

You have to define such a message yourself by possibly using reflection and an intermediate type.

See example application

https://github.com/golang/protobuf/issues/60

like image 82
Marsel Novy Avatar answered Sep 19 '22 11:09

Marsel Novy


I wrote a longer post about how to use google.protobuf.Struct to work with arbitrary JSON input. The structpb package capable to produce a map[string]interface{} from a structpb.Struct via its AsMap() function.

Official documentation: https://pkg.go.dev/google.golang.org/protobuf/types/known/structpb

like image 35
F. Norbert Avatar answered Sep 16 '22 11:09

F. Norbert