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)
- - (Object) content_type(file)
-
- (Response) initialize(request, server)
constructor
A new instance of Response.
- - (Object) log(msg)
- - (Object) print(msg)
- - (Object) send(code, message)
- - (Object) send_301(redirect_to)
- - (Object) send_404
- - (Object) send_file(path)
Constructor Details
- (Response) initialize(request, server)
Returns a new instance of Response
21 22 23 24 25 |
# File 'lib/server/response.rb', line 21 def initialize(request, server) @request = request @socket = request.socket @server = server end |
Instance Method Details
- (Object) content_type(file)
43 44 45 46 |
# File 'lib/server/response.rb', line 43 def content_type file ext = File.extname(file).split(".").last CONTENT_TYPE_MAPPING.fetch(ext, DEFAULT_CONTENT_TYPE) end |
- (Object) log(msg)
27 28 29 |
# File 'lib/server/response.rb', line 27 def log msg @server.log msg end |
- (Object) print(msg)
31 32 33 |
# File 'lib/server/response.rb', line 31 def print msg @socket.print msg end |
- (Object) send(code, message)
73 74 75 76 77 78 79 80 |
# File 'lib/server/response.rb', line 73 def send(code, ) print "HTTP/1.1 #{code} Not Found\r\n" + "Content-Type: text/plain\r\n" + "Content-Length: #{.size}\r\n" + "Connection: close\r\n" + "\r\n" + end |
- (Object) send_301(redirect_to)
48 49 50 51 52 53 54 55 56 57 58 |
# File 'lib/server/response.rb', line 48 def send_301 redirect_to redirect_to.slice!("web_root") redirect_to = "http://#{@socket.addr[2]}:#{@socket.addr[1]}#{redirect_to}" 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: close\r\n" end |
- (Object) send_404
35 36 37 38 39 40 41 |
# File 'lib/server/response.rb', line 35 def send_404 code = 404 = "404: File '#{@request.path}' not found\n" log "404: File not found #{@request.path}" send(code, ) end |
- (Object) send_file(path)
60 61 62 63 64 65 66 67 68 69 70 71 |
# File 'lib/server/response.rb', line 60 def send_file path File.open(@request.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: close\r\n" + "\r\n" # write the contents of the file to the socket IO.copy_stream(file, @socket) end end |