且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

访问cpp-netlib http服务器中的请求标头

更新时间:2023-10-23 15:08:28

您要引用的特征适用于客户端请求中的标头,用于cpp-netlib中的客户端实现.为了使从服务器中的请求获取标头与从客户端请求/响应对象获取请求相同,需要做一些工作(未完成).

The trait you're referring to applies to the headers in a client-side request, for the client-side implementation in cpp-netlib. There was some work being done (incomplete) to make getting a header from the request in the server be the same as for getting the request from client request/response objects.

服务器端标头是成对向量的原因是为了高效"的空间和时间.如果您可以支付在服务器处理程序上创建多图的费用,则可能应该这样做.通常以有效方式有效处理请求中的标头的模式是始终对要查找的标头进行线性扫描,并在输入标头时对其进行处理.类似于以下内容:

The reason the headers on the server side are a vector of pairs is for "efficiency" in terms of space and time. If you can pay the cost of creating a multimap on the server's handler, you should probably do that instead. The usual pattern for efficiently working through headers in a request in an efficient manner is to always do a linear scan of the headers you're looking for, and processing them as they come in. Something similar to this:

string content_type, content_length;
for (const auto& header : request.headers) {
  if (header.name == "Content-Type") content_type = header.value;
  if (header.name == "Content-Length") content_length = header.value;
  if (!content_type.empty() && !content_length.empty()) break;
}

如果您的应用程序需要这种级别的标头处理,则可以使用某种模式(也许是std::map<string, std::function<void(const std::string&)>>)将其概括化.

You may generalise this using some sort of pattern (a std::map<string, std::function<void(const std::string&)>> perhaps) if your application requires this level of header processing.

但是,一般来说,遍历向量列表应该不会花费太多时间.如果标题的数量很大(O(10,000)),那么您还有其他问题.这里的权衡是在内存局部性(向量具有连续元素,而映射通常具有在内存的不同部分中随机分配的元素的映射)与有效查找(对数时间仅在一定大小后才有意义)之间的权衡.

In general though, iterating through a list of vectors shouldn't take too much time. If the number of headers is large (O(10,000)) then you have other problems. The tradeoff here is between memory locality (a vector has contiguous elements as opposed to a map that has elements typically randomly allocated in different parts of memory) and efficient lookup (logarithmic time only really makes sense after a certain size).

我完全接受便利性受到影响的观点.也许不同的数据结构在这里会有所帮助(也许是boost::flat_map).但是,接口的改进将是使与客户端请求/响应一起使用的代码也与服务器请求/响应对象一起使用.

I completely accept the point that the convenience suffers a bit. Maybe a different data structure would be helpful here (a boost::flat_map perhaps). But an interface improvement would be to make the code that works with client request/response also work with server request/response objects.