Created
April 27, 2014 10:32
-
-
Save higuma/11342427 to your computer and use it in GitHub Desktop.
Rack応用 - HTTP圧縮エンコーディング最適化 ref: http://qiita.com/higuma/items/9b841aca5f3d58a2b5aa
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Accept-Encoding: gzip, deflate |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Content-Encoding: gzip |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'rack' | |
class GzipFile | |
def initialize(root) | |
@file = Rack::File.new(root) | |
end | |
def call(env) | |
path = env['PATH_INFO'] # 元のパスを保存 | |
env['PATH_INFO'] = path + '.gz' # .gzを追加 | |
status, headers, body = @file.call(env) # Rack::Fileに処理させる | |
if status == 200 # .gzがある場合 | |
# まずMIME typeがapplication/gzipになっているので正しく付け直す | |
mime = Rack::Mime.mime_type(File.extname(path), 'text/plain') | |
headers['Content-Type'] = mime if mime | |
# クライアントがgzipに対応しているかチェック | |
accept_enc = env['HTTP_ACCEPT_ENCODING'] | |
if accept_enc && accept_enc.include?('gzip') | |
# 対応している場合はヘッダ設定だけでOK | |
headers['Content-Encoding'] = 'gzip' | |
else | |
# 非対応の場合は自分で読み込んで解凍する | |
body = [Zlib::GzipReader.open(body.to_path) {|gz| gz.read }] | |
headers['Content-Length'] = body[0].bytesize.to_s # 要設定 | |
headers.delete 'Content-Encoding' # 消去 | |
end | |
[code, headers, body] | |
else # .gzがなかったら... | |
env['PATH_INFO'] = path # パスを元に戻してリトライ | |
@file.call(env) | |
end | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ gem install rack-gzip-file |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment