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

后端 未结 3 822
醉话见心
醉话见心 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 03:07

    Based on @matt's answer, but this really gives you the request headers in a hash as requested in the question:

    headers = Hash[*env.select {|k,v| k.start_with? 'HTTP_'}
      .collect {|k,v| [k.sub(/^HTTP_/, ''), v]}
      .collect {|k,v| [k.split('_').collect(&:capitalize).join('-'), v]}
      .sort
      .flatten]
    

    Depending on what key convention you prefer you might want to use something else instead of :capitalize.

提交回复
热议问题