问题描述
我正在使用 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 或请求对象可能有权访问这些信息,但上下文似乎只提供了一个到元数据的接口,这是自定义的。
gRPC C++ examples 中没有任何迹象表明存在此类 API,gRPC source code 中的任何相关源/头文件也没有。在教程、博客文章、视频和文档方面,我已经用尽了我的选择 - 我在 grpc-io 论坛上询问了 a similar question,但没有人接受。希望 SO 工作人员在这里有一些见解!
我还应该注意,我尝试将各种环境变量作为标志传递给正在运行的进程,以查看是否可以获得有关 HTTP 标头的详细信息,但即使启用了 these flags(与 HTTP 相关的标头) ,我看不到基本的 HTTP 标头。
解决方法
首先,gRPC 库绝对使用 HTTP/2。 The protocol is explicitly defined in terms of HTTP/2。
gRPC 库不会直接向应用程序公开原始 HTTP 标头。但是,它们确实具有跟踪日志记录选项,可以记录各种用于调试目的的信息,包括标头。可以通过设置环境变量 GRPC_TRACE
来启用跟踪器。还应设置环境变量 GRPC_VERBOSITY=DEBUG
以确保输出所有日志。可以在 this document describing how the library uses envinronment variables.
在 C++ 库中,http
跟踪器应记录原始标头。 grpc-js 库具有不同的内部结构和不同的跟踪器定义,因此您应该为该库使用 call_stream
跟踪器。这些也会记录其他请求信息,但挑选标头应该很容易。