main
sandyx 3 months ago
commit fcd814ccf6

@ -0,0 +1,11 @@
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<title>Apocrypha</title>
<p>hello world</p>
</body>
</html>

@ -0,0 +1,102 @@
#!/usr/bin/ruby
# main.rb
require 'socket'
require 'fileutils'
require 'pathname'
Root = '.'
Port = 8080
class HttpResponse
def self.content_length(resp)
"Content-Length: #{resp.length}"
end
def self.content_type(resp)
ctype = {
".png" => "image/png",
".txt" => "text/plain",
".html" => "text/html",
".css" => "text/css",
".mp3" => "audio/mpeg",
".ttf" => "font/ttf",
".mp4" => "video/mp4",
".pdf" => "application/pdf"
}
"Content-Type: #{ctype[resp.ext]}"
end
def self.build(resp)
resp.route
if resp.not_found?
return "HTTP/1.1 404 NOT FOUND\r\n"
end
headers = [content_length(resp), content_type(resp)].join("\r\n")
puts headers
return "HTTP/1.1 200 OK\r\n#{headers}\r\n#{resp.data}"
end
end
class HttpRouter
attr_reader :ext
attr_reader :length
attr_reader :data
def initialize(path)
@path = Pathname.new(path)
@ext = File.extname(path)
@not_found = false
@data
end
def route
case @path
when "/"
@path = "./index.html"
return route
else
if File.exist? @path.basename
@data = File.read(Root + @path.to_s)
@length = @data.length
@ext = File.extname(@path)
else
@not_found = true
end
end
end
def not_found?
@not_found
end
end
class HttpServer
def initialize(port)
@server = TCPServer.new port
end
def accept_connection
while session = @server.accept
request = session.gets
verb, path, protocol = request.split(' ') unless request.nil?
if protocol === 'HTTP/1.1'
resp = HttpRouter.new(path)
session.print HttpResponse.build(resp)
else
session.print 'Connection Refused'
end
session.close
end
end
end
server = HttpServer.new Port
server.accept_connection
Loading…
Cancel
Save