Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Newer
Older
100644 250 lines (212 sloc) 8.247 kb
7ed819a @chneukirchen Add Rack::Response and Rack::Utils
chneukirchen authored
1 require 'rack/utils'
2
5f13e3d @chneukirchen Add Rack::Request
chneukirchen authored
3 module Rack
376fa1e @chneukirchen Add RDocs
chneukirchen authored
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
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
15
5f13e3d @chneukirchen Add Rack::Request
chneukirchen authored
16 class Request
376fa1e @chneukirchen Add RDocs
chneukirchen authored
17 # The environment of the request.
05ab0f9 @chneukirchen More convenience for Rack::Request
chneukirchen authored
18 attr_reader :env
230d62c @chneukirchen Fix trailing whitespace. Sigh.
chneukirchen authored
19
5f13e3d @chneukirchen Add Rack::Request
chneukirchen authored
20 def initialize(env)
21 @env = env
22 end
23
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored
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 port; @env["SERVER_PORT"].to_i end
29 def request_method; @env["REQUEST_METHOD"] end
30 def query_string; @env["QUERY_STRING"].to_s end
31 def content_length; @env['CONTENT_LENGTH'] end
32 def content_type; @env['CONTENT_TYPE'] end
33 def session; @env['rack.session'] ||= {} end
34 def session_options; @env['rack.session.options'] ||= {} end
df22480 @josh rack.logger specification
josh authored
35 def logger; @env['rack.logger'] end
fe40ec2 @chneukirchen Fix that Request assumes form-data even when Content-Type says otherwise
chneukirchen authored
36
37 # The media type (type/subtype) portion of the CONTENT_TYPE header
38 # without any media type parameters. e.g., when CONTENT_TYPE is
39 # "text/plain;charset=utf-8", the media-type is "text/plain".
40 #
41 # For more information on the use of media types in HTTP, see:
42 # http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7
43 def media_type
939fa7d @tj Refactored Rack::Request#media_type
tj authored
44 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
45 end
46
47 # The media type parameters provided in CONTENT_TYPE as a Hash, or
48 # an empty Hash if no CONTENT_TYPE or media-type parameters were
49 # provided. e.g., when the CONTENT_TYPE is "text/plain;charset=utf-8",
50 # this method responds with the following Hash:
51 # { 'charset' => 'utf-8' }
52 def media_type_params
53 return {} if content_type.nil?
54 content_type.split(/\s*[;,]\s*/)[1..-1].
55 collect { |s| s.split('=', 2) }.
56 inject({}) { |hash,(k,v)| hash[k.downcase] = v ; hash }
57 end
58
59 # The character set of the request body if a "charset" media type
60 # parameter was given, or nil if no "charset" was specified. Note
61 # that, per RFC2616, text/* media types that specify no explicit
62 # charset are to be considered ISO-8859-1.
63 def content_charset
64 media_type_params['charset']
65 end
a18fc32 @chneukirchen Rename Request#method to #request_method to not confuse stdlibs
chneukirchen authored
66
c95b751 @chneukirchen Remove the port number of HTTP_HOST and SERVER_NAME
chneukirchen authored
67 def host
68 # Remove port number.
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored
69 (@env["HTTP_HOST"] || @env["SERVER_NAME"]).to_s.gsub(/:\d+\z/, '')
c95b751 @chneukirchen Remove the port number of HTTP_HOST and SERVER_NAME
chneukirchen authored
70 end
71
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored
72 def script_name=(s); @env["SCRIPT_NAME"] = s.to_s end
73 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
74
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored
75 def get?; request_method == "GET" end
76 def post?; request_method == "POST" end
77 def put?; request_method == "PUT" end
78 def delete?; request_method == "DELETE" end
79 def head?; request_method == "HEAD" end
fe40ec2 @chneukirchen Fix that Request assumes form-data even when Content-Type says otherwise
chneukirchen authored
80
81 # The set of form-data media-types. Requests that do not indicate
82 # one of the media types presents in this list will not be eligible
83 # for form-data / param parsing.
84 FORM_DATA_MEDIA_TYPES = [
85 nil,
86 'application/x-www-form-urlencoded',
87 'multipart/form-data'
88 ]
89
6674f36 better multipart handling
eTM authored
90 # The set of media-types. Requests that do not indicate
91 # one of the media types presents in this list will not be eligible
92 # for param parsing like soap attachments or generic multiparts
93 PARSEABLE_DATA_MEDIA_TYPES = [
94 'multipart/related',
95 'multipart/mixed'
df22480 @josh rack.logger specification
josh authored
96 ]
6674f36 better multipart handling
eTM authored
97
fe40ec2 @chneukirchen Fix that Request assumes form-data even when Content-Type says otherwise
chneukirchen authored
98 # Determine whether the request body contains form-data by checking
99 # the request media_type against registered form-data media-types:
100 # "application/x-www-form-urlencoded" and "multipart/form-data". The
101 # list of form-data media types can be modified through the
102 # +FORM_DATA_MEDIA_TYPES+ array.
103 def form_data?
104 FORM_DATA_MEDIA_TYPES.include?(media_type)
105 end
5f13e3d @chneukirchen Add Rack::Request
chneukirchen authored
106
6674f36 better multipart handling
eTM authored
107 # Determine whether the request body contains data by checking
108 # the request media_type against registered parse-data media-types
109 def parseable_data?
110 PARSEABLE_DATA_MEDIA_TYPES.include?(media_type)
111 end
112
376fa1e @chneukirchen Add RDocs
chneukirchen authored
113 # Returns the data recieved in the query string.
5f13e3d @chneukirchen Add Rack::Request
chneukirchen authored
114 def GET
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored
115 if @env["rack.request.query_string"] == query_string
116 @env["rack.request.query_hash"]
6c80c6c @chneukirchen Cache the parsed things in Rack::Request
chneukirchen authored
117 else
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored
118 @env["rack.request.query_string"] = query_string
119 @env["rack.request.query_hash"] =
120 Utils.parse_nested_query(query_string)
6c80c6c @chneukirchen Cache the parsed things in Rack::Request
chneukirchen authored
121 end
5f13e3d @chneukirchen Add Rack::Request
chneukirchen authored
122 end
123
376fa1e @chneukirchen Add RDocs
chneukirchen authored
124 # Returns the data recieved in the request body.
125 #
126 # This method support both application/x-www-form-urlencoded and
127 # multipart/form-data.
5f13e3d @chneukirchen Add Rack::Request
chneukirchen authored
128 def POST
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored
129 if @env["rack.input"].nil?
01c1770 @jeremy Rack::Request#POST raises if rack.input is missing instead of returni…
jeremy authored
130 raise "Missing rack.input"
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored
131 elsif @env["rack.request.form_input"].eql? @env["rack.input"]
132 @env["rack.request.form_hash"]
6674f36 better multipart handling
eTM authored
133 elsif form_data? || parseable_data?
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored
134 @env["rack.request.form_input"] = @env["rack.input"]
135 unless @env["rack.request.form_hash"] =
136 Utils::Multipart.parse_multipart(env)
137 form_vars = @env["rack.input"].read
0f081dd @josh Clean up Safari's ajax POST body
josh authored
138
139 # Fix for Safari Ajax postings that always append \0
140 form_vars.sub!(/\0\z/, '')
141
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored
142 @env["rack.request.form_vars"] = form_vars
143 @env["rack.request.form_hash"] = Utils.parse_nested_query(form_vars)
3513f4f @josh Add tests for multipart uploads. Also ensure multipart parser tries t…
josh authored
144
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored
145 @env["rack.input"].rewind
4fe5360 @chneukirchen Make Rack::Request read multipart form data
chneukirchen authored
146 end
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored
147 @env["rack.request.form_hash"]
fe40ec2 @chneukirchen Fix that Request assumes form-data even when Content-Type says otherwise
chneukirchen authored
148 else
149 {}
6c80c6c @chneukirchen Cache the parsed things in Rack::Request
chneukirchen authored
150 end
5f13e3d @chneukirchen Add Rack::Request
chneukirchen authored
151 end
152
376fa1e @chneukirchen Add RDocs
chneukirchen authored
153 # The union of GET and POST data.
5f13e3d @chneukirchen Add Rack::Request
chneukirchen authored
154 def params
8d01dc0 Avoid slurping or parsing request body on PUT requests
Eric Wong authored
155 self.put? ? self.GET : self.GET.update(self.POST)
67a7507 @chneukirchen handle EOFError exception in Request#params
chneukirchen authored
156 rescue EOFError => e
157 self.GET
5f13e3d @chneukirchen Add Rack::Request
chneukirchen authored
158 end
159
de7411c @manveru add some features to Request and the corresponding tests for them
manveru authored
160 # shortcut for request.params[key]
161 def [](key)
162 params[key.to_s]
163 end
164
165 # shortcut for request.params[key] = value
166 def []=(key, value)
167 params[key.to_s] = value
168 end
169
170 # like Hash#values_at
171 def values_at(*keys)
172 keys.map{|key| params[key] }
173 end
174
175 # the referer of the client or '/'
176 def referer
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored
177 @env['HTTP_REFERER'] || '/'
de7411c @manveru add some features to Request and the corresponding tests for them
manveru authored
178 end
179 alias referrer referer
180
181
5f13e3d @chneukirchen Add Rack::Request
chneukirchen authored
182 def cookies
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored
183 return {} unless @env["HTTP_COOKIE"]
b68c2d5 @chneukirchen Return empty hash on lack of cookies
chneukirchen authored
184
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored
185 if @env["rack.request.cookie_string"] == @env["HTTP_COOKIE"]
186 @env["rack.request.cookie_hash"]
6c80c6c @chneukirchen Cache the parsed things in Rack::Request
chneukirchen authored
187 else
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored
188 @env["rack.request.cookie_string"] = @env["HTTP_COOKIE"]
4a08f8a Conform to RFC 2109 regarding multiple values for same cookie
Aman Gupta authored
189 # According to RFC 2109:
190 # If multiple cookies satisfy the criteria above, they are ordered in
191 # the Cookie header such that those with more specific Path attributes
192 # precede those with less specific. Ordering with respect to other
193 # attributes (e.g., Domain) is unspecified.
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored
194 @env["rack.request.cookie_hash"] =
195 Utils.parse_query(@env["rack.request.cookie_string"], ';,').inject({}) {|h,(k,v)|
acb8695 @chneukirchen Fix cookie parsing
chneukirchen authored
196 h[k] = Array === v ? v.first : v
4a08f8a Conform to RFC 2109 regarding multiple values for same cookie
Aman Gupta authored
197 h
198 }
6c80c6c @chneukirchen Cache the parsed things in Rack::Request
chneukirchen authored
199 end
5f13e3d @chneukirchen Add Rack::Request
chneukirchen authored
200 end
201
202 def xhr?
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored
203 @env["HTTP_X_REQUESTED_WITH"] == "XMLHttpRequest"
5f13e3d @chneukirchen Add Rack::Request
chneukirchen authored
204 end
fd51d36 @chneukirchen Add Request#url
chneukirchen authored
205
376fa1e @chneukirchen Add RDocs
chneukirchen authored
206 # Tries to return a remake of the original request URL as a string.
fd51d36 @chneukirchen Add Request#url
chneukirchen authored
207 def url
208 url = scheme + "://"
209 url << host
210
211 if scheme == "https" && port != 443 ||
212 scheme == "http" && port != 80
213 url << ":#{port}"
214 end
215
234c062 @chneukirchen Add Request#fullpath
chneukirchen authored
216 url << fullpath
fd51d36 @chneukirchen Add Request#url
chneukirchen authored
217
218 url
219 end
df22480 @josh rack.logger specification
josh authored
220
3a544a7 @tj Added Rack::Request#path
tj authored
221 def path
222 script_name + path_info
223 end
df22480 @josh rack.logger specification
josh authored
224
234c062 @chneukirchen Add Request#fullpath
chneukirchen authored
225 def fullpath
3a544a7 @tj Added Rack::Request#path
tj authored
226 query_string.empty? ? path : "#{path}?#{query_string}"
234c062 @chneukirchen Add Request#fullpath
chneukirchen authored
227 end
0f2dab5 @qerub Added support for Accept-Encoding (via Request#accept_encoding and Ut…
qerub authored
228
229 def accept_encoding
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored
230 @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
231 m = /^([^\s,]+?)(?:;\s*q=(\d+(?:\.\d+)?))?$/.match(part) # From WEBrick
232
233 if m
234 [m[1], (m[2] || 1.0).to_f]
235 else
236 raise "Invalid value for Accept-Encoding: #{part.inspect}"
237 end
238 end
239 end
a48eb51 @manveru Add Request#ip and corresponding spec
manveru authored
240
241 def ip
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored
242 if addr = @env['HTTP_X_FORWARDED_FOR']
a48eb51 @manveru Add Request#ip and corresponding spec
manveru authored
243 addr.split(',').last.strip
244 else
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored
245 @env['REMOTE_ADDR']
a48eb51 @manveru Add Request#ip and corresponding spec
manveru authored
246 end
247 end
5f13e3d @chneukirchen Add Rack::Request
chneukirchen authored
248 end
249 end
Something went wrong with that request. Please try again.