forked from golang101/golang101
/
golang101.go
563 lines (509 loc) · 14.3 KB
/
golang101.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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
package main
import (
"bytes"
"context"
"go/build"
"html/template"
"io/ioutil"
"log"
"net/http"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"sync"
"time"
)
type Go101 struct {
staticHandler http.Handler
articleResHandler http.Handler
isLocalServer bool
articlePages map[string][]byte
indexContent template.HTML
serverMutex sync.Mutex
theme string // default is "dark"
}
var go101 = &Go101{
staticHandler: http.StripPrefix("/static/", staticFilesHandler),
articleResHandler: http.StripPrefix("/article/res/", resFilesHandler),
isLocalServer: false, // may be modified later
articlePages: map[string][]byte{},
indexContent: retrieveIndexContent(),
}
func (go101 *Go101) ServeHTTP(w http.ResponseWriter, r *http.Request) {
group, item := "", ""
tokens := strings.SplitN(r.URL.Path, "/", 3)
if len(tokens) > 1 {
group = strings.ToLower(tokens[1])
if len(tokens) > 2 {
item = tokens[2]
}
}
switch go101.ConfirmLocalServer(isLocalRequest(r)); group {
case "static":
w.Header().Set("Cache-Control", "max-age=31536000") // one year
go101.staticHandler.ServeHTTP(w, r)
case "article":
item = strings.ToLower(item)
if strings.HasPrefix(item, "res/") {
w.Header().Set("Cache-Control", "max-age=31536000") // one year
go101.articleResHandler.ServeHTTP(w, r)
//} else if go101.IsLocalServer() && (strings.HasPrefix(item, "print-") || strings.HasPrefix(item, "pdf-")) {
// w.Header().Set("Cache-Control", "no-cache, private, max-age=0")
// idx := strings.IndexByte(item, '-')
// go101.RenderPrintPage(w, r, item[:idx], item[idx+1:])
} else if !go101.RedirectArticlePage(w, r, item) {
go101.RenderArticlePage(w, r, item)
}
case "":
http.Redirect(w, r, "/article/101.html", http.StatusTemporaryRedirect)
default:
http.Redirect(w, r, "/article/101.html", http.StatusNotFound)
}
}
func (go101 *Go101) ConfirmLocalServer(isLocal bool) {
go101.serverMutex.Lock()
if go101.isLocalServer != isLocal {
go101.isLocalServer = isLocal
if go101.isLocalServer {
unloadPageTemplates() // loaded in one init function
go101.articlePages = map[string][]byte{} // invalidate article caches
}
}
go101.serverMutex.Unlock()
}
func (go101 *Go101) IsLocalServer() (isLocal bool) {
go101.serverMutex.Lock()
isLocal = go101.isLocalServer
go101.serverMutex.Unlock()
return
}
func pullGolang101Project(wd string) {
<-time.After(time.Minute / 2)
gitPull(wd)
for {
<-time.After(time.Hour * 24)
gitPull(wd)
}
}
func (go101 *Go101) ArticlePage(file string) ([]byte, bool) {
go101.serverMutex.Lock()
page := go101.articlePages[file]
isLocal := go101.isLocalServer
go101.serverMutex.Unlock()
return page, isLocal
}
func (go101 *Go101) CacheArticlePage(file string, page []byte) {
go101.serverMutex.Lock()
go101.articlePages[file] = page
go101.serverMutex.Unlock()
}
//===================================================
// pages
//==================================================
type Article struct {
Content, Title, Index template.HTML
TitleWithoutTags string
Filename string
FilenameWithoutExt string
}
var schemes = map[bool]string{false: "http://", true: "https://"}
func (go101 *Go101) RenderArticlePage(w http.ResponseWriter, r *http.Request, file string) {
page, isLocal := go101.ArticlePage(file)
if page == nil {
article, err := retrieveArticleContent(file)
if err == nil {
article.Index = disableArticleLink(go101.indexContent, file)
pageParams := map[string]interface{}{
"Article": article,
"Title": article.TitleWithoutTags,
"Theme": go101.theme,
"IsLocalServer": isLocal,
"Value": func() func(string, ...interface{}) interface{} {
var kvs = map[string]interface{}{}
return func(k string, v ...interface{}) interface{} {
if len(v) == 0 {
return kvs[k]
}
kvs[k] = v[0]
return ""
}
}(),
}
t := retrievePageTemplate(Template_Article, !isLocal)
var buf bytes.Buffer
if err = t.Execute(&buf, pageParams); err == nil {
page = buf.Bytes()
} else {
page = []byte(err.Error())
}
} else if os.IsNotExist(err) {
page = []byte{} // blank page means page not found.
}
if !isLocal {
go101.CacheArticlePage(file, page)
}
}
if len(page) == 0 { // blank page means page not found.
log.Printf("文章%s未找到", file)
//w.Header().Set("Cache-Control", "no-cache, private, max-age=0")
http.Redirect(w, r, "/article/101.html", http.StatusNotFound)
return
}
if isLocal {
w.Header().Set("Cache-Control", "no-cache, private, max-age=0")
} else {
w.Header().Set("Cache-Control", "max-age=50000") // about 14 hours
}
w.Write(page)
}
const H1, _H1, MaxLen = "<h1>", "</h1>", 128
var TagSigns = [2]rune{'<', '>'}
func retrieveArticleContent(file string) (Article, error) {
article := Article{}
content, err := loadArticleFile(file)
if err != nil {
return article, err
}
article.Content = template.HTML(content)
article.Filename = file
article.FilenameWithoutExt = strings.TrimSuffix(file, ".html")
// retrieve titles
j, i := -1, strings.Index(string(article.Content), H1)
if i >= 0 {
i += len(H1)
j = strings.Index(string(article.Content[i:i+MaxLen]), _H1)
if j >= 0 {
article.Title = article.Content[i-len(H1) : i+j+len(_H1)]
article.Content = article.Content[i+j+len(_H1):]
k, s := 0, make([]rune, 0, MaxLen)
for _, r := range article.Title {
if r == TagSigns[k] {
k = (k + 1) & 1
} else if k == 0 {
s = append(s, r)
}
}
article.TitleWithoutTags = string(s)
}
}
if j < 0 {
log.Println("retrieveTitlesForArticle", article.FilenameWithoutExt, "failed")
}
return article, nil
}
func retrieveIndexContent() template.HTML {
page101, err := retrieveArticleContent("101.html")
if err != nil {
panic(err)
}
content := []byte(page101.Content)
start := []byte("<!-- index starts (don't remove) -->")
i := bytes.Index(content, start)
if i < 0 {
panic("index not found")
}
content = content[i+len(start):]
end := []byte("<!-- index ends (don't remove) -->")
i = bytes.Index(content, end)
if i < 0 {
panic("index not found")
}
content = content[:i]
comments := [][]byte{
[]byte("<!-- (to remove) for printing"),
[]byte("(to remove) -->"),
}
for _, cmt := range comments {
i = bytes.Index(content, cmt)
if i >= 0 {
filleBytes(content[i:i+len(cmt)], ' ')
}
}
return template.HTML(content)
}
var (
aEnd = []byte(`</a>`)
aHref = []byte(`href="`)
aID = []byte(`id="i-`)
)
func disableArticleLink(htmlContent template.HTML, page string) (r template.HTML) {
content := []byte(htmlContent)
aStart := []byte(`<a class="index" href="` + page + `">`)
i := bytes.Index(content, aStart)
if i >= 0 {
content := content[i:]
i = bytes.Index(content[len(aStart):], aEnd)
if i >= 0 {
i += len(aStart)
//filleBytes(content[:len(start)], 0)
//filleBytes(content[i:i+len(end)], 0)
k := bytes.Index(content, aHref)
if i >= 0 {
content[1] = 'b'
content[i+2] = 'b'
copy(content[k:], aID)
}
}
}
return template.HTML(content)
}
//const Anchor, _Anchor, LineToRemoveTag, endl = `<li><a class="index" href="`, `">`, `(to remove)`, "\n"
//const IndexContentStart, IndexContentEnd = `<!-- index starts (don't remove) -->`, `<!-- index ends (don't remove) -->`
//
//func (go101 *Go101) RenderPrintPage(w http.ResponseWriter, r *http.Request, printTarget, item string) {
// page, isLocal := go101.ArticlePage(item)
// if page == nil {
// var err error
// var pageParams map[string]interface{}
// switch item {
// case "book101":
// pageParams, err = buildBook101PrintParams()
// }
//
// if err == nil {
// if pageParams == nil {
// pageParams = map[string]interface{}{}
// }
// pageParams["PrintTarget"] = printTarget
// pageParams["IsLocalServer"] = isLocal
//
// t := retrievePageTemplate(Template_PrintBook, !isLocal)
// var buf bytes.Buffer
// if err = t.Execute(&buf, pageParams); err == nil {
// page = buf.Bytes()
// }
// }
// if err != nil {
// page = []byte(err.Error())
// }
// if !isLocal {
// go101.CacheArticlePage(item, page)
// }
// }
//
// // ...
// if len(page) == 0 { // blank page means page not found.
// log.Printf("print page %s is not found", item)
// //w.Header().Set("Cache-Control", "no-cache, private, max-age=0")
// http.Redirect(w, r, "/article/101.html", http.StatusNotFound)
// return
// }
//
// if isLocal {
// w.Header().Set("Cache-Control", "no-cache, private, max-age=0")
// } else {
// w.Header().Set("Cache-Control", "max-age=50000") // about 14 hours
// }
// w.Write(page)
//}
//
//func buildBook101PrintParams() (map[string]interface{}, error) {
// article, err := retrieveArticleContent("101.html")
// if err != nil {
// return nil, err
// }
//
// // get all index article content by removing some lines
// var builder strings.Builder
//
// content := string(article.Content)
// i := strings.Index(content, IndexContentStart)
// if i < 0 {
// err = errors.New(IndexContentStart + " not found")
// return nil, err
// }
// i += len(IndexContentStart)
// content = content[i:]
// i = strings.Index(content, IndexContentEnd)
// if i >= 0 {
// content = content[:i]
// }
//
// for range [1000]struct{}{} {
// i = strings.Index(content, LineToRemoveTag)
// if i < 0 {
// break
// }
// start := strings.LastIndex(content[:i], endl)
// if start >= 0 {
// builder.WriteString(content[:start])
// }
// end := strings.Index(content[i:], endl)
// content = content[i:]
// if end < 0 {
// end = len(content)
// }
// content = content[end:]
// }
// builder.WriteString(content)
//
// // the index article
// articles := make([]Article, 0, 100)
// article.FilenameWithoutExt = "101"
// article.Content = template.HTML(builder.String())
// articles = append(articles, article)
//
// // find all articles from links
// content = string(article.Content)
// for range [1000]struct{}{} {
// i = strings.Index(content, Anchor)
// if i < 0 {
// break
// }
// content = content[i+len(Anchor):]
// i = strings.Index(content, _Anchor)
// if i < 0 {
// break
// }
// article, err := retrieveArticleContent(content[:i])
// if err != nil {
// log.Printf("retrieve article %s error: %s", content[:i], err)
// } else {
// articles = append(articles, article)
// }
// content = content[i+len(_Anchor):]
// }
//
// return map[string]interface{}{"Articles": articles}, nil
//}
//===================================================
// templates
//==================================================
type PageTemplate uint
const (
Template_Article PageTemplate = iota
Template_PrintBook
Template_Redirect
NumPageTemplates
)
var pageTemplates [NumPageTemplates + 1]*template.Template
var pageTemplatesMutex sync.Mutex //
var pageTemplatesCommonPaths = []string{"web", "templates"}
func init() {
for i := range pageTemplates {
retrievePageTemplate(PageTemplate(i), true)
}
}
func retrievePageTemplate(which PageTemplate, cacheIt bool) *template.Template {
if which > NumPageTemplates {
which = NumPageTemplates
}
pageTemplatesMutex.Lock()
t := pageTemplates[which]
pageTemplatesMutex.Unlock()
if t == nil {
switch which {
case Template_Article:
t = parseTemplate(pageTemplatesCommonPaths, "article")
case Template_PrintBook:
t = parseTemplate(pageTemplatesCommonPaths, "pdf")
case Template_Redirect:
t = parseTemplate(pageTemplatesCommonPaths, "redirect")
default:
t = template.New("blank")
}
if cacheIt {
pageTemplatesMutex.Lock()
pageTemplates[which] = t
pageTemplatesMutex.Unlock()
}
}
return t
}
func unloadPageTemplates() {
pageTemplatesMutex.Lock()
for i := range pageTemplates {
pageTemplates[i] = nil
}
pageTemplatesMutex.Unlock()
}
//===================================================
// non-embedding
//===================================================
var staticFilesHandler_NonEmbedding = http.FileServer(http.Dir(filepath.Join(rootPath, "web", "static")))
var resFilesHandler_NonEmbedding = http.FileServer(http.Dir(filepath.Join(rootPath, "articles", "res")))
func loadArticleFile_NonEmbedding(file string) ([]byte, error) {
return ioutil.ReadFile(filepath.Join(rootPath, "articles", file))
}
func parseTemplate_NonEmbedding(commonPaths []string, files ...string) *template.Template {
cp := filepath.Join(commonPaths...)
ts := make([]string, len(files))
for i, f := range files {
ts[i] = filepath.Join(rootPath, cp, f)
}
return template.Must(template.ParseFiles(ts...))
}
func updateGolang101_NonEmbedding() {
pullGolang101Project(rootPath)
}
var rootPath, wdIsGo101ProjectRoot = findGo101ProjectRoot()
func findGo101ProjectRoot() (string, bool) {
if _, err := os.Stat(filepath.Join(".", "golang101.go")); err == nil {
return ".", true
}
for _, name := range []string{
"gitlab.com/golang101/golang101", "gitlab.com/Golang101/golang101",
"github.com/golang101/golang101", "github.com/Golang101/golang101",
} {
pkg, err := build.Import(name, "", build.FindOnly)
if err == nil {
return pkg.Dir, false
}
}
return ".", false
}
//===================================================
// utils
//===================================================
func filleBytes(s []byte, b byte) {
for i := range s {
s[i] = b
}
}
func openBrowser(url string) error {
var cmd string
var args []string
switch runtime.GOOS {
case "windows":
cmd = "cmd"
args = []string{"/c", "start"}
case "darwin":
cmd = "open"
default: // "linux", "freebsd", "openbsd", "netbsd"
cmd = "xdg-open"
}
return exec.Command(cmd, append(args, url)...).Start()
}
func isLocalRequest(r *http.Request) bool {
end := strings.Index(r.Host, ":")
if end < 0 {
end = len(r.Host)
}
hostname := r.Host[:end]
return hostname == "localhost" // || hostname == "127.0.0.1" // 127.* for local cached version now
}
func runShellCommand(timeout time.Duration, wd string, cmd string, args ...string) ([]byte, error) {
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
command := exec.CommandContext(ctx, cmd, args...)
command.Dir = wd
return command.Output()
}
func gitPull(wd string) {
output, err := runShellCommand(time.Minute/2, wd, "git", "pull")
if err != nil {
log.Println("git pull:", err)
} else {
log.Printf("git pull: %s", output)
}
}
func goGet(pkgPath, wd string) {
_, err := runShellCommand(time.Minute/2, wd, "go", "get", "-u", pkgPath)
if err != nil {
log.Println("go get -u "+pkgPath+":", err)
} else {
log.Println("go get -u " + pkgPath + " succeeded.")
}
}