Class: Spyder::Web::FileServer

Inherits:
Object
  • Object
show all
Defined in:
lib/spyder/web/file_server.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(paths, index: nil) ⇒ FileServer

Returns a new instance of FileServer.



9
10
11
12
13
14
# File 'lib/spyder/web/file_server.rb', line 9

def initialize(paths, index: nil)
  @default_index = index
  @base_paths = Array(paths).map do |path|
    File.expand_path(File.join(Dir.pwd, path))
  end
end

Instance Attribute Details

#base_pathsObject (readonly)

Returns the value of attribute base_paths.



6
7
8
# File 'lib/spyder/web/file_server.rb', line 6

def base_paths
  @base_paths
end

#default_indexObject (readonly)

Returns the value of attribute default_index.



7
8
9
# File 'lib/spyder/web/file_server.rb', line 7

def default_index
  @default_index
end

Instance Method Details

#call(request) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/spyder/web/file_server.rb', line 16

def call(request)
  return unless request.verb == 'GET'

  input_path = request.path
  input_path = @default_index if request.path == '/' && @default_index

  req_path = safe_request_path(input_path)
  full_path = nil
  return unless @base_paths.any? do |base|
    fp = File.join(base, *req_path)
    next unless File.file?(fp)
    full_path = fp

    true
  end

  st = File.readable?(full_path) ? File.stat(full_path) : nil

  return unless st && %w[file link].include?(st.ftype)

  etag = "\"#{"%xT-%x0" % [st.mtime, st.size]}\""

  resp = serve_not_modified_response(request, st, etag)
  return resp if resp

  resp = Spyder::Response.new
  resp.add_standard_headers
  resp.set_header 'last-modified', st.mtime.httpdate
  resp.set_header 'etag', etag
  resp.set_header 'cache-control', 'public, must-revalidate, max-age=0'

  File.open full_path do |fp|
    mime = Marcel::MimeType.for(fp)
    if mime == 'application/octet-stream' || mime == 'text/plain'
      mime = Marcel::MimeType.for(name: req_path.last)
    end

    resp.set_header('content-type', mime) if mime

    fp.rewind
    resp.body = fp.read
  end

  resp
end