How to use `google.protobuf.Any` in Go with primitive types?

Viewed 1371

I have a message like

message Response {
  google.protobuf.Any id = 1;
  string message = 3;
}

and I would like to encode either an int32 or string in ID.

I can achieve this by making some wrapper type

message IntWrapper {
  int32 id = 1;
}

and using ptypes.MarshalAny from github.com/golang/protobuf/ptypes to marshal my new types since they implement proto.Message.

ptypes.MarshalAny(&myproto.IntWrapper{Id: 1})

I'd like to do this without the wrappers. Are there implementations of proto.Message somewhere for plain int32's or string's or another way to do this?

(Footnote: I do not want to implement proto.Message, but have it provided or autogenerated)

1 Answers

Although wrapping is necessary, Protobuf conveniently provides wrappers for primitive types in google.protobuf.wrappers.proto.

Here is an example of how to use google.protobuf.Any with primitive types in Go using the packages generated from these protos:

package main

import (
    "fmt"

    "google.golang.org/protobuf/types/known/anypb"
    "google.golang.org/protobuf/types/known/wrapperspb"
)

func main() {
    strWrapper := wrapperspb.String("foo")
    strAny, _ := anypb.New(strWrapper)
    fmt.Println(strAny)

    intWrapper := wrapperspb.Int32(123)
    intAny, _ := anypb.New(intWrapper)
    fmt.Println(intAny)
}
Related