Skip to content

Instantly share code, notes, and snippets.

@TwP
Created May 19, 2011 16:29
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save TwP/981176 to your computer and use it in GitHub Desktop.
Save TwP/981176 to your computer and use it in GitHub Desktop.
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
Copy link

tilo 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