2017-02-25 16:00:54 +01:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
2017-06-02 21:41:14 +02:00
|
|
|
"flag"
|
2017-02-25 16:00:54 +01:00
|
|
|
"html/template"
|
|
|
|
"io/ioutil"
|
|
|
|
"log"
|
|
|
|
"net/http"
|
|
|
|
"os"
|
|
|
|
"path"
|
|
|
|
"strconv"
|
|
|
|
"strings"
|
|
|
|
|
|
|
|
"github.com/russross/blackfriday"
|
|
|
|
)
|
|
|
|
|
2017-02-25 16:05:03 +01:00
|
|
|
func main() {
|
2017-06-02 21:41:14 +02:00
|
|
|
loadConfig()
|
2017-02-25 16:05:03 +01:00
|
|
|
|
|
|
|
if err := updateTemplate(); err != nil {
|
2017-06-02 21:41:14 +02:00
|
|
|
log.Fatal(`Failed to load template. (` + err.Error() + `)`)
|
2017-02-25 16:05:03 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
log.Fatal(http.ListenAndServe(":"+strconv.Itoa(config.Port), http.HandlerFunc(serveRequest)))
|
|
|
|
}
|
|
|
|
|
2017-02-25 16:00:54 +01:00
|
|
|
var config struct {
|
2017-06-02 21:41:14 +02:00
|
|
|
Port int
|
|
|
|
Template string
|
|
|
|
Pages string
|
|
|
|
Static string
|
2017-02-25 16:00:54 +01:00
|
|
|
}
|
|
|
|
|
2017-06-02 21:41:14 +02:00
|
|
|
func loadConfig() {
|
|
|
|
flag.IntVar(&config.Port, `port`, 80, `The port mdsite will listen on`)
|
|
|
|
flag.StringVar(&config.Template, `template`, `template.html`, `The template used by mdsite`)
|
|
|
|
flag.StringVar(&config.Pages, `pages`, `pages`, `The OS path used when searching a page`)
|
|
|
|
flag.StringVar(&config.Static, `static`, `static`, `The OS path used for static resource`)
|
|
|
|
flag.Parse()
|
2017-02-25 16:00:54 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
var t *template.Template
|
|
|
|
|
|
|
|
func updateTemplate() error {
|
|
|
|
var err error
|
|
|
|
t, err = template.ParseFiles(config.Template)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func serveRequest(w http.ResponseWriter, r *http.Request) {
|
|
|
|
if strings.HasPrefix(r.URL.Path, `/static/`) {
|
2017-06-02 21:41:14 +02:00
|
|
|
path := path.Join(config.Static, path.Clean(strings.TrimPrefix(r.URL.Path, `/static/`)))
|
|
|
|
http.ServeFile(w, r, path)
|
2017-02-25 16:00:54 +01:00
|
|
|
return
|
|
|
|
}
|
|
|
|
servePage(w, r)
|
|
|
|
}
|
|
|
|
|
|
|
|
func servePage(w http.ResponseWriter, r *http.Request) {
|
2017-06-02 21:41:14 +02:00
|
|
|
p := path.Join(config.Pages, path.Clean(r.URL.Path))
|
2017-02-25 16:00:54 +01:00
|
|
|
|
|
|
|
s, err := os.Stat(p)
|
2017-06-02 21:41:14 +02:00
|
|
|
if err == nil && s.IsDir() {
|
2017-02-25 16:00:54 +01:00
|
|
|
if p[len(p)-1] != '/' {
|
|
|
|
p += `/`
|
|
|
|
}
|
|
|
|
p += `index`
|
|
|
|
}
|
|
|
|
|
|
|
|
c, err := ioutil.ReadFile(p + `.md`)
|
|
|
|
if err != nil {
|
|
|
|
w.WriteHeader(404)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
t.Execute(w, template.HTML(blackfriday.MarkdownCommon(c)))
|
|
|
|
}
|