87 lines
1.9 KiB
Go
87 lines
1.9 KiB
Go
package main
|
|
|
|
import (
|
|
"flag"
|
|
"fmt"
|
|
"io/ioutil"
|
|
"log"
|
|
"net/http"
|
|
"os"
|
|
"os/signal"
|
|
"path"
|
|
"strings"
|
|
|
|
"github.com/gomarkdown/markdown"
|
|
"github.com/miekg/mmark"
|
|
"gopkg.in/russross/blackfriday.v2"
|
|
)
|
|
|
|
const (
|
|
GOMARKDOWN = "gomarkdown"
|
|
RUSSROSS = "russross"
|
|
MIEKG = "miekg"
|
|
)
|
|
|
|
func envOrDefault(key, def string) string {
|
|
if v := os.Getenv(key); v != "" {
|
|
return v
|
|
}
|
|
return def
|
|
}
|
|
|
|
func main() {
|
|
port := flag.String("p", envOrDefault("PORT", ":41913"), "port to run on")
|
|
root := flag.String("root", envOrDefault("ROOT", "."), "root dir to serve")
|
|
render := flag.String("render", envOrDefault("RENDER", GOMARKDOWN), "renderer to use")
|
|
flag.Parse()
|
|
|
|
if !strings.HasPrefix(*port, ":") {
|
|
*port = ":" + *port
|
|
}
|
|
|
|
go func() {
|
|
log.Printf("Serving %q on %q", *root, *port)
|
|
if err := http.ListenAndServe(*port, handler(*render, *root)); err != nil {
|
|
panic(err)
|
|
}
|
|
}()
|
|
|
|
// catch stop
|
|
stop := make(chan os.Signal)
|
|
signal.Notify(stop, os.Interrupt)
|
|
<-stop
|
|
}
|
|
|
|
func handler(code, root string) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
path := path.Join(root, path.Clean(r.URL.Path))
|
|
content, err := ioutil.ReadFile(path)
|
|
if err != nil {
|
|
http.NotFound(w, r)
|
|
return
|
|
}
|
|
fmt.Fprintln(w, `<html>`)
|
|
fmt.Fprintln(w, `<head>`)
|
|
fmt.Fprintln(w, `
|
|
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/kognise/water.css@latest/dist/dark.min.css">
|
|
`)
|
|
fmt.Fprintln(w, `</head>`)
|
|
fmt.Fprintln(w, `<body>`)
|
|
w.Write(render(code, content))
|
|
fmt.Fprintln(w, `</body>`)
|
|
fmt.Fprintln(w, `</html>`)
|
|
})
|
|
}
|
|
|
|
func render(code string, content []byte) []byte {
|
|
switch code {
|
|
case GOMARKDOWN:
|
|
return markdown.ToHTML(content, nil, nil)
|
|
case RUSSROSS:
|
|
return blackfriday.Run(content) //, blackfriday.WithExtensions(blackfriday.Extensions(blackfriday.TOC)))
|
|
case MIEKG:
|
|
return mmark.Parse(content, mmark.HtmlRenderer(0, ``, ``), mmark.EXTENSION_TABLES|int(blackfriday.TOC)).Bytes()
|
|
}
|
|
return nil
|
|
}
|