Skip to content

Instantly share code, notes, and snippets.

@mtgto
Created September 25, 2013 03:02
Show Gist options
  • Save mtgto/6694684 to your computer and use it in GitHub Desktop.
Save mtgto/6694684 to your computer and use it in GitHub Desktop.
対sbt用proxy (ruby製。typoあり)
require 'socket'
require 'net/http'
require 'uri'
class Proxy
PORT = 8888
def initialize
@server_socket = TCPServer.open(nil, PORT)
@responses = {}
end
def start
while true
Thread.start(@server_socket.accept) do |s|
method, url, version = get_base_header(s)
uri = URI.parse(url)
key = "#{method} #{url}"
if @responses.include?(key)
res = @responses[key]
puts "[HIT!] #{method} #{url}"
else
res = @responses[key] = get_http_response(method, uri)
puts "[MISS] #{method} #{url}"
end
s.write "HTTP/#{res.http_version} #{res.code} #{res.message}\r\n"
#puts "> HTTP/#{res.http_version} #{res.code} #{res.message}"
res.each_capitalized {|k, v|
s.write "#{k}: #{v}\r\n"
#puts "> #{k}: #{v}"
}
s.write "\r\n"
#puts
s.write res.body
#puts res.body
s.close
end
end
end
def get_http_response(method, uri)
res = Net::HTTP.start(uri.host, uri.port) {|h|
case method
when "HEAD"
h.head(uri.request_uri)
when "GET"
res = h.get(uri.request_uri)
res['Connection'] = 'closed'
res['Content-Length'] = res.body.size.to_s
res['Keep-Alice'] = nil
res['Transfer-Encoding'] = nil
res
else
raise RuntimeError.new("サポートしてないプロトコル: #{method}")
end
}
end
def get_base_header(s)
# TODO: 何時まで経っても改行コードを書かない悪い子がいたらどうしよう
l = s.gets
l.split
end
end
proxy = Proxy.new
proxy.start
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment