main
sandyx 2 months ago
parent fcd814ccf6
commit e0a28cf557

@ -5,11 +5,29 @@
require 'socket'
require 'fileutils'
require 'pathname'
require 'erb'
Root = '.'
Port = 8080
class HttpResponse
def self.process_erb(resp)
unless resp.ext === ".erb"
resp.data = resp.lazy.read
return
end
books = Dir["*"]
template = ERB.new resp.lazy.read
resp.data = template.result(binding)
return
end
def self.connection(str)
"Connection: #{str}"
end
def self.content_length(resp)
"Content-Length: #{resp.length}"
end
@ -19,11 +37,13 @@ class HttpResponse
".png" => "image/png",
".txt" => "text/plain",
".html" => "text/html",
".erb" => "text/html",
".css" => "text/css",
".mp3" => "audio/mpeg",
".ttf" => "font/ttf",
".mp4" => "video/mp4",
".pdf" => "application/pdf"
".pdf" => "application/pdf",
".webp" => "image/webp"
}
"Content-Type: #{ctype[resp.ext]}"
@ -36,17 +56,24 @@ class HttpResponse
return "HTTP/1.1 404 NOT FOUND\r\n"
end
headers = [content_length(resp), content_type(resp)].join("\r\n")
process_erb(resp)
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}"
return "HTTP/1.1 200 OK\r\n#{headers}\r\n\r\n#{resp.data}"
end
end
class HttpRouter
attr_reader :ext
attr_reader :length
attr_reader :data
attr_accessor :data
attr_reader :lazy
def initialize(path)
@path = Pathname.new(path)
@ -56,14 +83,16 @@ class HttpRouter
end
def route
puts @path
case @path
when "/"
@path = "./index.html"
when Pathname.new("/")
@path = Pathname.new("/index.erb")
return route
else
if File.exist? @path.basename
@data = File.read(Root + @path.to_s)
@length = @data.length
@lazy = File.open(@path.basename)
@length = File.size(@path.basename)
@ext = File.extname(@path)
else
@not_found = true
@ -85,12 +114,12 @@ class HttpServer
while session = @server.accept
request = session.gets
verb, path, protocol = request.split(' ') unless request.nil?
verb, path, protocol = request.split(' ')
if protocol === 'HTTP/1.1'
resp = HttpRouter.new(path)
session.print HttpResponse.build(resp)
session.puts HttpResponse.build(resp)
else
session.print 'Connection Refused'
session.puts 'Connection Refused'
end
session.close

Loading…
Cancel
Save