From f2361997623e5141e6baa907d79f1212b36fbb8b Mon Sep 17 00:00:00 2001 From: MIKAMI Yoshiyuki Date: Mon, 3 Jul 2017 09:56:54 +0900 Subject: Add multi mapping support via header --- lib/rack/sendfile.rb | 8 ++++++-- test/spec_sendfile.rb | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 2 deletions(-) diff --git a/lib/rack/sendfile.rb b/lib/rack/sendfile.rb index bdb7cf2f..34c1a84e 100644 --- a/lib/rack/sendfile.rb +++ b/lib/rack/sendfile.rb @@ -150,8 +150,12 @@ module Rack if mapping = @mappings.find { |internal,_| internal =~ path } path.sub(*mapping) elsif mapping = env['HTTP_X_ACCEL_MAPPING'] - internal, external = mapping.split('=', 2).map(&:strip) - path.sub(/^#{internal}/i, external) + mapping.split(',').map(&:strip).each do |m| + internal, external = m.split('=', 2).map(&:strip) + new_path = path.sub(/^#{internal}/i, external) + return new_path unless path == new_path + end + path end end end diff --git a/test/spec_sendfile.rb b/test/spec_sendfile.rb index 18689857..1eb9413c 100644 --- a/test/spec_sendfile.rb +++ b/test/spec_sendfile.rb @@ -122,4 +122,39 @@ describe Rack::Sendfile do FileUtils.remove_entry_secure dir2 end end + + it "sets X-Accel-Redirect response header and discards body when initialized with multiple mappings via header" do + begin + dir1 = Dir.mktmpdir + dir2 = Dir.mktmpdir + + first_body = open_file(File.join(dir1, 'rack_sendfile')) + first_body.puts 'hello world' + + second_body = open_file(File.join(dir2, 'rack_sendfile')) + second_body.puts 'goodbye world' + + headers = { + 'HTTP_X_SENDFILE_TYPE' => 'X-Accel-Redirect', + 'HTTP_X_ACCEL_MAPPING' => "#{dir1}/=/foo/bar/, #{dir2}/=/wibble/" + } + + request(headers, first_body) do |response| + response.must_be :ok? + response.body.must_be :empty? + response.headers['Content-Length'].must_equal '0' + response.headers['X-Accel-Redirect'].must_equal '/foo/bar/rack_sendfile' + end + + request(headers, second_body) do |response| + response.must_be :ok? + response.body.must_be :empty? + response.headers['Content-Length'].must_equal '0' + response.headers['X-Accel-Redirect'].must_equal '/wibble/rack_sendfile' + end + ensure + FileUtils.remove_entry_secure dir1 + FileUtils.remove_entry_secure dir2 + end + end end -- cgit v1.2.3-24-ge0c7