Permalink
Browse files

Gracefully handle a JSON post body that evaluates to something other

than a hash.
  • Loading branch information...
1 parent fc2e630 commit daee38117ebac28b9a60afe0a75afda791cb211b @radsaq radsaq committed Nov 28, 2012
Showing with 16 additions and 1 deletion.
  1. +6 −1 lib/goliath/rack/params.rb
  2. +10 −0 spec/unit/rack/params_spec.rb
View
7 lib/goliath/rack/params.rb
@@ -31,7 +31,12 @@ def retrieve_params(env)
when URL_ENCODED then
::Rack::Utils.parse_nested_query(body)
when JSON_ENCODED then
- MultiJson.load(body)
+ json = MultiJson.load(body)
+ if json.is_a?(Hash)
+ json
+ else
+ {'_json' => json}
+ end
else
{}
end
View
10 spec/unit/rack/params_spec.rb
@@ -142,6 +142,16 @@
ret['foo'].should == 'bar'
end
+ it "parses json that does not evaluate to a hash" do
+ @env['CONTENT_TYPE'] = 'application/json'
+ @env['rack.input'] = StringIO.new
+ @env['rack.input'] << %|["foo","bar"]|
+ @env['rack.input'].rewind
+
+ ret = @params.retrieve_params(@env)
+ ret['_json'].should == ['foo', 'bar']
+ end
+
it "handles empty input gracefully on JSON" do
@env['CONTENT_TYPE'] = 'application/json'
@env['rack.input'] = StringIO.new

0 comments on commit daee381

Please sign in to comment.