main
sandyx 2 months ago
parent fcd814ccf6
commit e0a28cf557

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

Loading…
Cancel
Save