89 lines
No EOL
3.4 KiB
Ruby
89 lines
No EOL
3.4 KiB
Ruby
require 'socket'
|
|
require_relative 'request'
|
|
require_relative 'route'
|
|
|
|
class HTTPServer
|
|
|
|
def initialize(port, router)
|
|
@port = port
|
|
@router = router
|
|
end
|
|
|
|
def start
|
|
server = TCPServer.new(@port)
|
|
puts "Listening on #{@port}"
|
|
|
|
while session = server.accept
|
|
data = ""
|
|
while line = session.gets and line !~ /^\s*$/
|
|
data += line
|
|
end
|
|
puts "RECEIVED REQUEST"
|
|
puts "-" * 40
|
|
puts data
|
|
puts "-" * 40
|
|
|
|
request = Request.new(data)
|
|
pp request
|
|
|
|
routeReturn = @router.match_route(request)
|
|
# pil nedåt ska in i response-klassen
|
|
response = Response.new(routeReturn, session)
|
|
response.print()
|
|
|
|
outputContent = {}
|
|
if routeReturn[1] == 200
|
|
if routeReturn[0][:block] != nil
|
|
outputContent[:info] = routeReturn[0][:block].call
|
|
print("Recieved HTML, enabling as called:\n #{outputContent[:info]}")
|
|
outputContent[:type] = "text/html"
|
|
status = 200
|
|
else
|
|
outputContent[:info] = nil
|
|
status = 200
|
|
end
|
|
elsif routeReturn[1] == 404
|
|
print("HTML route not found, searching for target file...\n")
|
|
if File.file?("./public/#{routeReturn[0].resource}")
|
|
print("Found file: ./public/#{routeReturn[0].resource}\n")
|
|
outputContent[:info] = File.open("./public#{routeReturn[0].resource}", "rb")
|
|
if outputContent[:type].to_s.split("/")[0] == "text"
|
|
print("Successfully opened file \"./public#{routeReturn[0].resource}\" with contents:\n#{outputContent[:info].read}\n ")
|
|
end
|
|
outputContent[:type] = getMime(File.extname("./public/#{routeReturn[0].resource}").to_str)
|
|
status = 200
|
|
else
|
|
print("Could not find file: \"./public/#{routeReturn[0].resource}\"\n")
|
|
status = 404
|
|
end
|
|
end
|
|
|
|
# Nedanstående bör göras i er Response-klass
|
|
|
|
print("\nStatus: #{status.to_s}\n")
|
|
session.print "HTTP/1.1 #{status}\r\n"
|
|
if status != 404
|
|
session.print "Content-Type: #{outputContent[:type]}\r\n"
|
|
print("\nReading content type: #{outputContent[:type]}\n")
|
|
print("\nLoaded is of type: #{outputContent[:info].class}\n")
|
|
print("\nSize reading: #{File.size(outputContent[:info])}\n")
|
|
session.print "Content-Length: #{File.size(outputContent[:info])}\r\n"
|
|
session.print "\r\n"
|
|
printContent = outputContent[:info].read
|
|
if printContent; session.print printContent end
|
|
end
|
|
session.close
|
|
end
|
|
end
|
|
|
|
def getMime(extension)
|
|
mimes = { ".css" => "text/css", ".html" => "text/html", ".ico" => "image/vnd.microsoft.icon", ".jpg" => "image/jpeg", ".png" => "image/png"}
|
|
if mimes[extension] != nil
|
|
print("Found #{mimes[extension]} result for extension #{extension}\n")
|
|
return mimes[extension]
|
|
else
|
|
print("Found no result for extension #{extension}\n")
|
|
return nil
|
|
end
|
|
end
|
|
end |