Class: Server::Response
- Inherits:
-
Object
- Object
- Server::Response
- Defined in:
- lib/server/response.rb
Overview
This helper function parses the extension of the requested file and then looks up its content type.
Instance Method Summary collapse
- #content_type(file) ⇒ Object
-
#initialize(request) ⇒ Response
constructor
A new instance of Response.
- #print(msg) ⇒ Object
- #send(code, message, type = 'text/html') ⇒ Object
- #send_301(redirect_to) ⇒ Object
- #send_404 ⇒ Object
- #send_file(path) ⇒ Object
Constructor Details
#initialize(request) ⇒ Response
Returns a new instance of Response.
23 24 25 26 |
# File 'lib/server/response.rb', line 23 def initialize(request) @request = request @socket = request.socket end |
Instance Method Details
#content_type(file) ⇒ Object
40 41 42 43 |
# 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) ⇒ Object
28 29 30 |
# File 'lib/server/response.rb', line 28 def print msg @socket.print msg end |
#send(code, message, type = 'text/html') ⇒ Object
76 77 78 79 80 81 82 83 84 |
# File 'lib/server/response.rb', line 76 def send(code, , type='text/html') print "HTTP/1.1 #{code}\r\n" + "Content-Type: #{type}\r\n" + "Content-Length: #{.size}\r\n" + "Connection: Keep-Alive\r\n" + "Vary: Accept-Encoding\r\n" + "\r\n" + end |
#send_301(redirect_to) ⇒ Object
45 46 47 48 49 50 51 52 53 54 55 |
# 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 ⇒ Object
32 33 34 35 36 37 38 |
# File 'lib/server/response.rb', line 32 def send_404 code = '404 Not Found' = "404: File '#{@request.path}' not found\n" Server.log "404: File not found #{@request.path}" send(code, ) end |
#send_file(path) ⇒ Object
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 |
# 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 |