1

This is my proto file:

import "google/protobuf/struct.proto";

service Renderer {
  rpc Render(Request) returns (Response) {}
}

message Request {
  string template = 1;
  string locale = 2;
  google.protobuf.Struct variables = 3;
}

In the following function:

func (s *Server) Render(
    ctx context.Context,
    message *Request,
) (*Response, error) {
    fmt.Println(message.Variables.AsMap()) // is always empty

    return &Response{}, nil
}

the variables field is always empty even when I send this to the server:

{
    "template": "template_name",
    "locale": "pt",
    "variables": {
        "foo": "bar"
    }
}

I'm expecting variables to contain foo as a key and bar as the value. What I'm doing wrong? What can I do to achieve this in case I'm doing it wrong?

Eleandro Duzentos
  • 1,370
  • 18
  • 36

1 Answers1

0

Have a look at structpb. It contains a decent example.

You can't use the JSON example below because it is a map[string]string and this is insufficiently general-purpose to represent dynamic types.

variables": {
  "foo": "bar"
}

If you use structpb to generate your {"foo":"bar"} value:

package main

import (
    "log"

    "google.golang.org/protobuf/types/known/structpb"
)

func main() {
    v, err := structpb.NewStruct(map[string]interface{}{
        "foo": "bar",
    })
    if err != nil {
        log.Fatal(err)
    }

    log.Println(v)
}

You'll see that v is represented in Go as:

fields:
  key:"foo" 
  value:{
    string_value:"bar"
  }
}

This is what is expected by Server.Render as message.Variables in your code.

DazWilkin
  • 32,823
  • 5
  • 47
  • 88