-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathebin.go
More file actions
610 lines (526 loc) · 13.7 KB
/
ebin.go
File metadata and controls
610 lines (526 loc) · 13.7 KB
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
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
package main
import (
"bufio"
"errors"
"fmt"
"html/template"
"io"
"log"
"net/http"
"os"
"path/filepath"
"regexp"
"strings"
texttemplate "text/template"
"time"
)
type CollectionLink struct {
Name string
Path string
Image string
ImgCount int
}
type BlogPost struct {
Name string
ReadableDate string
Path string
Content template.HTML
Tags []string
// Used in RSS
PubDate string
Desc string
LastChange string
}
type DocumentMatch struct {
Name string
Path string
MatchingWords string
}
type PageData struct {
Links []CollectionLink
BlogPosts []BlogPost
SelectedTag string
Title string
ImageColumnOne []string
ImageColumnTwo []string
SinglePost bool
FoundDocuments []DocumentMatch
}
type FeedData struct {
LastPostTime string
LastChangeTime string
Posts []BlogPost
}
func main() {
fs := http.FileServer(http.Dir("./static"))
http.Handle("/static/", http.StripPrefix("/static/", fs))
http.HandleFunc("/", serveTemplate)
http.HandleFunc("/blog/", serveBlogPage)
http.HandleFunc("/blog/post/", serveBlogPost)
http.HandleFunc("/knaker/", redirectToKnaker)
http.HandleFunc("/query/", serveQuery)
http.HandleFunc("/rss/", serveRSS)
fmt.Println("Listening on :9001...")
err := http.ListenAndServe(":9001", nil)
if err != nil {
log.Fatal(err)
}
}
func serveTemplate(w http.ResponseWriter, r *http.Request) {
url := r.URL.Path
lp := filepath.Join("templates", "layout.html")
fp := filepath.Join("static", filepath.Clean(url))
if strings.HasPrefix(url, "/works/gallery/") && !strings.Contains(url, ".") {
serveGalleryPage(w, r)
} else {
// First try to serve from static folder
info, err := os.Stat(fp)
if err == nil {
// Serve static file
if !info.IsDir() {
http.ServeFile(w, r, fp)
} else {
// If static file does not exist try templates folder
tp := filepath.Join("templates", filepath.Clean(url), "index.html")
_, err := os.Stat(tp)
if err == nil {
// Add a / to the end of the URL if there isn't on already
if !strings.HasSuffix(url, "/") {
http.Redirect(w, r, url+"/", http.StatusMovedPermanently)
return
}
tmpl, err := template.ParseFiles(lp, tp)
if err != nil {
serveNotFound(w, r)
} else {
tmpl.ExecuteTemplate(w, "layout", nil)
}
} else {
if os.IsNotExist(err) {
// Try to serve directory contents
http.ServeFile(w, r, fp)
}
}
}
} else {
if os.IsNotExist(err) {
print("Couldn't find " + fp + "\n")
serveNotFound(w, r)
} else {
serveInternalError(w, r)
}
}
}
}
func serveQuery(w http.ResponseWriter, r *http.Request) {
data := PageData{}
searchQueryValue := r.FormValue("s")
if len(searchQueryValue) > 100 {
// Search query too long
data = PageData{
FoundDocuments: []DocumentMatch{
{
Name: "",
Path: "#",
MatchingWords: "Your query is too long. Please use at most 100 characters.",
},
},
}
} else {
// Perform search
search := strings.Split(searchQueryValue, " ")
found, err := findMatchingDocuments(search)
if err != nil {
serveInternalError(w, r)
return
}
data.FoundDocuments = found
if len(data.FoundDocuments) == 0 {
data = PageData{
FoundDocuments: []DocumentMatch{
{
Name: "",
Path: "#",
MatchingWords: "No results found for \"" + searchQueryValue + "\".",
},
},
}
}
}
lp := filepath.Join("templates", "layout.html")
tp := filepath.Join("templates", "query", "index.html")
tmpl, err := template.ParseFiles(lp, tp)
if err != nil {
serveInternalError(w, r)
return
}
err = tmpl.ExecuteTemplate(w, "layout", data)
if err != nil {
serveInternalError(w, r)
}
}
func findMatchingDocuments(search []string) (matches []DocumentMatch, err error) {
fp := "templates"
files := []string{}
err = filepath.Walk(fp, func(path string, info os.FileInfo, err error) error {
if strings.Contains(path, "index.html") {
files = append(files, path)
}
return nil
})
if err != nil {
return
}
matches = []DocumentMatch{}
for _, file := range files {
f, err := os.Open(file)
if err != nil {
return nil, err
}
defer f.Close()
parts := strings.Split(strings.Replace(file, "\\", "/", -1), "/")
title := strings.Title(parts[len(parts)-2])
matching := []string{}
// Match against text content
scanner := bufio.NewScanner(f)
scanner.Split(bufio.ScanWords)
for scanner.Scan() {
text := scanner.Text()
if strings.Contains(text, "{") || strings.Contains(text, "}") {
continue
}
for _, str := range search {
if strings.Contains(strings.ToLower(text), strings.ToLower(str)) {
matching = append(matching, text)
break
}
}
}
// Match against title
for _, str := range search {
if strings.Contains(strings.ToLower(title), strings.ToLower(str)) {
matching = append(matching, title)
break
}
}
// Clean up matches
for i, match := range matching {
re := regexp.MustCompile(`(.*\=\")|(\/\"\>$)|(\"\/\>$)|(\<\/.*\>$)|(</.*>)|("\>)|(,)`)
matching[i] = strings.TrimSpace(string(re.ReplaceAll([]byte(match), []byte(" "))))
}
if len(matching) > 0 {
if title == "Templates" {
title = "Home"
}
path := strings.TrimRight(strings.TrimLeft(strings.Replace(file, "\\", "/", -1), "templates\\"), ".index.html")
matches = append(matches, DocumentMatch{
Name: title,
Path: path,
MatchingWords: "Contains: " + strings.Join(matching, ", "),
})
}
}
return
}
func serveRSS(w http.ResponseWriter, r *http.Request) {
posts := blogPosts(w, r)
if posts == nil {
serveNotFound(w, r)
return
}
last := posts[len(posts)-1]
data := FeedData{
LastPostTime: last.PubDate,
LastChangeTime: last.LastChange,
Posts: posts,
}
tmpl := texttemplate.Must(texttemplate.ParseFiles("rss.xml"))
tmpl.ExecuteTemplate(w, "RSS", data)
}
func stringArrayHas(array []string, target string) bool {
for _, s := range array {
if s == target {
return true
}
}
return false
}
func serveBlogPage(w http.ResponseWriter, r *http.Request) {
lp := filepath.Join("templates", "layout.html")
tp := filepath.Join("templates", "blog", "index.html")
tmpl, err := template.ParseFiles(lp, tp)
if err != nil {
serveNotFound(w, r)
return
}
posts := blogPosts(w, r)
if posts == nil {
serveNotFound(w, r)
return
}
data := PageData{}
url := r.URL.Path
filtered := []BlogPost{}
tag := strings.Split(url, "/")[2]
if tag != "" {
data.SelectedTag = tag
for _, post := range posts {
if stringArrayHas(post.Tags, tag) {
filtered = append(filtered, post)
}
}
posts = filtered
}
// Reverse posts
for i, j := 0, len(posts)-1; i < j; i, j = i+1, j-1 {
posts[i], posts[j] = posts[j], posts[i]
}
data.BlogPosts = posts
err = tmpl.ExecuteTemplate(w, "layout", data)
if err != nil {
serveInternalError(w, r)
}
}
func serveBlogPost(w http.ResponseWriter, r *http.Request) {
location := filepath.Join("static", strings.ReplaceAll(strings.TrimLeft(r.URL.Path, "/"), "/post", ""))
lp := filepath.Join("templates", "layout.html")
tp := filepath.Join("templates", "blog", "index.html")
tmpl, err := template.ParseFiles(lp, tp)
if err != nil {
serveNotFound(w, r)
return
}
info, err := os.Stat(location)
if err != nil {
serveNotFound(w, r)
return
}
post, err := getBlogPostData(location, info)
if err != nil {
serveInternalError(w, r)
return
}
data := PageData{
BlogPosts: []BlogPost{post},
SinglePost: true,
}
err = tmpl.ExecuteTemplate(w, "layout", data)
if err != nil {
serveInternalError(w, r)
}
}
func blogPosts(w http.ResponseWriter, r *http.Request) []BlogPost {
fp := filepath.Join("static", "blog")
// Gather all blog posts in an array
posts := []BlogPost{}
// Walk through all files in blog folder
err := filepath.Walk(fp, func(path string, info os.FileInfo, err error) error {
// Only interested in folders
if !info.IsDir() {
return nil
}
// Skip the static/blog folder
baseFolder := filepath.Join("static", "blog")
if path == baseFolder {
return nil
}
post, err := getBlogPostData(path, info)
if err != nil {
serveInternalError(w, r)
return nil
}
posts = append(posts, post)
return nil
})
if err != nil {
serveInternalError(w, r)
}
return posts
}
func getBlogPostData(path string, info os.FileInfo) (BlogPost, error) {
name := info.Name()
contentPath := filepath.Join(path, "index.html")
file, err := os.Open(contentPath)
if err != nil {
return BlogPost{}, err
}
defer file.Close()
// Read entire blog post file
buf := new(strings.Builder)
_, err = io.Copy(buf, file)
if err != nil {
return BlogPost{}, err
}
// Create a sneak peak of the content
desc := buf.String()
// Remove HTML tags, tabs, and carriage returns
re := regexp.MustCompile(`(<div .*</div>)|(<.*>)|(</.*>)|(<.*/>)|(\t+)|(\r)`)
desc = strings.TrimSpace(string(re.ReplaceAll([]byte(desc), []byte(""))))
// Time format for XML
const rfc2822 = "Mon Jan 02 15:04:05 -0700 2006"
const blogFormat = "2006-01-02"
const readableFormat = "January 2, 2006"
timePublished, err := time.Parse(blogFormat, name)
if err != nil {
return BlogPost{}, err
}
pubDate := timePublished.Format(rfc2822)
readableDate := timePublished.Format(readableFormat)
tags, title := extractBlogPostTitleAndTags(contentPath)
return BlogPost{
Name: title,
Path: "https://ebinbellini.com/blog/post/" + name + "/",
Desc: desc,
Content: template.HTML(buf.String()),
Tags: tags,
ReadableDate: readableDate,
PubDate: pubDate,
LastChange: info.ModTime().Format(rfc2822),
}, nil
}
func extractBlogPostTitleAndTags(path string) (tags []string, title string) {
title = "No title"
tags = []string{}
file, err := os.Open(path)
if err != nil {
return nil, title
}
defer file.Close()
reader := bufio.NewReader(file)
for {
// Read line expected to contain title or start of tags
line, err := reader.ReadString('\n')
if err != nil || !strings.Contains(line, "<div") {
return tags, title
}
// Check if line contains title
re := regexp.MustCompile(`<div class="title">(.*)</div>`)
matches := re.FindStringSubmatch(line)
if len(matches) > 1 {
title = matches[1]
continue
}
if strings.Contains(line, `<div class="tags">`) {
for {
line, err = reader.ReadString('\n')
if err != nil && err != io.EOF {
break
}
// Return at the end of the tag container
if strings.Contains(line, `</div>`) {
return tags, title
}
// Get tag from within quotation marks
tags = append(tags, strings.Split(strings.Split(line, `"`)[1], "/")[2])
}
}
if title != "No title" && len(tags) > 0 {
return tags, title
}
}
}
func redirectToKnaker(w http.ResponseWriter, r *http.Request) {
// Add a / to the end of the URL if there isn't on already
url := r.URL.Path
suffix := ""
if !strings.HasSuffix(url, "/") {
suffix = "/"
}
// Redirect to the correct URL
http.Redirect(w, r, "/works"+r.URL.Path+suffix, http.StatusMovedPermanently)
}
func serveGalleryPage(w http.ResponseWriter, r *http.Request) {
url := r.URL.Path
lp := filepath.Join("templates", "layout.html")
if url == "/works/gallery/" {
tp := filepath.Join("templates", "works", "gallery", "index.html")
tmpl, err := template.ParseFiles(lp, tp)
if err != nil {
serveNotFound(w, r)
} else {
links := imageGalleryCollectionLinks(w, r)
data := PageData{
Links: links,
}
err := tmpl.ExecuteTemplate(w, "layout", data)
if err != nil {
serveInternalError(w, r)
return
}
}
} else {
tp := filepath.Join("templates", "works", "gallery", "template.html")
tmpl, err := template.ParseFiles(lp, tp)
if err != nil {
serveNotFound(w, r)
} else {
title := strings.Title(strings.Replace(strings.TrimSuffix(strings.TrimPrefix(url, "/works/"), "/"), "/", " > ", -1))
images, err := listGalleryImages(w, r)
if err != nil {
serveNotFound(w, r)
return
}
columnOne := images[:len(images)/2]
columnTwo := images[len(images)/2:]
data := PageData{
Title: title,
ImageColumnOne: columnOne,
ImageColumnTwo: columnTwo,
}
err = tmpl.ExecuteTemplate(w, "layout", data)
if err != nil {
serveInternalError(w, r)
return
}
}
}
}
func imageGalleryCollectionLinks(w http.ResponseWriter, r *http.Request) []CollectionLink {
fp := filepath.Join("static", "works", "gallery")
links := []CollectionLink{}
err := filepath.Walk(fp, func(path string, info os.FileInfo, err error) error {
name := info.Name()
file, err := os.Open(path)
images, _ := file.Readdirnames(0)
defer file.Close()
if !strings.Contains(name, ".") && name != "gallery" {
links = append(links, CollectionLink{
Name: strings.Title(name),
Path: name + "/",
Image: images[0],
ImgCount: len(images),
})
}
return nil
})
if err != nil {
serveInternalError(w, r)
}
return links
}
func listGalleryImages(w http.ResponseWriter, r *http.Request) ([]string, error) {
url := r.URL.Path
fp := filepath.Join("static", url)
files := []string{}
err := filepath.Walk(fp, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if strings.Contains(info.Name(), ".") {
files = append(files, info.Name())
}
return nil
})
if err != nil {
return nil, errors.New("Image gallery collection " + fp + " not found")
}
return files, nil
}
func serveNotFound(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
http.ServeFile(w, r, filepath.Join("templates", "404.html"))
}
func serveInternalError(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusInternalServerError)
http.ServeFile(w, r, filepath.Join("templates", "error.html"))
}