Class: Scarpe::Components::AssetServer::FileServlet

Inherits:
WEBrick::HTTPServlet::AbstractServlet
  • Object
show all
Defined in:
lib/scarpe/components/asset_server.rb

Overview

Define a custom servlet to handle file requests Webrick config adapted from ChetankumarSB’s local_file_server example

Constant Summary collapse

FS_TYPES =
[:app, :scarpe_components]

Instance Method Summary collapse

Constructor Details

#initialize(server, options) ⇒ FileServlet

Returns a new instance of FileServlet.



185
186
187
188
189
190
191
192
193
194
195
# File 'lib/scarpe/components/asset_server.rb', line 185

def initialize(server, options)
  @fs_opts = options
  unless options[:Type]
    raise "Internal error! FileServlet expects to know what root it's serving!"
  end
  unless FS_TYPES.include?(options[:Type])
    raise "Internal error! Unknown FileServlet root type #{options[:Type].inspect}!"
  end

  super
end

Instance Method Details

#do_GET(request, response) ⇒ Object



197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
# File 'lib/scarpe/components/asset_server.rb', line 197

def do_GET(request, response)
  relative_path = request.path.delete_prefix(@fs_opts[:Prefix])
  path = File.join(@fs_opts[:DocumentRoot], relative_path)

  if File.exist?(path) && !File.directory?(path)
    begin
      file_content = File.read(path)

      response.status = 200
      response['Content-Type'] = WEBrick::HTTPUtils.mime_type(path, WEBrick::HTTPUtils::DefaultMimeTypes)
      response.body = file_content
    rescue StandardError => e
      STDERR.puts "Error serving asset: #{e.inspect}"
      response.status = 500
      response.body = 'Internal Server Error'
    end
  else
    response.status = 404
    response.body = 'File not found'
  end
end

#inspectObject



181
182
183
# File 'lib/scarpe/components/asset_server.rb', line 181

def inspect
  "<FileServlet #{@fs_opts[:Type].inspect}>"
end