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

后端 未结 3 812
醉话见心
醉话见心 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:59

    Like @Gavriel's answer, but using transform_keys (simpler):

    class Request
      def headers
        env.select { |k,v| k.start_with? 'HTTP_'}.
          transform_keys { |k| k.sub(/^HTTP_/, '').split('_').map(&:capitalize).join('-') }
      end
    end
    

    You can even make it so lookups still work even if the case is different:

      def headers
        env.
          select { |k,v| k.start_with? 'HTTP_'}.
          transform_keys { |k| k.sub(/^HTTP_/, '').split('_').map(&:capitalize).join('-') }.
          sort.to_h.
          tap do |headers|
            headers.define_singleton_method :[] do |k|
              super(k.split(/[-_]/).map(&:capitalize).join('-'))
            end
          end
      end
    

    So for example, even if headers normalizes the keys so it returns this:

    {
      Dnt: '1',
      Etag: 'W/"ec4454af5ae1bacff1afc5a06a2133f4"',
      'X-Xss-Protection': '1; mode=block',
    }
    

    you can still look up headers using the more natural/common names for these headers:

    headers['DNT']
    headers['ETag']
    headers['X-XSS-Protection']
    

提交回复
热议问题