Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A simple rack middleware that allows you to post JSON body data. We are using the YAJL json library for ruby. Feel free to substitute your own.
require 'yajl'
module Rack
# A Rack middleware for parsing POST/PUT body data when Content-Type is
# <tt>application/json</tt>.
#
class JsonPostBody
# Constants
#
POST_BODY = 'rack.input'.freeze
FORM_HASH = 'rack.request.form_hash'.freeze
FORM_INPUT = 'rack.request.form_input'.freeze
def initialize(app)
@app = app
end
def call(env)
if env['CONTENT_TYPE'] =~ %r{application/json}i
body = env[POST_BODY].read
# make sure we have a hash before parsing
if body =~ %r/^\s*\{/
env.update(FORM_HASH => Yajl::Parser.parse(body), FORM_INPUT => env[POST_BODY])
end
end
@app.call(env)
end
end
end
@tilo

This comment has been minimized.

Copy link

commented Sep 13, 2015

what if you want don't want to just parse, but to replace the post body entirely?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.