登录
首页 >  Golang >  Go问答

如何在 Go 中运行时创建“鸭子类型”grpc protobuf 消息?

来源:stackoverflow

时间:2024-03-30 11:12:34 451浏览 收藏

今天golang学习网给大家带来了《如何在 Go 中运行时创建“鸭子类型”grpc protobuf 消息?》,其中涉及到的知识点包括等等,无论你是小白还是老手,都适合看一看哦~有好的建议也欢迎大家在评论留言,若是看完有所收获,也希望大家能多多点赞支持呀!一起加油学习~

问题内容

我正在使用 grpc protobuf 消息定义并在 go 中实现它们。

我的最终目标是让我的 rpc 检索用户的一些 json 并返回 profile 消息,其中包含可选的嵌套消息,用于解组 json 的子集。

使用此 rpc:

rpc getuser (getuserrequest) returns (profile) {
    option (google.api.http) = {
      get: "/user/{id=*}"
    };
  }

并假设以下 json:

{
  "profile": {
     "foo": {
        "name": "tim"
        "age": 22
      },
     "bar": {
       "level": 5
     }
  }
}

我想返回一个仅包含“foo”、“bar”或两者的 profile 消息,作为基于 grpc 请求的传入运行时 scope 参数的嵌套消息(当前,scope 将是包含消息的字符串列表)用于将 json 子集到相应消息中的名称,例如 ["foo","bar"])。

给定这些消息定义:

message profile {
  //both foo & bar are optional by default
  foo foo = 1 [json_name="foo"];
  bar bar = 2 [json_name="bar"];
}

message foo {
  string name = 1 [json_name="name"];
  int32 age = 2 [json_name="age"];
}

message bar {
  string level = 1 [json_name="level"];
}

然后,如果 scope["foo"],我希望 rpc 返回:

profile{
  foo: // foo message unmarshalled from json
}

或者如果 "scope"["foo","bar"] 那么:

profile{
  foo: 
  bar:
}

问题似乎可以归结为“鸭子输入”消息类型。

尝试 1

我通过执行以下操作接近找到使用 protoreflectprotoregistry 的解决方案:

import(
    "google.golang.org/protobuf/reflect/protoregistry"
    "google.golang.org/protobuf/reflect/protoreflect"
)

var scope protoreflect.fullname = "foo"
var types = new(protoregistry.types)
var message, errs = types.findmessagebyname(scope)
var almost_foo = message.new()

// using `myjson` object without top level "profile" key to make testing more simple at the moment
var myjson = `{ "foo": { .. }, "bar", { ... } }`
err = json.unmarshal([]byte(myjson), almost_foo)

但是当我尝试使用 almost_foo 创建配置文件消息时:

var profile = &pb.profile{almost_foo}

我收到错误:无法在字段值中使用almost_foo(类型protoreflect.message)作为类型*package_name.foo

尝试 2

使用

import(
  "github.com/jhump/protoreflect/desc"
  "github.com/jhump/protoreflect/dynamic"
)

我尝试再次动态创建消息:

var fd, errs = desc.LoadFileDescriptor("github.com/package/path/..")
var message_desc = fd.FindMessage("Foo")
var almost_foo = dynamic.NewMessage(message_desc)

并且出现类似的错误: 不能在字段值中使用almost_foo(类型*dynamic.message)作为类型*package_name.foo

两次尝试几乎都创建了一条消息,但类型系统仍然不允许实际使用任何一个。

感谢任何帮助。


解决方案


我设法通过先将 json 缩减为我想要的内容,然后将其通过 unmarshal 来解决这个问题。

我创建了一个顶级消息,它将 profile 作为字段:

message getuserresponse {
  profile profile = 1;
}

并重新定义响应:

rpc getuser (getuserrequest) returns (getuserresponse)

为了构建允许/范围内的 json,我使用:

"github.com/tidwall/gjson"
"github.com/tidwall/sjson"

我将范围路径(点分隔,例如 ["profile.foo"])指定的 json 复制到最初为空的输出 response_json 字符串,并仅构建允许返回的 json。

var response_json string

var scopes = []string{"profile.foo"}

for _, scope := range scopes {
    // copy allowed json subset in raw form
    value := gjson.get(myjson, scope + "|@ugly")

    // if scope didn't copy a value, skip
    if value.string() == "" {
        continue
    } else {
        // write value to output json using setraw since value can be an object
        response_json, _ = sjson.setraw(response_json, scope, value.raw)
    }
}

response_json 看起来像:

{
  "profile": {
     "foo": {
        "name": "tim"
        "age": 22
      }
  }
}

然后解组:

response = &pb.VerifyUserResponse{}
err = json.Unmarshal([]byte(response_json), response)

到这里,我们也就讲完了《如何在 Go 中运行时创建“鸭子类型”grpc protobuf 消息?》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>