Class: Rack::PostBodyContentTypeParser
- Inherits:
-
Object
- Object
- Rack::PostBodyContentTypeParser
- Defined in:
- lib/rack/contrib/post_body_content_type_parser.rb
Overview
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
Constant Summary collapse
- CONTENT_TYPE =
Constants
'CONTENT_TYPE'.freeze
- POST_BODY =
'rack.input'.freeze
- FORM_INPUT =
'rack.request.form_input'.freeze
- FORM_HASH =
'rack.request.form_hash'.freeze
- APPLICATION_JSON =
Supported Content-Types
'application/json'.freeze
Instance Method Summary collapse
- #bad_request(body = 'Bad Request') ⇒ Object
- #call(env) ⇒ Object
-
#initialize(app, &block) ⇒ PostBodyContentTypeParser
constructor
A new instance of PostBodyContentTypeParser.
Constructor Details
#initialize(app, &block) ⇒ PostBodyContentTypeParser
Returns a new instance of PostBodyContentTypeParser.
70 71 72 73 74 |
# File 'lib/rack/contrib/post_body_content_type_parser.rb', line 70 def initialize(app, &block) warn "[DEPRECATION] `PostBodyContentTypeParser` is deprecated. Use `JSONBodyParser` as a drop-in replacement." @app = app @block = block || Proc.new { |body| JSON.parse(body, :create_additions => false) } end |
Instance Method Details
#bad_request(body = 'Bad Request') ⇒ Object
86 87 88 |
# File 'lib/rack/contrib/post_body_content_type_parser.rb', line 86 def bad_request(body = 'Bad Request') [ 400, { 'content-type' => 'text/plain', 'content-length' => body.bytesize.to_s }, [body] ] end |
#call(env) ⇒ Object
76 77 78 79 80 81 82 83 84 |
# File 'lib/rack/contrib/post_body_content_type_parser.rb', line 76 def call(env) if Rack::Request.new(env).media_type == APPLICATION_JSON && (body = env[POST_BODY].read).length != 0 env[POST_BODY].rewind if env[POST_BODY].respond_to?(:rewind) # somebody might try to read this stream env.update(FORM_HASH => @block.call(body), FORM_INPUT => env[POST_BODY]) end @app.call(env) rescue JSON::ParserError bad_request('failed to parse body as JSON') end |