Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

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