Skip to content

Instantly share code, notes, and snippets.

@sr
Created December 28, 2008 02:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sr/40351 to your computer and use it in GitHub Desktop.
Save sr/40351 to your computer and use it in GitHub Desktop.
# 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