【发布时间】:2021-06-05 07:08:08
【问题描述】:
我正在使用 gRPC 和 Protobuf,使用 C++ 服务器和 C++ 客户端,以及 grpc-js 客户端。 有没有办法从 gRPC 中的传输层读取所有 HTTP 请求/响应标头? 我正在寻找典型的客户端/服务器 HTTP 标头 - 特别是,我想要查看正在使用的协议版本(是否为 HTTP1.1/2)。我知道 gRPC 应该使用 HTTP2,但我试图在低级别确认它。
在一个典型的 gRPC 客户端实现中,你有这样的东西:
class PingPongClient {
public:
PingPongClient(std::shared_ptr<Channel> channel)
: stub_(PingPong::NewStub(channel)) {}
// Assembles the client's payload, sends it and presents the response back
// from the server.
PingPongReply PingPong(PingPongRequest request) {
// Container for the data we expect from the server.
PingPongReply reply;
// Context for the client. It could be used to convey extra information to
// the server and/or tweak certain RPC behaviors.
ClientContext context;
// The actual RPC.
Status status = stub_->Ping(&context, request, &reply);
// Act upon its status.
if (status.ok()) {
return reply;
} else {
auto errorMsg = status.error_code() + ": " + status.error_message();
std::cout << errorMsg << std::endl;
throw std::runtime_error(errorMsg);
}
}
private:
std::unique_ptr<PingPong::Stub> stub_;
};
在服务器端,类似:
class PingPongServiceImpl final : public PingPong::Service {
Status Ping(
ServerContext* context,
const PingPongRequest* request,
PingPongReply* reply
) override {
std::cout << "PingPong" << std::endl;
printContextClientMetadata(context->client_metadata());
if (request->input_msg() == "hello") {
reply->set_output_msg("world");
} else {
reply->set_output_msg("I can't pong unless you ping me 'hello'!");
}
std::cout << "Replying with " << reply->output_msg() << std::endl;
return Status::OK;
}
};
我认为无论是 ServerContext 还是请求对象都可以访问这些信息,但 context 似乎只提供了一个自定义元数据的接口。
gRPC C++ examples 中没有任何一个表明存在这样的 API,gRPC source code 中也没有任何相关的源/头文件。在教程、博客文章、视频和文档方面,我已经用尽了我的选择——我在 grpc-io 论坛上询问了a similar question,但没有得到任何人。希望 SO 工作人员在这里有一些见解!
我还应该注意,我尝试将各种环境变量作为标志传递给正在运行的进程,以查看是否可以获得有关 HTTP 标头的详细信息,但即使启用了these flags(与 HTTP 相关的),我看不到基本的 HTTP 标头。
【问题讨论】:
-
我相信您可以通过使用gRPCurl 访问服务器来枚举请求|响应标头和 HTTP 版本。我手头没有客户,但是 IIRC,使用详细输出。希望有帮助!
-
@DazWilkin 感谢您让我意识到这一点!不过,在这种情况下,我认为 grpcurl 充当客户端,因此通过忽略实际发出请求的 C++/JS 客户端来消除等式的一半。这是一个有用的工具
标签: c++ protocol-buffers grpc grpc-js