Skip to content

Instantly share code, notes, and snippets.

@higuma
Created April 27, 2014 10:32
Show Gist options
  • Save higuma/11342427 to your computer and use it in GitHub Desktop.
Save higuma/11342427 to your computer and use it in GitHub Desktop.
Rack応用 - HTTP圧縮エンコーディング最適化 ref: http://qiita.com/higuma/items/9b841aca5f3d58a2b5aa
Accept-Encoding: gzip, deflate
Content-Encoding: gzip
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
$ gem install rack-gzip-file
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment