Skip to content
This repository
Browse code

Gracefully handle a JSON post body that evaluates to something other

than a hash.
  • Loading branch information...
commit daee38117ebac28b9a60afe0a75afda791cb211b 1 parent fc2e630
radsaq authored November 28, 2012
7  lib/goliath/rack/params.rb
@@ -31,7 +31,12 @@ def retrieve_params(env)
31 31
                   when URL_ENCODED then
32 32
                     ::Rack::Utils.parse_nested_query(body)
33 33
                   when JSON_ENCODED then
34  
-                    MultiJson.load(body)
  34
+                    json = MultiJson.load(body)
  35
+                    if json.is_a?(Hash)
  36
+                      json
  37
+                    else
  38
+                      {'_json' => json}
  39
+                    end
35 40
                   else
36 41
                     {}
37 42
                   end
10  spec/unit/rack/params_spec.rb
@@ -142,6 +142,16 @@
142 142
         ret['foo'].should == 'bar'
143 143
       end
144 144
 
  145
+      it "parses json that does not evaluate to a hash" do
  146
+        @env['CONTENT_TYPE'] = 'application/json'
  147
+        @env['rack.input'] = StringIO.new
  148
+        @env['rack.input'] << %|["foo","bar"]|
  149
+        @env['rack.input'].rewind
  150
+
  151
+        ret = @params.retrieve_params(@env)
  152
+        ret['_json'].should == ['foo', 'bar']
  153
+      end
  154
+
145 155
       it "handles empty input gracefully on JSON" do
146 156
         @env['CONTENT_TYPE'] = 'application/json'
147 157
         @env['rack.input'] = StringIO.new

0 notes on commit daee381

Please sign in to comment.
Something went wrong with that request. Please try again.