class Rack::PostBodyContentTypeParser

DEPRECATED: JSONBodyParser is a drop-in replacement that is faster and more configurable.

A Rack middleware for parsing POST/PUT body data when Content-Type is not one of the standard supported types, like application/json.

How to use the middleware

Example of simple config.ru file:

require 'rack'
require 'rack/contrib'

use ::Rack::PostBodyContentTypeParser

app = lambda do |env|
  request = Rack::Request.new(env)
  body = "Hello #{request.params['name']}"
  [200, {'Content-Type' => 'text/plain'}, [body]]
end

run app

Example with passing block argument:

use ::Rack::PostBodyContentTypeParser do |body|
  { 'params' => JSON.parse(body) }
end

Example with passing proc argument:

parser = ->(body) { { 'params' => JSON.parse(body) } }
use ::Rack::PostBodyContentTypeParser, &parser

Failed JSON parsing

Returns “400 Bad request” response if invalid JSON document was sent:

Raw HTTP response:

HTTP/1.1 400 Bad Request
Content-Type: text/plain
Content-Length: 28

failed to parse body as JSON

Constants

APPLICATION_JSON

Supported Content-Types

CONTENT_TYPE

Constants

FORM_HASH
FORM_INPUT
POST_BODY

Public Class Methods

new(app, &block) click to toggle source
   # File lib/rack/contrib/post_body_content_type_parser.rb
70 def initialize(app, &block)
71   warn "[DEPRECATION] `PostBodyContentTypeParser` is deprecated. Use `JSONBodyParser` as a drop-in replacement."
72   @app = app
73   @block = block || Proc.new { |body| JSON.parse(body, :create_additions => false) }
74 end

Public Instance Methods

bad_request(body = 'Bad Request') click to toggle source
   # File lib/rack/contrib/post_body_content_type_parser.rb
86 def bad_request(body = 'Bad Request')
87   [ 400, { 'Content-Type' => 'text/plain', 'Content-Length' => body.bytesize.to_s }, [body] ]
88 end
call(env) click to toggle source
   # File lib/rack/contrib/post_body_content_type_parser.rb
76 def call(env)
77   if Rack::Request.new(env).media_type == APPLICATION_JSON && (body = env[POST_BODY].read).length != 0
78     env[POST_BODY].rewind # somebody might try to read this stream
79     env.update(FORM_HASH => @block.call(body), FORM_INPUT => env[POST_BODY])
80   end
81   @app.call(env)
82 rescue JSON::ParserError
83   bad_request('failed to parse body as JSON')
84 end