-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathblog.go
79 lines (65 loc) · 1.65 KB
/
blog.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package main
import (
"fmt"
"html/template"
"log"
"bytes"
"io/ioutil"
"net/http"
"path/filepath"
"github.com/gomarkdown/markdown"
)
var tpl struct {
index, article *template.Template
}
var docs map[string]template.HTML
type Context struct {
Article template.HTML
Request *http.Request
}
func init() {
TemplatePath := "templates/"
base := filepath.Join(TemplatePath, "base.gohtml")
index := filepath.Join(TemplatePath, "index.gohtml")
article := filepath.Join(TemplatePath, "article.gohtml")
tpl.index = template.Must(template.ParseFiles(base, index))
tpl.article = template.Must(template.ParseFiles(base, article))
files, err := ioutil.ReadDir("articles/")
if err != nil {
log.Fatalln(err)
}
docs = make(map[string]template.HTML)
for _, file := range files {
md , err := ioutil.ReadFile("articles/" + file.Name())
if err != nil {
log.Fatalln(err)
}
n := file.Name()[:len(file.Name())-3]
docs[n] = template.HTML(markdown.ToHTML(md, nil, nil))
}
}
func main() {
ip_port := ":8080"
http.HandleFunc("/",handler)
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("./static"))))
log.Println("Serving from " + ip_port)
http.ListenAndServe(ip_port, nil)
}
func handler(conn http.ResponseWriter,req *http.Request) {
var buf bytes.Buffer
log.Println(req.URL.String())
if val , ok := docs[req.URL.String()[1:]]; ok {
context := Context{val,req}
err := tpl.article.ExecuteTemplate(&buf, "base", context)
if err != nil {
log.Fatalln(err)
}
} else {
err := tpl.index.ExecuteTemplate(&buf, "base", docs)
if err != nil {
log.Fatalln(err)
}
}
body := buf.String()
fmt.Fprintf(conn, body)
}