登录
首页 >  Golang >  Go问答

如何在 gRPC 协议中接受并验证该映射?

来源:stackoverflow

时间:2024-04-16 12:18:34 312浏览 收藏

在Golang实战开发的过程中,我们经常会遇到一些这样那样的问题,然后要卡好半天,等问题解决了才发现原来一些细节知识点还是没有掌握好。今天golang学习网就整理分享《如何在 gRPC 协议中接受并验证该映射?》,聊聊,希望可以帮助到正在努力赚钱的你。

问题内容

我正在向我的 grpc 应用程序发送以下 post 请求:

curl \
--request post \
--header 'content-type: application/json' \
--data-raw '{
 "mandatory-key1": "value1",
 "mandatory-key2": {
    "arbitrary-optional-key1": [
        "b",
        "c"
    ],
    "arbitrary-optional-key2": [
        "e"
    ]
  }
}' \
'http://localhost:11000/myendpoint'

mandatory-key-1 关联的值必须是非空字符串。 与 mandatory-key-2 关联的值必须是一个映射,其中所有键都是字符串,所有值都是字符串列表。

现在我必须在 grpc 原型文件中对该请求的数据结构进行建模。

我正在考虑做这样的事情:

message MyRequestData {
  // pairs represents that map that the user will send in to the MyEndpoint.
  map pairs = 1;
}

但是这个规范还不够通用。我需要知道如何正确编写这个规范。

问题 1:如何编写此规范,以便它接受值中的字符串以及字符串列表?

问题 2:如何进行验证以确保 pairs 具有密钥 mandatory-key1mandatory-key2 而没有其他密钥?

问题 3:我如何进行验证以确保:

  1. pairs 拥有密钥 mandatory-key1mandatory-key2 而没有其他密钥?
  2. pairs[mandatory-key1"] 的值是非空字符串吗?
  3. pairs["mandatory-key2"] 的值是

解决方案


protobuf 不提供(您需要的)验证。

当您使用协议生成的源时,您需要编写验证代码。

protobuf 不直接支持重复的映射值,但您可以:

message Request {
  string mandatory_key1 = 1;
  map mandatory_key2 = 2;
}
message Value {
  repeated string value = 1;
}

本篇关于《如何在 gRPC 协议中接受并验证该映射?》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

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