Browse Source

Initial commit

master
Nise Void 4 years ago
commit
175d7513af
  1. 4
      .gitignore
  2. 91
      main.go

4
.gitignore

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

91
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)))
}
Loading…
Cancel
Save