Class: Riddl::Utils::FileServe

Inherits:
Implementation show all
Defined in:
lib/ruby/riddl/utils/fileserve.rb

Instance Method Summary collapse

Methods inherited from Implementation

#headers, #initialize, #status

Constructor Details

This class inherits a constructor from Riddl::Implementation

Instance Method Details

#responseObject



8
9
10
11
12
13
14
15
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
# File 'lib/ruby/riddl/utils/fileserve.rb', line 8

def response
  path = File.file?(@a[0]) ? @a[0] : "#{@a[0]}/#{@r[@match.length-1..-1].join('/')}".gsub(/\/+/,'/')

  if File.directory?(path)
    @status = 404
    return []
  end
  if File.exists?(path)
    mtime = File.mtime(path)
    @headers << Riddl::Header.new("Last-Modified",mtime.httpdate)
    @headers << Riddl::Header.new("ETag",Digest::MD5.hexdigest(mtime.httpdate))
    htime = @env["HTTP_IF_MODIFIED_SINCE"].nil? ? Time.at(0) : Time.parse(@env["HTTP_IF_MODIFIED_SINCE"])
    if htime == mtime
      @headers << Riddl::Header.new("Connection","close")
      @status = 304 # Not modified
      return []
    else
      fmt = @a[1] || begin
        mt = MIME::Types.type_for(path).first
        if mt.nil?
          'text/plain;charset=utf-8'
        else
          apx = ''
          if mt.ascii?
            tstr = File.read(path,CharlockHolmes::EncodingDetector::DEFAULT_BINARY_SCAN_LEN)
            apx = ';charset=' + CharlockHolmes::EncodingDetector.detect(tstr)[:encoding]
          end
          mt.to_s + apx
        end
      end
      return Riddl::Parameter::Complex.new('file',fmt,File.open(path,'r'))
    end
  end
  @status = 404
end