Skip to content

Commit 750cece

Browse files
authored
Documentation: add usage examples for PostBodyContentTypeParser middleware (#164)
1 parent a0f708b commit 750cece

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

lib/rack/contrib/post_body_content_type_parser.rb

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,48 @@ module Rack
1010
#
1111
# A Rack middleware for parsing POST/PUT body data when Content-Type is
1212
# not one of the standard supported types, like <tt>application/json</tt>.
13+
#
14+
# === How to use the middleware
15+
#
16+
# Example of simple +config.ru+ file:
17+
#
18+
# require 'rack'
19+
# require 'rack/contrib'
20+
#
21+
# use ::Rack::PostBodyContentTypeParser
22+
#
23+
# app = lambda do |env|
24+
# request = Rack::Request.new(env)
25+
# body = "Hello #{request.params['name']}"
26+
# [200, {'Content-Type' => 'text/plain'}, [body]]
27+
# end
28+
#
29+
# run app
30+
#
31+
# Example with passing block argument:
32+
#
33+
# use ::Rack::PostBodyContentTypeParser do |body|
34+
# { 'params' => JSON.parse(body) }
35+
# end
36+
#
37+
# Example with passing proc argument:
38+
#
39+
# parser = ->(body) { { 'params' => JSON.parse(body) } }
40+
# use ::Rack::PostBodyContentTypeParser, &parser
41+
#
42+
#
43+
# === Failed JSON parsing
44+
#
45+
# Returns "400 Bad request" response if invalid JSON document was sent:
46+
#
47+
# Raw HTTP response:
48+
#
49+
# HTTP/1.1 400 Bad Request
50+
# Content-Type: text/plain
51+
# Content-Length: 28
52+
#
53+
# failed to parse body as JSON
54+
#
1355
class PostBodyContentTypeParser
1456

1557
# Constants

0 commit comments

Comments
 (0)