80 lines
No EOL
2.8 KiB
Ruby
80 lines
No EOL
2.8 KiB
Ruby
require 'socket'
|
|
require_relative 'request'
|
|
require_relative 'route'
|
|
|
|
class HTTPServer
|
|
|
|
def initialize(port)
|
|
@port = port
|
|
end
|
|
|
|
def start
|
|
server = TCPServer.new(@port)
|
|
puts "Listening on #{@port}"
|
|
|
|
router = Router.new
|
|
router.add_route("GET",/\/grillkorv\/\d/) do |id, senap|
|
|
if File.read("./public/grillkorv.html") != nil
|
|
File.read("./public/grillkorv.html")
|
|
else
|
|
"Html not found"
|
|
end
|
|
end
|
|
router.add_route("GET",/\/grillkorv\/\w.css/) do |id, senap|
|
|
if File.read("./public/grillkorv.html") != nil
|
|
File.read("./public/grillkorv.html")
|
|
else
|
|
"Html not found"
|
|
end
|
|
end
|
|
router.add_route("GET","/favicon.ico")
|
|
|
|
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)
|
|
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}")
|
|
outputContent[:info] = File.read("./public#{routeReturn[0].resource}")
|
|
print("Successfully opened file \"./public#{routeReturn[0].resource}\" with contents:\n#{outputContent[:info]}\n ")
|
|
outputContent[:type] = "text/css"
|
|
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
|
|
|
|
session.print "HTTP/1.1 #{status}\r\n"
|
|
session.print "Content-Type: #{outputContent[:type]}\r\n"
|
|
print("Reading content type: #{outputContent[:type]}\n")
|
|
session.print "\r\n"
|
|
if outputContent[:info]; session.print outputContent[:info] end
|
|
session.close
|
|
end
|
|
end
|
|
end |