-
Notifications
You must be signed in to change notification settings - Fork 0
/
go-mddocdb.go
172 lines (156 loc) · 3.82 KB
/
go-mddocdb.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
package mddocdb
import (
"io"
"log"
"net/http"
"regexp"
"strings"
"text/template"
"time"
"github.com/gomarkdown/markdown"
"github.com/gomarkdown/markdown/parser"
"github.com/hashicorp/go-memdb"
)
var (
extensions = parser.CommonExtensions | parser.AutoHeadingIDs | parser.NonBlockingSpace
titleregex = regexp.MustCompile(`<h1 id=".*?">(.*?)</h1>`)
)
type Options struct {
CacheDuration time.Duration
Template *template.Template
Logger *log.Logger
}
type FS interface {
OpenRead(key string) (io.Reader, error)
}
func must(err error) {
if err != nil {
panic(err)
}
}
func respond(w http.ResponseWriter, statusCode int) {
w.WriteHeader(statusCode)
w.Write([]byte(http.StatusText(statusCode)))
}
type docTxn struct {
*memdb.Txn
}
type CachedDocument struct {
Key string
Document []byte
CreatedAt time.Time
}
func (d docTxn) get(key string) (*CachedDocument, error) {
doc, err := d.First("docs", "id", key)
if err != nil && err != memdb.ErrNotFound {
return nil, err
} else if doc == nil {
return nil, nil
} else {
return doc.(*CachedDocument), nil
}
}
func (d docTxn) replace(before *CachedDocument, after *CachedDocument) error {
if before != nil {
err := d.Delete("docs", before)
if err != nil && err != memdb.ErrNotFound {
return err
}
}
return d.Insert("docs", after)
}
func GetHandler(fs FS, basepath string, opts *Options) http.Handler {
db, err := memdb.NewMemDB(&memdb.DBSchema{
Tables: map[string]*memdb.TableSchema{
"docs": &memdb.TableSchema{
Name: "docs",
Indexes: map[string]*memdb.IndexSchema{
"id": &memdb.IndexSchema{
Name: "id",
Unique: true,
Indexer: &memdb.StringFieldIndex{Field: "Key"},
},
},
},
},
})
must(err)
l := opts.Logger
if l == nil {
l = log.Default()
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
key := r.URL.Path
if key[:len(basepath)] == basepath {
key = key[len(basepath):]
}
key = key + ".md"
if key[0] == '/' {
key = key[1:]
}
tx := docTxn{db.Txn(true)}
defer tx.Commit()
doc, err := tx.get(key)
if err != nil {
l.Printf("error fetching document from cache: %s", err.Error())
respond(w, http.StatusInternalServerError)
return
} else if doc != nil && time.Now().Sub(doc.CreatedAt) < opts.CacheDuration {
// already in cache and usable
w.Header().Set("Server-Timing", "cachehit")
w.WriteHeader(http.StatusOK)
w.Write(doc.Document)
return
}
// not in cache; fetch from FS, replace
reader, err := fs.OpenRead(key)
if err != nil {
l.Printf("error fetching file from storage: %s", err.Error())
respond(w, http.StatusInternalServerError)
return
} else if reader == nil {
l.Printf("file not found in storage: %s", key)
respond(w, http.StatusNotFound)
return
}
bytes, err := io.ReadAll(reader)
if err != nil {
l.Printf("error reading data from file: %s", err.Error())
respond(w, http.StatusInternalServerError)
return
}
html := markdown.ToHTML(bytes, parser.NewWithExtensions(extensions), nil)
match := titleregex.FindSubmatch(html)
title := ""
if match != nil && len(match) > 1 {
title = string(match[1])
}
sb := &strings.Builder{}
err = opts.Template.Execute(sb, struct {
Document string
Title string
}{
Document: string(html),
Title: title,
})
if err != nil {
l.Printf("error rendering template: %s", err.Error())
respond(w, http.StatusInternalServerError)
return
}
w.Header().Set("Server-Timing", "cachemiss")
w.WriteHeader(http.StatusOK)
w.Write([]byte(sb.String()))
doc2 := &CachedDocument{
Key: key,
Document: []byte(sb.String()),
CreatedAt: time.Now(),
}
err = tx.replace(doc, doc2)
if err != nil {
l.Printf("error rendering updating cache: %s", err.Error())
respond(w, http.StatusInternalServerError)
return
}
})
}