Skip to content

Instantly share code, notes, and snippets.

@csabahenk
Created December 9, 2011 02:26
Show Gist options
  • Save csabahenk/1449848 to your computer and use it in GitHub Desktop.
Save csabahenk/1449848 to your computer and use it in GitHub Desktop.
Gist ripoff markdown server

This script spawns you a file server which serves markdown files (of .md extension) by rendering them to html. Might come handy if you are writing up something in markdown and want to check the work you've done.

It needs the github-markdown gem (gem install github-markdown).

#!/usr/bin/env ruby
require "webrick"
require "open-uri"
require "optparse"
require "github/markdown"
module WEBrick
module HTTPServlet
class MarkdownHandler < AbstractServlet
def initialize(server, local_path)
super(server, local_path)
@local_path = local_path
end
def do_GET(req, res)
res.body =<<EOF
<html>
<head>
<link href="/.css" media="screen" rel="stylesheet" type="text/css" />
</head>
<body>
#{GitHub::Markdown.to_html IO.read(@local_path), :gfm}
</body>
</html>
EOF
res['content-type'] = 'text/html; charset=utf-8'
end
end
end
end
opts = { :Port => 1234, :DocumentRoot => '.' }
exts = %w[md]
css = nil
OptionParser.new { |op|
op.banner = "simple web service that renders markdown files to html\n#{op.banner}"
op.on('-p', '--port <port>', Integer, "listen port, default: #{opts[:Port]}") { |v| opts[:Port] = v }
op.on('-r', '--root <dir>', "document root, default: #{opts[:DocumentRoot]}") { |v| opts[:DocumentRoot] = v }
op.on('-e', '--extensions x,y,z', Array, "extensions that are considered markdown, default: #{exts.join(",")}") { |v| exts = v }
op.on('-c', '--css <css>') { |v| css = v }
}.parse!
exts.each { |s|
WEBrick::HTTPServlet::FileHandler.add_handler s,
WEBrick::HTTPServlet::MarkdownHandler
}
server = WEBrick::HTTPServer.new opts
if css
cssdata = IO.read css
server.mount_proc('/.css') { |req, res|
res.body = cssdata
res['content-type'] = 'text/css'
}
end
%w[INT TERM].each do |signal|
trap(signal) {server.shutdown}
end
server.start
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment