/
main.go
93 lines (84 loc) · 1.86 KB
/
main.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package main
import (
"flag"
"fmt"
"html/template"
"log"
"net/http"
"os"
"path/filepath"
"sort"
"code.google.com/p/go.talks/pkg/present"
)
type Doc struct {
*present.Doc
Path string
}
var (
docs []*Doc
docPaths = make(map[string]*Doc)
httpAddr = flag.String("http", ":8080", "HTTP listen address")
rTemplate = template.Must(template.ParseFiles("root.tmpl"))
pTemplate = template.Must(present.Template().ParseFiles("action.tmpl", "article.tmpl"))
)
func main() {
flag.Parse()
var err error
docs, err = loadDocs()
if err != nil {
log.Fatal(err)
}
for _, d := range docs {
d.Template = pTemplate
docPaths[d.Path] = d
}
http.HandleFunc("/", handler)
http.Handle("/static/", http.FileServer(http.Dir(".")))
log.Fatal(http.ListenAndServe(*httpAddr, nil))
}
func handler(w http.ResponseWriter, r *http.Request) {
var err error
if r.URL.Path == "/" {
err = rTemplate.Execute(w, docs)
} else {
doc, ok := docPaths[r.URL.Path[1:]]
if !ok {
http.Error(w, "not found", http.StatusNotFound)
return
}
err = pTemplate.ExecuteTemplate(w, "root", doc)
}
if err != nil {
log.Println(err)
fmt.Fprintln(w, err)
}
}
func loadDocs() ([]*Doc, error) {
var docs []*Doc
fn := func(path string, info os.FileInfo, err error) error {
if filepath.Ext(path) != ".article" {
return nil
}
f, err := os.Open(path)
if err != nil {
return err
}
defer f.Close()
d, err := present.Parse(f, filepath.Base(path), 0)
if err != nil {
return err
}
docs = append(docs, &Doc{d, path})
return nil
}
err := filepath.Walk(".", fn)
if err != nil {
return nil, err
}
sort.Sort(docsByTime(docs))
return docs, nil
}
type docsByTime []*Doc
func (s docsByTime) Len() int { return len(s) }
func (s docsByTime) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
func (s docsByTime) Less(i, j int) bool { return s[i].Time.After(s[j].Time) }