Rack::Request - how do I get all headers?

后端 未结 3 819
醉话见心
醉话见心 2020-12-09 02:26

The title is pretty self-explanatory. Is there any way to get the headers (except for Rack::Request.env[])?

3条回答
  •  醉酒成梦
    2020-12-09 02:44

    The HTTP headers are available in the Rack environment passed to your app:

    HTTP_ Variables: Variables corresponding to the client-supplied HTTP request headers (i.e., variables whose names begin with HTTP_). The presence or absence of these variables should correspond with the presence or absence of the appropriate HTTP header in the request.

    So the HTTP headers are prefixed with "HTTP_" and added to the hash.

    Here's a little program that extracts and displays them:

    require 'rack'
    
    app = Proc.new do |env|
      headers = env.select {|k,v| k.start_with? 'HTTP_'}
        .collect {|key, val| [key.sub(/^HTTP_/, ''), val]}
        .collect {|key, val| "#{key}: #{val}
    "} .sort [200, {'Content-Type' => 'text/html'}, headers] end Rack::Server.start :app => app, :Port => 8080

    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).

提交回复
热议问题