-
Notifications
You must be signed in to change notification settings - Fork 1
/
wiki.go
75 lines (66 loc) · 1.7 KB
/
wiki.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
package roll
import (
"html/template"
"io"
"io/ioutil"
"log"
"net/http"
"path"
"github.com/gomarkdown/markdown"
"github.com/gomarkdown/markdown/ast"
"github.com/gomarkdown/markdown/html"
"github.com/gomarkdown/markdown/parser"
"github.com/gorilla/mux"
)
var ()
func (b *Bot) wikiHandler(w http.ResponseWriter, req *http.Request) {
vars := mux.Vars(req)
page, ok := vars["page"]
if !ok {
log.Println("No page variable")
http.NotFound(w, req)
return
}
f, err := b.openFile(path.Join("wiki", page+".md"))
if err != nil {
log.Printf("Can't find wiki page %s: %v", page, err)
http.NotFound(w, req)
return
}
data, err := ioutil.ReadAll(f)
if err != nil {
log.Printf("Can't read wiki page %s: %v", page, err)
http.NotFound(w, req)
return
}
title := ""
titleHook := func(w io.Writer, node ast.Node, entering bool) (ast.WalkStatus, bool) {
// Filter out Title blocks (ex: %Title) and save the title.
if h, ok := node.(*ast.Heading); ok {
for _, n := range h.GetChildren() {
if t, ok := n.(*ast.Text); ok && h.IsTitleblock {
title = string(t.Literal)
return ast.SkipChildren, true
}
}
}
return ast.GoToNext, false
}
mdExtensions := parser.CommonExtensions | parser.AutoHeadingIDs | parser.Titleblock
mdParser := parser.NewWithExtensions(mdExtensions)
opts := html.RendererOptions{
Flags: html.CommonFlags,
RenderNodeHook: titleHook,
}
renderer := html.NewRenderer(opts)
output := markdown.ToHTML(data, mdParser, renderer)
templateData := struct {
Title string
Body template.HTML
}{
title,
template.HTML(output),
}
var wikiTemplate = template.Must(template.ParseFiles("templates/wiki.html"))
wikiTemplate.Execute(w, templateData)
}