Created
December 28, 2008 02:09
-
-
Save sr/40351 to your computer and use it in GitHub Desktop.
This file contains 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
# WTFPL | |
# Requires http://github.com/rtomayko/sinatra/tree/hoboken | |
require "rubygems" | |
require "rack" | |
require "thin" | |
require "pathname" | |
require "addressable/uri" | |
require "sinatra/base" | |
class Serve < Sinatra::Application | |
class UnknownDirectoryError < StandardError; end | |
Formats = %w(html css js textile markdown).freeze | |
attr_reader :base, :charset | |
def initialize(base, charset="UTF-8") | |
@base = Pathname(base) | |
@charset = charset | |
raise UnknownDirectoryError unless @base.directory? | |
end | |
get "/*" do | |
Formats.each do |format| | |
path = params[:splat].join | |
path = "index" if path.empty? || path == "/" | |
path << ".#{format}" unless base.join(path).file? && !path.end_with?(format) | |
next unless (file = base.join(path)).file? | |
content_type media_type(file.extname || format) || "html", :charset => charset | |
halt [200, file.read] | |
break | |
end | |
not_found 'Not found. Try <a href="/">root</a>.' | |
end | |
end | |
if $0 == __FILE__ | |
directory = ARGV[0] || Dir.pwd | |
charset = ARGV[1] ? ARGV[1] : nil | |
app = begin | |
Serve.new(directory, charset) | |
rescue Serve::UnknownDirectoryError | |
$stderr.puts "Unknown directory `#{directory}`" | |
abort("Usage: #{$0} directory [charset]") | |
end | |
Thin::Server.start("0.0.0.0", 1234) do | |
use Rack::CommonLogger | |
run app | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment