Last active
August 29, 2015 14:17
-
-
Save NightFeather/59b7f2581bd6addd400a to your computer and use it in GitHub Desktop.
This file contains 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 'net/http' | |
Signal.trap("INT") { | |
puts "Caught Signal...., Go down." | |
exit | |
} | |
puts "Start Working at #{Dir.pwd}" | |
class Response < Struct.new(:path,:status, :head, :body) | |
end | |
def build_response(path) | |
r = Response.new | |
r.path = path | |
r.status = File.exist?(path) ? 200 : 404 | |
r.head = ["Content-Type: #{mime_type(File.extname(path))}; charset=utf-8","Connection: close"] | |
r.body = File.exist?(path) ? open(path).read : error_page(r.status) | |
return r | |
end | |
def error_page status | |
t = "#{status} #{reason(status)}" | |
"<html><head><title>#{t}</title></head><body><h1>#{t}</h1></body></html>" | |
end | |
def mime_type ext | |
case (ext) | |
when ".html" | |
return "text/html" | |
when ".js" | |
return "text/javascript" | |
when ".css" | |
return "text/css" | |
when ".jpg" | |
return "image/mpeg" | |
when ".png" | |
return "image/png" | |
when ".gif" | |
return "image/gif" | |
else | |
return "text/html" | |
end | |
end | |
def parse_path(getpath) | |
if( File.exist?( File.join(".",getpath) ) ) | |
return parse_path(File.join(getpath,"index.html")) if File.directory?(File.join(".",getpath)) | |
return File.join(".",getpath) | |
else | |
return File.join(".",getpath) | |
end | |
end | |
def reason code | |
case code | |
when 200 | |
"OK" | |
when 404 | |
"Not Found" | |
else | |
"WTF" | |
end | |
end | |
TCPServer.open("127.0.0.1",8080) { |s| | |
loop { | |
Thread.start(s.accept) { |c| | |
head = [] | |
loop { | |
buffer = c.gets | |
break if buffer =~ /^\s*$/ | |
head << buffer | |
} | |
fp = parse_path(head[0].split(" ")[1]) | |
r = build_response(fp) | |
puts "#"*10 | |
puts head | |
puts "="*10 | |
puts r.path | |
puts "#"*10 | |
c.puts "HTTP/1.1 #{r.status} #{reason(r.status)}\r\n" | |
r.head.each{|h| c.puts h+"\r\n"} | |
c.puts "\r\n" | |
c.puts r.body | |
c.close | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment