commit 175d7513af2bbf080d2ad815fb52854aee96af88 Author: NiseVoid Date: Sat Feb 25 16:00:54 2017 +0100 Initial commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..1bc7494 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +pages/ +static/ +template.html +mdsite diff --git a/main.go b/main.go new file mode 100644 index 0000000..a8b7eb4 --- /dev/null +++ b/main.go @@ -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))) +}