Skip to content
Newer
Older
100644 282 lines (238 sloc) 8.79 KB
7ed819a @chneukirchen Add Rack::Response and Rack::Utils
chneukirchen authored Feb 16, 2007
1 require 'rack/utils'
2
5f13e3d @chneukirchen Add Rack::Request
chneukirchen authored Feb 16, 2007
3 module Rack
376fa1e @chneukirchen Add RDocs
chneukirchen authored Mar 1, 2007
4 # Rack::Request provides a convenient interface to a Rack
5 # environment. It is stateless, the environment +env+ passed to the
6 # constructor will be directly modified.
7 #
8 # req = Rack::Request.new(env)
9 # req.post?
10 # req.params["data"]
eefbed8 @mtodd Added Rack::Request initialization memoization to reduce repetitive i…
mtodd authored Dec 24, 2008
11 #
12 # The environment hash passed will store a reference to the Request object
13 # instantiated so that it will only instantiate if an instance of the Request
14 # object doesn't already exist.
230d62c @chneukirchen Fix trailing whitespace. Sigh.
chneukirchen authored May 16, 2007
15
5f13e3d @chneukirchen Add Rack::Request
chneukirchen authored Feb 16, 2007
16 class Request
376fa1e @chneukirchen Add RDocs
chneukirchen authored Mar 1, 2007
17 # The environment of the request.
05ab0f9 @chneukirchen More convenience for Rack::Request
chneukirchen authored Feb 18, 2007
18 attr_reader :env
230d62c @chneukirchen Fix trailing whitespace. Sigh.
chneukirchen authored May 16, 2007
19
5f13e3d @chneukirchen Add Rack::Request
chneukirchen authored Feb 16, 2007
20 def initialize(env)
21 @env = env
22 end
23
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored Aug 5, 2009
24 def body; @env["rack.input"] end
25 def scheme; @env["rack.url_scheme"] end
26 def script_name; @env["SCRIPT_NAME"].to_s end
27 def path_info; @env["PATH_INFO"].to_s end
28 def request_method; @env["REQUEST_METHOD"] end
29 def query_string; @env["QUERY_STRING"].to_s end
30 def content_length; @env['CONTENT_LENGTH'] end
31 def content_type; @env['CONTENT_TYPE'] end
32 def session; @env['rack.session'] ||= {} end
33 def session_options; @env['rack.session.options'] ||= {} end
df22480 @josh rack.logger specification
josh authored Dec 11, 2009
34 def logger; @env['rack.logger'] end
fe40ec2 @chneukirchen Fix that Request assumes form-data even when Content-Type says otherwise
chneukirchen authored Mar 15, 2008
35
36 # The media type (type/subtype) portion of the CONTENT_TYPE header
37 # without any media type parameters. e.g., when CONTENT_TYPE is
38 # "text/plain;charset=utf-8", the media-type is "text/plain".
39 #
40 # For more information on the use of media types in HTTP, see:
41 # http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7
42 def media_type
939fa7d @tj Refactored Rack::Request#media_type
tj authored Mar 18, 2009
43 content_type && content_type.split(/\s*[;,]\s*/, 2).first.downcase
fe40ec2 @chneukirchen Fix that Request assumes form-data even when Content-Type says otherwise
chneukirchen authored Mar 15, 2008
44 end
45
46 # The media type parameters provided in CONTENT_TYPE as a Hash, or
47 # an empty Hash if no CONTENT_TYPE or media-type parameters were
48 # provided. e.g., when the CONTENT_TYPE is "text/plain;charset=utf-8",
49 # this method responds with the following Hash:
50 # { 'charset' => 'utf-8' }
51 def media_type_params
52 return {} if content_type.nil?
d3893c2 @raggi 186 bro :'(
raggi authored Oct 3, 2010
53 Hash[*content_type.split(/\s*[;,]\s*/)[1..-1].
fe40ec2 @chneukirchen Fix that Request assumes form-data even when Content-Type says otherwise
chneukirchen authored Mar 15, 2008
54 collect { |s| s.split('=', 2) }.
d3893c2 @raggi 186 bro :'(
raggi authored Oct 3, 2010
55 map { |k,v| [k.downcase, v] }.flatten]
fe40ec2 @chneukirchen Fix that Request assumes form-data even when Content-Type says otherwise
chneukirchen authored Mar 15, 2008
56 end
57
58 # The character set of the request body if a "charset" media type
59 # parameter was given, or nil if no "charset" was specified. Note
60 # that, per RFC2616, text/* media types that specify no explicit
61 # charset are to be considered ISO-8859-1.
62 def content_charset
63 media_type_params['charset']
64 end
a18fc32 @chneukirchen Rename Request#method to #request_method to not confuse stdlibs
chneukirchen authored Feb 18, 2007
65
fb32ff7 @josh Request#host knows about forwared host [#77 state:resolved]
josh authored Dec 20, 2009
66 def host_with_port
67 if forwarded = @env["HTTP_X_FORWARDED_HOST"]
68 forwarded.split(/,\s?/).last
69 else
70 @env['HTTP_HOST'] || "#{@env['SERVER_NAME'] || @env['SERVER_ADDR']}:#{@env['SERVER_PORT']}"
71 end
72 end
4bfe1d7 @brasten Modified Rack::Request#port to respect HTTP_X_FORWARDED_HOST port inf…
brasten authored Jun 29, 2010
73
74 def port
75 host, port = host_with_port.split(/:/)
76
77 (port || @env["SERVER_PORT"]).to_i
78 end
fb32ff7 @josh Request#host knows about forwared host [#77 state:resolved]
josh authored Dec 21, 2009
79
c95b751 @chneukirchen Remove the port number of HTTP_HOST and SERVER_NAME
chneukirchen authored Feb 28, 2007
80 def host
81 # Remove port number.
fb32ff7 @josh Request#host knows about forwared host [#77 state:resolved]
josh authored Dec 21, 2009
82 host_with_port.to_s.gsub(/:\d+\z/, '')
c95b751 @chneukirchen Remove the port number of HTTP_HOST and SERVER_NAME
chneukirchen authored Feb 28, 2007
83 end
84
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored Aug 5, 2009
85 def script_name=(s); @env["SCRIPT_NAME"] = s.to_s end
86 def path_info=(s); @env["PATH_INFO"] = s.to_s end
a18fc32 @chneukirchen Rename Request#method to #request_method to not confuse stdlibs
chneukirchen authored Feb 18, 2007
87
320d800 @manveru Add Request.trace? and Request.options?
manveru authored Jun 11, 2010
88 def delete?; request_method == "DELETE" end
89 def get?; request_method == "GET" end
90 def head?; request_method == "HEAD" end
91 def options?; request_method == "OPTIONS" end
92 def post?; request_method == "POST" end
93 def put?; request_method == "PUT" end
94 def trace?; request_method == "TRACE" end
fe40ec2 @chneukirchen Fix that Request assumes form-data even when Content-Type says otherwise
chneukirchen authored Mar 15, 2008
95
96 # The set of form-data media-types. Requests that do not indicate
97 # one of the media types presents in this list will not be eligible
98 # for form-data / param parsing.
99 FORM_DATA_MEDIA_TYPES = [
100 'application/x-www-form-urlencoded',
101 'multipart/form-data'
102 ]
103
6674f36 better multipart handling
eTM authored Apr 11, 2009
104 # The set of media-types. Requests that do not indicate
105 # one of the media types presents in this list will not be eligible
106 # for param parsing like soap attachments or generic multiparts
107 PARSEABLE_DATA_MEDIA_TYPES = [
108 'multipart/related',
109 'multipart/mixed'
df22480 @josh rack.logger specification
josh authored Dec 11, 2009
110 ]
6674f36 better multipart handling
eTM authored Apr 11, 2009
111
fe40ec2 @chneukirchen Fix that Request assumes form-data even when Content-Type says otherwise
chneukirchen authored Mar 15, 2008
112 # Determine whether the request body contains form-data by checking
aea2d60 @rtomayko Use Content-Type to determine POST params parsing [#20]
rtomayko authored Jan 15, 2009
113 # the request Content-Type for one of the media-types:
114 # "application/x-www-form-urlencoded" or "multipart/form-data". The
fe40ec2 @chneukirchen Fix that Request assumes form-data even when Content-Type says otherwise
chneukirchen authored Mar 15, 2008
115 # list of form-data media types can be modified through the
116 # +FORM_DATA_MEDIA_TYPES+ array.
aea2d60 @rtomayko Use Content-Type to determine POST params parsing [#20]
rtomayko authored Jan 15, 2009
117 #
118 # A request body is also assumed to contain form-data when no
119 # Content-Type header is provided and the request_method is POST.
fe40ec2 @chneukirchen Fix that Request assumes form-data even when Content-Type says otherwise
chneukirchen authored Mar 15, 2008
120 def form_data?
aea2d60 @rtomayko Use Content-Type to determine POST params parsing [#20]
rtomayko authored Jan 15, 2009
121 type = media_type
122 meth = env["rack.methodoverride.original_method"] || env['REQUEST_METHOD']
123 (meth == 'POST' && type.nil?) || FORM_DATA_MEDIA_TYPES.include?(type)
fe40ec2 @chneukirchen Fix that Request assumes form-data even when Content-Type says otherwise
chneukirchen authored Mar 15, 2008
124 end
5f13e3d @chneukirchen Add Rack::Request
chneukirchen authored Feb 16, 2007
125
6674f36 better multipart handling
eTM authored Apr 11, 2009
126 # Determine whether the request body contains data by checking
127 # the request media_type against registered parse-data media-types
128 def parseable_data?
129 PARSEABLE_DATA_MEDIA_TYPES.include?(media_type)
130 end
131
376fa1e @chneukirchen Add RDocs
chneukirchen authored Mar 1, 2007
132 # Returns the data recieved in the query string.
5f13e3d @chneukirchen Add Rack::Request
chneukirchen authored Feb 16, 2007
133 def GET
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored Aug 5, 2009
134 if @env["rack.request.query_string"] == query_string
135 @env["rack.request.query_hash"]
6c80c6c @chneukirchen Cache the parsed things in Rack::Request
chneukirchen authored Feb 19, 2007
136 else
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored Aug 5, 2009
137 @env["rack.request.query_string"] = query_string
d8ccbf3 @josh Extract parse_query and parse_multipart in Request so subclasses
josh authored Dec 20, 2009
138 @env["rack.request.query_hash"] = parse_query(query_string)
6c80c6c @chneukirchen Cache the parsed things in Rack::Request
chneukirchen authored Feb 19, 2007
139 end
5f13e3d @chneukirchen Add Rack::Request
chneukirchen authored Feb 16, 2007
140 end
141
376fa1e @chneukirchen Add RDocs
chneukirchen authored Mar 1, 2007
142 # Returns the data recieved in the request body.
143 #
144 # This method support both application/x-www-form-urlencoded and
145 # multipart/form-data.
5f13e3d @chneukirchen Add Rack::Request
chneukirchen authored Feb 16, 2007
146 def POST
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored Aug 5, 2009
147 if @env["rack.input"].nil?
01c1770 @jeremy Rack::Request#POST raises if rack.input is missing instead of returni…
jeremy authored May 14, 2009
148 raise "Missing rack.input"
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored Aug 5, 2009
149 elsif @env["rack.request.form_input"].eql? @env["rack.input"]
150 @env["rack.request.form_hash"]
6674f36 better multipart handling
eTM authored Apr 11, 2009
151 elsif form_data? || parseable_data?
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored Aug 5, 2009
152 @env["rack.request.form_input"] = @env["rack.input"]
d8ccbf3 @josh Extract parse_query and parse_multipart in Request so subclasses
josh authored Dec 21, 2009
153 unless @env["rack.request.form_hash"] = parse_multipart(env)
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored Aug 5, 2009
154 form_vars = @env["rack.input"].read
0f081dd @josh Clean up Safari's ajax POST body
josh authored Jan 18, 2009
155
156 # Fix for Safari Ajax postings that always append \0
157 form_vars.sub!(/\0\z/, '')
158
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored Aug 5, 2009
159 @env["rack.request.form_vars"] = form_vars
d8ccbf3 @josh Extract parse_query and parse_multipart in Request so subclasses
josh authored Dec 21, 2009
160 @env["rack.request.form_hash"] = parse_query(form_vars)
3513f4f @josh Add tests for multipart uploads. Also ensure multipart parser tries t…
josh authored Jan 13, 2009
161
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored Aug 5, 2009
162 @env["rack.input"].rewind
4fe5360 @chneukirchen Make Rack::Request read multipart form data
chneukirchen authored Feb 28, 2007
163 end
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored Aug 5, 2009
164 @env["rack.request.form_hash"]
fe40ec2 @chneukirchen Fix that Request assumes form-data even when Content-Type says otherwise
chneukirchen authored Mar 15, 2008
165 else
166 {}
6c80c6c @chneukirchen Cache the parsed things in Rack::Request
chneukirchen authored Feb 19, 2007
167 end
5f13e3d @chneukirchen Add Rack::Request
chneukirchen authored Feb 16, 2007
168 end
169
376fa1e @chneukirchen Add RDocs
chneukirchen authored Mar 1, 2007
170 # The union of GET and POST data.
5f13e3d @chneukirchen Add Rack::Request
chneukirchen authored Feb 16, 2007
171 def params
aea2d60 @rtomayko Use Content-Type to determine POST params parsing [#20]
rtomayko authored Jan 15, 2009
172 self.GET.update(self.POST)
67a7507 @chneukirchen handle EOFError exception in Request#params
chneukirchen authored Apr 10, 2008
173 rescue EOFError => e
174 self.GET
5f13e3d @chneukirchen Add Rack::Request
chneukirchen authored Feb 16, 2007
175 end
176
de7411c @manveru add some features to Request and the corresponding tests for them
manveru authored May 15, 2007
177 # shortcut for request.params[key]
178 def [](key)
179 params[key.to_s]
180 end
181
182 # shortcut for request.params[key] = value
183 def []=(key, value)
184 params[key.to_s] = value
185 end
186
187 # like Hash#values_at
188 def values_at(*keys)
189 keys.map{|key| params[key] }
190 end
191
aa7ce77 @ghazel do not default referer to '/'
ghazel authored Sep 17, 2010
192 # the referer of the client
de7411c @manveru add some features to Request and the corresponding tests for them
manveru authored May 15, 2007
193 def referer
aa7ce77 @ghazel do not default referer to '/'
ghazel authored Sep 17, 2010
194 @env['HTTP_REFERER']
de7411c @manveru add some features to Request and the corresponding tests for them
manveru authored May 15, 2007
195 end
196 alias referrer referer
197
e2a1a64 @josh Request#user_agent
josh authored Dec 20, 2009
198 def user_agent
199 @env['HTTP_USER_AGENT']
200 end
de7411c @manveru add some features to Request and the corresponding tests for them
manveru authored May 15, 2007
201
5f13e3d @chneukirchen Add Rack::Request
chneukirchen authored Feb 16, 2007
202 def cookies
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored Aug 5, 2009
203 return {} unless @env["HTTP_COOKIE"]
b68c2d5 @chneukirchen Return empty hash on lack of cookies
chneukirchen authored Feb 19, 2007
204
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored Aug 5, 2009
205 if @env["rack.request.cookie_string"] == @env["HTTP_COOKIE"]
206 @env["rack.request.cookie_hash"]
6c80c6c @chneukirchen Cache the parsed things in Rack::Request
chneukirchen authored Feb 19, 2007
207 else
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored Aug 5, 2009
208 @env["rack.request.cookie_string"] = @env["HTTP_COOKIE"]
4a08f8a Conform to RFC 2109 regarding multiple values for same cookie
Aman Gupta authored Jan 21, 2008
209 # According to RFC 2109:
210 # If multiple cookies satisfy the criteria above, they are ordered in
211 # the Cookie header such that those with more specific Path attributes
212 # precede those with less specific. Ordering with respect to other
213 # attributes (e.g., Domain) is unspecified.
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored Aug 5, 2009
214 @env["rack.request.cookie_hash"] =
d3893c2 @raggi 186 bro :'(
raggi authored Oct 3, 2010
215 Hash[*Utils.parse_query(@env["rack.request.cookie_string"], ';,').map {|k,v|
e9d7699 @spastorino PERF: change inject({}) to Hash + map
spastorino authored Oct 3, 2010
216 [k, Array === v ? v.first : v]
d3893c2 @raggi 186 bro :'(
raggi authored Oct 3, 2010
217 }.flatten]
6c80c6c @chneukirchen Cache the parsed things in Rack::Request
chneukirchen authored Feb 19, 2007
218 end
5f13e3d @chneukirchen Add Rack::Request
chneukirchen authored Feb 16, 2007
219 end
220
221 def xhr?
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored Aug 5, 2009
222 @env["HTTP_X_REQUESTED_WITH"] == "XMLHttpRequest"
5f13e3d @chneukirchen Add Rack::Request
chneukirchen authored Feb 16, 2007
223 end
fd51d36 @chneukirchen Add Request#url
chneukirchen authored Feb 21, 2007
224
376fa1e @chneukirchen Add RDocs
chneukirchen authored Mar 1, 2007
225 # Tries to return a remake of the original request URL as a string.
fd51d36 @chneukirchen Add Request#url
chneukirchen authored Feb 21, 2007
226 def url
227 url = scheme + "://"
228 url << host
229
230 if scheme == "https" && port != 443 ||
231 scheme == "http" && port != 80
232 url << ":#{port}"
233 end
234
234c062 @chneukirchen Add Request#fullpath
chneukirchen authored Mar 30, 2007
235 url << fullpath
fd51d36 @chneukirchen Add Request#url
chneukirchen authored Feb 21, 2007
236
237 url
238 end
df22480 @josh rack.logger specification
josh authored Dec 11, 2009
239
3a544a7 @tj Added Rack::Request#path
tj authored Mar 18, 2009
240 def path
241 script_name + path_info
242 end
df22480 @josh rack.logger specification
josh authored Dec 11, 2009
243
234c062 @chneukirchen Add Request#fullpath
chneukirchen authored Mar 30, 2007
244 def fullpath
3a544a7 @tj Added Rack::Request#path
tj authored Mar 18, 2009
245 query_string.empty? ? path : "#{path}?#{query_string}"
234c062 @chneukirchen Add Request#fullpath
chneukirchen authored Mar 30, 2007
246 end
0f2dab5 @qerub Added support for Accept-Encoding (via Request#accept_encoding and Ut…
qerub authored Jul 1, 2008
247
248 def accept_encoding
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored Aug 5, 2009
249 @env["HTTP_ACCEPT_ENCODING"].to_s.split(/,\s*/).map do |part|
0f2dab5 @qerub Added support for Accept-Encoding (via Request#accept_encoding and Ut…
qerub authored Jul 1, 2008
250 m = /^([^\s,]+?)(?:;\s*q=(\d+(?:\.\d+)?))?$/.match(part) # From WEBrick
251
252 if m
253 [m[1], (m[2] || 1.0).to_f]
254 else
255 raise "Invalid value for Accept-Encoding: #{part.inspect}"
256 end
257 end
258 end
a48eb51 @manveru Add Request#ip and corresponding spec
manveru authored Aug 30, 2008
259
260 def ip
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored Aug 5, 2009
261 if addr = @env['HTTP_X_FORWARDED_FOR']
fa324e3 @manveru Don't use 'unknown' in HTTP_X_FORWARDED_FOR
manveru authored Jun 9, 2010
262 (addr.split(',').grep(/\d\./).first || @env['REMOTE_ADDR']).to_s.strip
a48eb51 @manveru Add Request#ip and corresponding spec
manveru authored Aug 30, 2008
263 else
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored Aug 5, 2009
264 @env['REMOTE_ADDR']
a48eb51 @manveru Add Request#ip and corresponding spec
manveru authored Aug 30, 2008
265 end
266 end
d8ccbf3 @josh Extract parse_query and parse_multipart in Request so subclasses
josh authored Dec 21, 2009
267
4defbe5 @josevalim Improves performance by lazy loading the session.
josevalim authored Sep 19, 2010
268 def ssl?
269 @env['HTTPS'] == 'on' || @env['HTTP_X_FORWARDED_PROTO'] == 'https'
270 end
271
d8ccbf3 @josh Extract parse_query and parse_multipart in Request so subclasses
josh authored Dec 21, 2009
272 protected
273 def parse_query(qs)
274 Utils.parse_nested_query(qs)
275 end
276
277 def parse_multipart(env)
278 Utils::Multipart.parse_multipart(env)
279 end
5f13e3d @chneukirchen Add Rack::Request
chneukirchen authored Feb 16, 2007
280 end
281 end
Something went wrong with that request. Please try again.