diff --git a/lib/cgi/core.rb b/lib/cgi/core.rb index 69373cb..a586f72 100644 --- a/lib/cgi/core.rb +++ b/lib/cgi/core.rb @@ -848,6 +848,7 @@ def initialize_query() boundary = $1.dup @multipart = true @params = read_multipart(boundary, Integer(content_length)) + append_query_string(@params) else @multipart = false @params = CGI.parse( @@ -860,10 +861,21 @@ def initialize_query() end when "POST" stdinput.binmode if defined? stdinput.binmode - if content_length.nil? - stdinput.read or '' + body = if content_length.nil? + stdinput.read || '' else - stdinput.read(Integer(content_length)) or '' + stdinput.read(Integer(content_length)) || '' + end + # The query string is independent of the method (cgi#57). + # Body values stay first, so cgi[key] is unchanged when + # the same name is in both places. + query = env_table['QUERY_STRING'] || "" + if query.empty? + body + elsif body.empty? + query + else + "#{body}&#{query}" end else read_from_cmdline @@ -888,6 +900,16 @@ def initialize_query() end private :initialize_query + def append_query_string(params) + query = env_table['QUERY_STRING'] || "" + return params if query.empty? + CGI.parse(query).each do |key, values| + (params[key] ||= []).concat(values) + end + params + end + private :append_query_string + # Returns whether the form contained multipart/form-data def multipart? @multipart diff --git a/test/cgi/test_cgi_core.rb b/test/cgi/test_cgi_core.rb index b805c31..f19ee2c 100644 --- a/test/cgi/test_cgi_core.rb +++ b/test/cgi/test_cgi_core.rb @@ -92,6 +92,23 @@ def test_cgi_core_params_POST $stdin = STDIN end + def test_cgi_core_params_POST_reads_the_query_string + body = 'body=1' + update_env( + 'REQUEST_METHOD' => 'POST', + 'CONTENT_LENGTH' => body.bytesize.to_s, + 'QUERY_STRING' => 'q=2&body=from-query', + ) + $stdin = StringIO.new(body) + cgi = CGI.new + assert_equal('1', cgi['body']) + assert_equal(['1', 'from-query'], cgi.params['body']) + assert_equal('2', cgi['q']) + assert_equal(['2'], cgi.params['q']) + ensure + $stdin = STDIN + end + def test_cgi_core_params_POST_without_content_length update_env( 'REQUEST_METHOD' => 'POST',