Skip to content

Instantly share code, notes, and snippets.

@nvsofts
Last active August 29, 2015 14:10
Show Gist options
  • Save nvsofts/61176d30afbf84ae8e6a to your computer and use it in GitHub Desktop.
Save nvsofts/61176d30afbf84ae8e6a to your computer and use it in GitHub Desktop.
自分用アレゲ画像キャッシュプロキシ
#!/usr/bin/env ruby
require 'fileutils'
require 'digest/sha2'
require 'webrick'
require 'webrick/httpproxy'
HOST_REGEX = [<HOST>]
PATH_REGEX = {/gif$/ => 'image/gif', /jpe??g$/ => 'image/jpeg', /png$/ => 'image/png'}
BIND_ADDR = '<IP>'
PORT = 8080
class CacheProxy < WEBrick::HTTPProxyServer
def proxy_service(req, res)
match_host = false
HOST_REGEX.each do |v|
if req.host.match(v) then
match_host = true
break
end
end
if !match_host then
super(req, res)
return
end
match_path_mime = nil
match_path = false
PATH_REGEX.each do |k, v|
if req.path.match(k) then
match_path = true
match_path_mime = v
break
end
end
if !match_path then
super(req, res)
return
end
puts req.host + req.path
hash = Digest::SHA256.hexdigest(req.path)
path_ = 'cache/%s' % req.host.gsub('/', '')
path = '%s/%s' % [path_, hash]
if File.exists?(path) then
puts 'Using %s' % path
puts
data = IO.binread(path)
res.status = 200
res.content_type = match_path_mime
res.body = data
return
end
super(req, res)
FileUtils.mkdir_p(path_)
IO.binwrite(path, res.body)
puts 'Cached to %s' % path
puts
end
end
config = { :BindAddress => BIND_ADDR, :Port => PORT, :AccessLog => [], :DoNotReverseLookup => true }
s = CacheProxy.new( config )
Signal.trap('INT') do
s.shutdown
end
s.start
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment