class Server::Response
This helper function parses the extension of the requested file and then looks up its content type.
Public Class Methods
new(request)
click to toggle source
# File lib/server/response.rb, line 23 def initialize(request) @request = request @socket = request.socket end
Public Instance Methods
content_type(file)
click to toggle source
# File lib/server/response.rb, line 40 def content_type file ext = File.extname(file).split(".").last CONTENT_TYPE_MAPPING.fetch(ext, DEFAULT_CONTENT_TYPE) end
print(msg)
click to toggle source
# File lib/server/response.rb, line 28 def print msg @socket.print msg end
send(code, message, type='text/html')
click to toggle source
# File lib/server/response.rb, line 76 def send(code, message, type='text/html') print "HTTP/1.1 #{code}\r\n" + "Content-Type: #{type}\r\n" + "Content-Length: #{message.size}\r\n" + "Connection: Keep-Alive\r\n" + "Vary: Accept-Encoding\r\n" + "\r\n" + message end
send_301(redirect_to)
click to toggle source
# File lib/server/response.rb, line 45 def send_301 redirect_to redirect_to.slice!("web_root") redirect_to = "http://#{@socket.addr[2]}:#{@socket.addr[1]}#{redirect_to}" Server.log "301: redirect to #{redirect_to}" # respond with a 301 error code to redirect print "HTTP/1.1 301 Moved Permanently\r\n" + "Location: #{redirect_to}\r\n"+ "Connection: Keep-Alive\r\n" end
send_404()
click to toggle source
# File lib/server/response.rb, line 32 def send_404 code = '404 Not Found' message = "404: File '#{@request.path}' not found\n" Server.log "404: File not found #{@request.path}" send(code, message) end
send_file(path)
click to toggle source
# File lib/server/response.rb, line 57 def send_file path last_modified = File.mtime(path).httpdate File.open(path, "rb") do |file| print "HTTP/1.1 200 OK\r\n" + "Content-Type: #{content_type(file)}\r\n" + "Content-Length: #{file.size}\r\n" + "Connection: Keep-Alive\r\n" + "Vary: Accept-Encoding\r\n" + "Last-Modified: #{last_modified}\r\n" + "Date: #{Date.today.httpdate}\r\n" + "Expires: #{Date.today.next_year.httpdate}\r\n" + "Cache-Control: max-age=31536000,public\r\n" + "\r\n" # write the contents of the file to the socket IO.copy_stream(file, @socket) end end