Class: Cosensee::WebServer::StaticFileHandler

Inherits:
Object
  • Object
show all
Defined in:
lib/cosensee/web_server/static_file_handler.rb

Overview

Rack application for Falcon that serves static files from a directory.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(dir:, logger:) ⇒ StaticFileHandler

Returns a new instance of StaticFileHandler.



10
11
12
13
# File 'lib/cosensee/web_server/static_file_handler.rb', line 10

def initialize(dir:, logger:)
  @dir = dir
  @logger = logger
end

Instance Attribute Details

#dirObject (readonly)

Returns the value of attribute dir.



15
16
17
# File 'lib/cosensee/web_server/static_file_handler.rb', line 15

def dir
  @dir
end

#loggerObject (readonly)

Returns the value of attribute logger.



15
16
17
# File 'lib/cosensee/web_server/static_file_handler.rb', line 15

def logger
  @logger
end

Instance Method Details

#call(env) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/cosensee/web_server/static_file_handler.rb', line 17

def call(env)
  path_info = env['PATH_INFO']
  logger.info("Request path: #{env['PATH_INFO']}")
  path_info = if path_info.start_with?('/')
                "/#{URI.decode_www_form_component(path_info.slice(1..-1))}"
              else
                URI.decode_www_form_component(path_info)
              end
  path = File.join(dir, path_info)
  path = File.join(path, 'index.html') if File.directory?(path)

  if File.exist?(path) && !File.directory?(path)
    content = File.read(path)
    content_type = MiniMime.lookup_by_filename(path).content_type
    content_length = content.bytesize.to_s

    logger.info("Response size: #{content_length}")

    [200, { 'Content-Type' => content_type, 'Content-Length' => content_length }, [content]]
  else
    logger.info("Error File not found path: #{env['PATH_INFO']}")
    [404, { 'Content-Type' => 'text/plain' }, ["File not found: #{env['PATH_INFO']}"]]
  end
end