Class: Raamen::FileServer

Inherits:
Object
  • Object
show all
Defined in:
lib/raamen/static.rb

Constant Summary collapse

MIME_TYPES =
{
  ".txt" => "text/plain",
  ".jpg" => "image/jpeg",
  ".zip" => "application/zip"
}

Instance Method Summary collapse

Constructor Details

#initialize(root) ⇒ FileServer

Returns a new instance of FileServer.



32
33
34
# File 'lib/raamen/static.rb', line 32

def initialize(root)
  @root = root
end

Instance Method Details

#call(env) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/raamen/static.rb', line 36

def call(env)
  req = Rack::Request.new(env)
  res = Rack::Response.new
  file_path = File.join(
   Dir.pwd,
    req.path
  )

  if File.exist?(file_path)
    extension = File.extname(file_path)
    content_type = MIME_TYPES[extension]
    file_content = File.read(file_path)
    res["Content-Type"] = content_type
    res.write(file_content)
  else
    res.status = 404
    res.write("File not found")
  end

  res
end