summaryrefslogtreecommitdiff
path: root/tags.go
blob: caffd4a5bab4ce758441715e210d727245fbcd74 (plain)
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
// Should be compiled to binary to be used as CGI script
package main

import (
	"fmt"
	"html"
	"io/fs"
	"net/url"
	"os"
	"path/filepath"
	"regexp"
	"strings"
)

func extractTitle(content string) string {
	titleRegex := regexp.MustCompile(`(?i)<title>(.*?)</title>`)
	matches := titleRegex.FindStringSubmatch(content)
	if len(matches) > 1 {
		return matches[1]
	}
	return "Без названия"
}

func main() {
	// CGI header
	fmt.Println("Content-Type: text/html; charset=utf-8")
	fmt.Println()

	// Получаем query string из окружения
	rawQuery := os.Getenv("QUERY_STRING")
	values, _ := url.ParseQuery(rawQuery)
	tag := values.Get("tag")
	if tag == "" {
		fmt.Println("<p>Error: no tag specified</p>")
		return
	}

	postsDir := "../posts"
	tagRegex := regexp.MustCompile(`data-tag="` + regexp.QuoteMeta(tag) + `"`)

	type Post struct {
		Path  string
		Title string
	}

	var matches []Post

	filepath.WalkDir(postsDir, func(path string, d fs.DirEntry, err error) error {
		if err != nil {
			return nil
		}
		if !d.IsDir() {
			contentBytes, err := os.ReadFile(path)
			if err == nil && tagRegex.Match(contentBytes) {
				content := string(contentBytes)
				title := extractTitle(content)
				relPath := "/posts/" + filepath.Base(path)
				matches = append(matches, Post{Path: relPath, Title: title})
			}
		}
		return nil
	})

	// Составляем <ul>
	var b strings.Builder
	b.WriteString("<ul>\n")
	for _, post := range matches {
		fmt.Fprintf(&b, "<li><a class=\"text-sm underline\" href=\"%s\">%s</a></li>\n",
			html.EscapeString(post.Path),
			html.EscapeString(post.Title))
	}
	b.WriteString("</ul>")

	// Читаем шаблон
	templateBytes, err := os.ReadFile("../templates/tags.html")
	if err != nil {
		fmt.Println("<p>Error: template not found</p>")
		return
	}
	template := string(templateBytes)

	// Заменяем маркеры
	output := strings.Replace(template, "<!-- %cgi.list% -->", b.String(), 1)
	output = strings.Replace(output, "<!-- %cgi.tag% -->", html.EscapeString(tag), 1)

	// Отдаём результат
	fmt.Print(output)
}