-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
184 lines (167 loc) · 4.04 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
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
173
174
175
176
177
178
179
180
181
182
183
184
package main
import (
"bytes"
"fmt"
"io"
"log"
"net/http"
"os"
"sync"
"golang.org/x/net/html"
)
func main() {
port := env("PORT", "5000")
http.Handle("/", &readium{})
http.ListenAndServe(":"+port, nil)
}
func env(name, fallback string) string {
if v, ok := os.LookupEnv(name); ok {
return v
}
return fallback
}
type readium struct {
client http.Client
mu sync.Mutex
cache map[string]*page
}
type page struct {
hits int
code int
content string
}
func (rd *readium) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if len(r.URL.Path) < 2 {
io.WriteString(w, `<!doctype html>Hello.`)
return
}
rd.mu.Lock()
defer rd.mu.Unlock()
p, ok := rd.cache[r.URL.Path]
if !ok {
resp, err := rd.client.Get("https://medium.com" + r.URL.Path)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer resp.Body.Close()
var b bytes.Buffer
b.WriteString(`<!doctype html><body>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style type="text/css">
body{ margin:40px auto; max-width:800px; line-height:1.6; font-size:18px; padding:0 10px; }
h1,h2,h3 { line-height:1.2 }
img { max-height: 400px; max-width: 400px; }
</style>
`)
out, _ := extract(resp.Body)
b.Write(out)
// Poor man's lru ¯\_(ツ)_/¯
if len(rd.cache) > 200 {
rd.cache = nil
}
if rd.cache == nil {
rd.cache = make(map[string]*page)
}
p = &page{
code: resp.StatusCode,
content: b.String(),
}
rd.cache[r.URL.Path] = p
}
p.hits++
w.Header().Add("x-cache-hits", fmt.Sprint(p.hits))
w.Header().Add("x-cache-size", fmt.Sprint(len(rd.cache)))
w.WriteHeader(p.code)
io.WriteString(w, p.content)
}
func extract(body io.Reader) ([]byte, error) {
var out bytes.Buffer
var (
inArticle bool
discardStack []string
)
z := html.NewTokenizer(body)
for {
switch z.Next() {
case html.ErrorToken:
return out.Bytes(), z.Err()
case html.TextToken:
if inArticle && len(discardStack) == 0 {
if _, err := out.Write(z.Text()); err != nil {
return out.Bytes(), fmt.Errorf("cannot write text: %w", err)
}
}
case html.SelfClosingTagToken:
t, _ := z.TagName()
switch tag := string(t); tag {
case "br", "img":
if inArticle && len(discardStack) == 0 {
var attrs []byte
for {
k, v, more := z.TagAttr()
if !more {
break
}
if _, ok := allowedTags[string(k)]; ok {
attrs = append(attrs, fmt.Sprintf(`%s="%s"`, k, v)...)
}
}
fmt.Fprintf(&out, "<%s %s>\n", tag, attrs)
}
default:
}
case html.StartTagToken:
t, _ := z.TagName()
switch tag := string(t); tag {
case "article":
inArticle = true
case "title", "p", "a", "em", "strong", "div", "span", "section", "h1", "h2", "h3", "blockquote", "figure", "figcaption", "pre", "code":
if inArticle && len(discardStack) == 0 {
var attrs []byte
for {
k, v, more := z.TagAttr()
if !more {
break
}
if _, ok := allowedTags[string(k)]; ok {
attrs = append(attrs, fmt.Sprintf(`%s="%s"`, k, v)...)
}
}
fmt.Fprintf(&out, "<%s %s>\n", tag, attrs)
}
default:
if inArticle {
discardStack = append(discardStack, string(tag))
}
}
case html.EndTagToken:
switch tag, _ := z.TagName(); string(tag) {
case "article":
inArticle = false
case "title", "p", "a", "em", "strong", "div", "span", "section", "h1", "h2", "h3", "blockquote", "figure", "figcaption", "pre", "code":
if inArticle && len(discardStack) == 0 {
fmt.Fprintf(&out, "</%s>\n", tag)
}
default:
if inArticle {
if len(discardStack) == 0 {
log.Printf("cannot discard %q: empty stack", tag)
} else {
if last := discardStack[len(discardStack)-1]; last != string(tag) {
log.Printf("cannot discard %q: stack is %q", tag, discardStack)
} else {
discardStack = discardStack[:len(discardStack)-1]
}
}
}
}
}
}
}
var allowedTags = map[string]struct{}{
"src": struct{}{},
"title": struct{}{},
"role": struct{}{},
"href": struct{}{},
}