Toppatea/lib/response.rb
2024-06-01 18:51:48 +02:00

73 lines
No EOL
3.4 KiB
Ruby

# Reponse class used to format and respond to a request. Takes in the touple returned by the route class and returns either the requested method or the file in the requested position (if the match returned a 404 and a file is found in the requested position)
class Response
# Initialize the response by checking if a response is applicable and what information should be returned
#
# @param routeReturn [Array] A list consisting of the matched request and the status
def initialize(routeReturn)
outputContent = {}
status = routeReturn[1]
if status == 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 status == 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
@status = status
@outputContent = outputContent
end
# Responds to the request with the information requested
#
# @param session [TCPsocket] A client request through the TCP port awaiting a response
def print(session)
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
# Gets the mime extension for respond file
#
# @param extension [Str] a string containing the extension of the file to find the MIME format for
# @return [String] the MIME format of the requested extension.
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