Last active
December 17, 2015 18:09
-
-
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!
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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