Initial commit

This commit is contained in:
Nise Void 2017-02-25 16:00:54 +01:00
commit 175d7513af
2 changed files with 95 additions and 0 deletions

4
.gitignore vendored Normal file
View File

@ -0,0 +1,4 @@
pages/
static/
template.html
mdsite

91
main.go Normal file
View File

@ -0,0 +1,91 @@
package main
import (
"encoding/json"
"html/template"
"io/ioutil"
"log"
"net/http"
"os"
"path"
"strconv"
"strings"
"github.com/russross/blackfriday"
)
var config struct {
Port int `json:"port"`
Template string `json:"template"`
}
func main() {
// Open config
f, err := os.Open(`config.json`)
if err != nil && !os.IsNotExist(err) {
log.Fatal(`Failed to open config. ` + err.Error())
}
// Set defaults
config.Port = 80
config.Template = `template.html`
// Parse config
if err == nil {
err = json.NewDecoder(f).Decode(&config)
if err != nil {
log.Fatal(`Could not parse config. ` + err.Error())
}
}
if err := updateTemplate(); err != nil {
log.Fatal(`Failed to load template. ` + err.Error())
}
log.Fatal(http.ListenAndServe(":"+strconv.Itoa(config.Port), http.HandlerFunc(serveRequest)))
}
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/`) {
p, _ := os.Getwd()
p = path.Join(p, r.URL.Path)
http.ServeFile(w, r, p)
return
}
servePage(w, r)
}
func servePage(w http.ResponseWriter, r *http.Request) {
p := `pages` + path.Clean(r.URL.Path)
s, err := os.Stat(p)
if err != nil {
w.WriteHeader(404)
return
}
if s.IsDir() {
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)))
}