Skip to content

Instantly share code, notes, and snippets.

@csabahenk
Last active August 29, 2015 14:02
Show Gist options
  • Save csabahenk/e87516e03f6f84612a5f to your computer and use it in GitHub Desktop.
Save csabahenk/e87516e03f6f84612a5f to your computer and use it in GitHub Desktop.
Pandoc based markdown rendering service

This script spawns you a file server which serves files of various markup formats by rendering them to html. Might come handy if you are writing up something in markdown/rst/etc. and want to check the work you've done.

It needs Ruby and Pandoc (to which we refer for the list of available formatters).

#!/usr/bin/env ruby
require "webrick"
require "open-uri"
require "optparse"
module WEBrick
module HTTPServlet
class PandocHandler < AbstractServlet
CSSPATH = '/.css'
def initialize(server, local_path)
super(server, local_path)
@local_path = local_path
@use_css = server[:PandocCSS]
end
def do_GET(req, res)
IO.popen(%w[pandoc -t html -s] + (@use_css ? ["-c", CSSPATH] : []) + [@local_path]) { |f|
res.body = f.read
Process.wait2(f.pid)[1].success? or raise "pandoc failed on #{@local_path}"
}
res['content-type'] = 'text/html; charset=utf-8'
end
end
end
end
opts = { :Port => 1234, :DocumentRoot => '.',
:DocumentRootOptions => {:HandlerTable => Hash.new(WEBrick::HTTPServlet::PandocHandler),
# to work around some
# issue with options
:FancyIndexing => true}
}
css = nil
OptionParser.new { |op|
op.banner = "simple web service that renders files of various markups 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('-c', '--css <css>') { |v|
css = v
opts[:PandocCSS] = true
}
}.parse!
server = WEBrick::HTTPServer.new opts
if css
cssdata = IO.read css
server.mount_proc(WEBrick::HTTPServlet::PandocHandler::CSSPATH) { |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