Skip to content

Instantly share code, notes, and snippets.

@hmarr
Last active December 16, 2015 15:09
Show Gist options
  • Save hmarr/6367dd67d5de69ab4051 to your computer and use it in GitHub Desktop.
Save hmarr/6367dd67d5de69ab4051 to your computer and use it in GitHub Desktop.
Accept Github flavoured markdown on stdin, and render it in the browser
#!/usr/bin/env python
import sys
import urllib2
import json
import webbrowser
import BaseHTTPServer
import threading
markdown = sys.stdin.read()
mode = 'markdown'
if len(sys.argv) == 2 and sys.argv[1] == 'gfm':
mode = 'gfm'
url = 'https://api.github.com/markdown'
data = json.dumps({'text': markdown, 'mode': mode})
request = urllib2.Request(url, data)
response = urllib2.urlopen(request)
markdown_html = response.read()
class Handler(BaseHTTPServer.BaseHTTPRequestHandler):
def do_GET(self):
html = """
<html>
<head>
<link rel="stylesheet"
type="text/css"
href="https://cdn.jsdelivr.net/github-markdown-css/2.1.1/github-markdown.css">
<style>
.markdown-body {
max-width: 887px;
margin: 50px auto;
}
</style>
</head>
<body class="markdown-body">%s</body>
</html>
""" % markdown_html
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
self.wfile.write(html)
def log_message(self, format, *args):
return
def run_server():
httpd = BaseHTTPServer.HTTPServer(('localhost', 48293), Handler)
httpd.handle_request()
server_thread = threading.Thread(target=run_server)
server_thread.start()
webbrowser.open_new('http://localhost:48293')
server_thread.join()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment