Rack::Request - 如何获取所有标头?
标题是非常不言自明的。有什么方法可以获取标头(Rack::Request.env[]
除外)?
The title is pretty self-explanatory. Is there any way to get the headers (except for Rack::Request.env[]
)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
HTTP 标头可在传递给您的应用的机架环境中使用:
因此,HTTP 标头以“HTTP_”为前缀并添加到哈希中。
这是一个提取并显示它们的小程序:
当我运行这个程序时,除了 Chrome 或 Firefox 显示的 HTTP 标头之外,还有一个“版本:HTPP/1.1”(即带有键“HTTP_VERSION”和值“ HTTP/1.1”被添加到 env 哈希中)。
The HTTP headers are available in the Rack environment passed to your app:
So the HTTP headers are prefixed with "HTTP_" and added to the hash.
Here's a little program that extracts and displays them:
When I run this, in addition to the HTTP headers as shown by Chrome or Firefox, there is a "VERSION: HTPP/1.1" (i.e. an entry with key "HTTP_VERSION" and value "HTTP/1.1" is being added to the env hash).
基于@matt的答案,但这确实为您提供了问题中所要求的哈希中的请求标头:
根据您喜欢的键约定,您可能想要使用其他内容而不是 :capitalize。
Based on @matt's answer, but this really gives you the request headers in a hash as requested in the question:
Depending on what key convention you prefer you might want to use something else instead of :capitalize.
就像@Gavriel的答案,但使用
transform_keys
(更简单):您甚至可以使其即使大小写不同,查找仍然有效:
例如,即使
headers
标准化键,因此它返回以下内容:您仍然可以使用这些标头的更自然/常见名称来查找标头:
Like @Gavriel's answer, but using
transform_keys
(simpler):You can even make it so lookups still work even if the case is different:
So for example, even if
headers
normalizes the keys so it returns this:you can still look up headers using the more natural/common names for these headers: