Skip to content

Instantly share code, notes, and snippets.

@rochacon
Created July 24, 2014 21:18
Show Gist options
  • Save rochacon/34080d98939aa1fa06ad to your computer and use it in GitHub Desktop.
Save rochacon/34080d98939aa1fa06ad to your computer and use it in GitHub Desktop.
Simple web server to render Markdown from a folder
// md-server is a simple web server to render Markdown files through HTTP
// this was just a quick "hack" so I could show some docs I was working on to a friend
// since the lack of styles and links, this ended up being completely unuseful
// if you want a serious Markdown renderer server, take a look at: http://www.mkdocs.org/
package main
import (
"flag"
"fmt"
"github.com/russross/blackfriday"
"io/ioutil"
"net/http"
"os"
"path/filepath"
)
var ROOT string
func main() {
flag.StringVar(&ROOT, "root", "", "Root folder where Markdown templates lives")
flag.Parse()
if ROOT == "" {
ROOT, _ = os.Getwd()
} else {
ROOT, _ = filepath.Abs(ROOT)
}
fmt.Println("Listening on :8001")
fmt.Println("root:", ROOT)
http.HandleFunc("/", renderMd)
http.ListenAndServe(":8001", nil)
}
func renderMd(w http.ResponseWriter, r *http.Request) {
filename := r.URL.Path
if filename == "/" {
filename = "index.md"
}
markdown, err := ioutil.ReadFile(filepath.Join(ROOT, filename))
if err != nil {
var status int
if os.IsNotExist(err) {
status = 404
} else {
status = 500
}
http.Error(w, err.Error(), status)
return
}
fmt.Fprintf(w, "%s", blackfriday.MarkdownCommon(markdown))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment