Skip to content

Instantly share code, notes, and snippets.

@johnholdun
Last active December 17, 2015 18:09
Show Gist options
  • Save johnholdun/5650960 to your computer and use it in GitHub Desktop.
Save johnholdun/5650960 to your computer and use it in GitHub Desktop.
Serve a directory of files AND parse them if they're not HTML!
# from your working directory, just run `rackup /path/to/simple_server.ru`
require 'tilt'
require 'sass'
run lambda{ |env|
path = ENV['PWD'] + env['REQUEST_PATH']
path += 'index' if path =~ %r[/$]
path.gsub! /\?(.+)$/, ''
params = $1
params = Rack::Utils.parse_nested_query(params) if params.is_a? String
params ||= {}
file = nil
potential_files = [path, Dir.glob("#{path}.*"), Dir.glob("#{path}/index.*")].flatten
potential_files.each do |potential_file|
if file.nil? and File.exists? potential_file
file = potential_file
end
end
if file
status = 200
output = Tilt.new(file).render(Struct.new(:params), params: params)
extension = File.extname(file)[1 .. -1]
content_type = case extension
when 'html', 'haml', 'erb'
'text/html'
when 'css', 'sass'
'text/css'
else
'text/plain'
end
else
status = 404
output = 'Not found'
content_type = 'text/plain'
end
[status, {'Content-Type' => content_type}, [output]]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment