Skip to content

Instantly share code, notes, and snippets.

@FaviusTy
Last active December 11, 2015 15:58
Show Gist options
  • Save FaviusTy/4624107 to your computer and use it in GitHub Desktop.
Save FaviusTy/4624107 to your computer and use it in GitHub Desktop.
msgpackのrequestをunpackしてparamsに変換するRackミドルウェア。 use Rack::MsgpackParamsParser でどうぞ
# encoding: utf-8
require "rack"
require "msgpack"
module Rack
class MsgpackParamsParser
# Constants
#
CONTENT_TYPE = 'CONTENT_TYPE'.freeze
POST_BODY = 'rack.input'.freeze
FORM_INPUT = 'rack.request.form_input'.freeze
FORM_HASH = 'rack.request.form_hash'.freeze
# Supported Content-Types
#
APPLICATION_MSGPACK = "application/x-msgpack".freeze
def initialize(app)
@app = app
end
def call(env)
case env[CONTENT_TYPE]
when APPLICATION_MSGPACK
input_body = env[POST_BODY].read
if input_body.length > 0
unpacked_body = MessagePack.unpack(input_body)
env.update(FORM_HASH => unpacked_body, FORM_INPUT => env[POST_BODY])
end
end
@app.call(env)
end
end
end
if __FILE__ == $0
require 'sinatra/base'
require 'test/unit'
require 'rack/test'
class TestServer < Sinatra::Base
use Rack::MsgpackParamsParser
post '/test' do
params[:message]
end
end
class RackTest < Test::Unit::TestCase
include Rack::Test::Methods
def app
TestServer
end
def test_call
data = {message: "test_message"}
post '/test', data.to_msgpack, 'CONTENT_TYPE' => 'application/x-msgpack'
p last_response.body
end
end
end
@FaviusTy
Copy link
Author

https://github.com/rack/rack-contrib のRack::PostBodyContentTypeParser の模倣とも言う

@FaviusTy
Copy link
Author

テストコードを追加してみた

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment