From 78b410c668354c30323a259167beb7eddaa2d58f Mon Sep 17 00:00:00 2001 From: Sebastian Zack Tin Lahm-Lee Date: Sun, 4 Oct 2026 12:58:12 +0800 Subject: first ver --- README.md | 156 ++++++++++++++++++++++ convert.go | 430 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ feed.go | 78 +++++++++++ go.mod | 3 + main.go | 291 ++++++++++++++++++++++++++++++++++++++++ ratelimit.go | 59 ++++++++ render.go | 134 +++++++++++++++++++ site.go | 378 +++++++++++++++++++++++++++++++++++++++++++++++++++ 8 files changed, 1529 insertions(+) create mode 100644 README.md create mode 100644 convert.go create mode 100644 feed.go create mode 100644 go.mod create mode 100644 main.go create mode 100644 ratelimit.go create mode 100644 render.go create mode 100644 site.go diff --git a/README.md b/README.md new file mode 100644 index 0000000..a67f90d --- /dev/null +++ b/README.md @@ -0,0 +1,156 @@ +# mingyuet-server + +A minimal blogging server for **明月樓閒話 Mingyuet Comments**. + +You keep writing raw HTML — but only the *content* of each post. The server +wraps it in the site layout (the table shell with the sidebar and footer +that every page used to carry by hand), generates the index and archive +pages, gives every post a permalink, and produces an RSS feed. No database: +the content *is* the file system. No third-party Go dependencies either — +just the standard library. + +One binary, two subcommands: + +``` +mingyuet-server convert [flags] one-time migration from the old static site +mingyuet-server serve [flags] run the server +``` + +## Content root layout + +``` +/ + posts/*.html dated post fragments (your blog entries) + pages/*.html standalone page fragments (About, Special, Releases, ...) + static/* served verbatim (style.css, images, robots.txt, assets/, ...) + layout.html optional override of the embedded layout template +``` + +### Post fragments (`posts/`) + +A fragment is plain HTML — exactly what used to live *inside* a +`
` — plus a few optional meta comments on their own +lines at the top of the file: + +```html + + + + (only needed if the filename isn't a date) + (optional; affects the pubDate in the RSS feed) +

Your content. The date line is generated for you — don't write it; + on listing pages it's a link to the post's own page.

+ +

Everything after the marker only appears on the post's own page.

+``` + +* **File name = date.** `20261004.html` → dated 2026.10.4. To publish, just + drop the file into `posts/`; it appears within a few seconds + (`-scan-interval`), no restart needed. +* **Several posts on one date:** give them suffixes in the order you want + them listed (newest first): `20261004-2.html` is listed *above* + `20261004-1.html`. If there is only one post that day, no suffix. +* **`title:`** renders as the `

` on both the listing and the post page + (and in `` / RSS, tag-stripped). Omit it for untitled entries. +* **`<!-- more -->`** splits excerpt from body. The listing page shows the + excerpt followed by a `>>> More` link to the post page; without the marker + the full content is shown inline, like the old short entries. +* **`time:`** sets the post's clock time, used in the RSS `pubDate` + (without it the post is dated midnight UTC). Format: `HH:MM` or + `HH:MM:SS`, optionally followed by a zone — an IANA name + (`Asia/Hong_Kong`, `Europe/Dublin` — DST is applied for the post's + date, and the binary carries its own tz database so this works on any + host), `UTC`, or a fixed offset (`+08`, `+08:00`, `-0530`). No zone + means UTC. The site pages themselves keep showing just the date. +* **`id:`** is the `id=` attribute of the entry `<div>` on listing pages + (used to preserve old `#pNN` anchors). Defaults to the filename stem. +* **`alias:`** makes `/articles/<alias>.html` redirect to this post — used + to keep old inbound article links alive. +* Use absolute paths for assets inside content (`/assets/...`), since + fragments render at several URL depths. + +### Page fragments (`pages/`) + +Mapped 1:1 to URLs: `pages/about.html` → `/about.html`, +`pages/special/beatles.html` → `/special/beatles.html`. Optional +`<!-- title: ... -->` sets the `<title>` suffix (e.g. `About`, or +`Higgins's Guide to the Beatles :: Special`). Content renders inside the +same layout. + +## URL map + +| URL | What | +|---|---| +| `/` (also `/index.html`) | newest `-page-size` posts + link to older collection | +| `/archives/01.html`, `/archives/02.html`, ... | auto-generated older collections | +| `/post/<name>.html` | permalink for one post (every post has one, titled or not) | +| `/articles/<name>.html` | **301** to `/post/<name>.html` — matched by name *or* `alias:` | +| `/feed.xml` (alias `/rss.xml`) | RSS 2.0, newest `-feed-items` posts; item title = `title:` meta or the date, description = post HTML, cut off after `-feed-maxlen` characters with a `(more on the source page)` note | +| `/<pages path>` | page fragments | +| anything else | looked up in `static/`, otherwise a themed 404 | + +## Migrating the old site (`convert`) + +``` +go build -o mingyuet-server . +./mingyuet-server convert -src /path/to/old/site -dst /path/to/content-root +./mingyuet-server serve -site /path/to/content-root -addr :8080 \ + -base-url https://your.domain +``` + +The converter reads `index.html` and `archives/*.html`, extracts every +`<div id="pNN" class="entry">` block, and merges each `>>> More` / +`>> Read More` pointer with the article page it pointed to (the article's +body becomes the post's post-page content; the old entry keeps its `pNN` +id and gets an `alias:` for the article URL). Pages (`about.html`, +`special.html`, `releases.html`, `special/*.html`) become fragments and +static assets are copied (`assets/`, `releases/`, root-level non-HTML +files). The source tree is never modified; it also prints a report of +what went where and skips any article no entry points at. + +Notes: + +* Relative links inside content (`./assets/…`, `../assets/…`) are + rewritten to absolute `/assets/…` — fragments render at mixed depths + now. (This also fixes links that were already broken on the old + archive page.) +* Same-date entries get `-1`/`-2` suffixes arranged to preserve the + original display order. +* With the current content this yields 43 posts; the index shows the + same 22 entries as before and `archives/01.html` the same 21. +* Orphan article `20251108.html` / `20251121.html` are reported and + skipped: nothing links to them (their live counterparts are the + `special/` pages, which the converter does import). + +## Running (`serve`) + +| Flag | Default | Meaning | +|---|---|---| +| `-addr` | `:8080` | listen address | +| `-site` | `./site` | content root | +| `-base-url` | `http://localhost:8080` | public URL used for RSS links | +| `-page-size` | `22` | posts per page (matches the old index) | +| `-feed-items` | `25` | RSS items | +| `-feed-maxlen` | `2000` | cut RSS descriptions longer than this many characters, ending with a `(more on the source page)` note (0 = never cut) | +| `-rate` | `60` | max requests per client IP per `-rate-window` | +| `-rate-window` | `1m` | rate limit window | +| `-trust-proxy` | off | take client IP from `X-Forwarded-For` (use **only** behind your own reverse proxy, otherwise clients can spoof it) | +| `-scan-interval` | `5s` | how often to rescan `posts/` and `pages/` | + +### Anti-abuse rate limiting + +Every request counts against a fixed per-IP window (`-rate` requests per +`-rate-window`, default 60/minute). Over the limit the server answers +`429 Too Many Requests` with a `Retry-After` header until the window rolls +over. State is in memory only. If you run behind nginx/caddy/etc., pass +`-trust-proxy` so the limit applies to real client IPs rather than the +proxy's. + +### Layout override + +Drop a `layout.html` into the content root to change the site shell (the +embedded default replicates the original hand-written one, plus an RSS +`<link>` in `<head>`). It must use the `{{.FullTitle}}`, `{{.Root}}` and +`{{.Content}}` template actions. `{{.Root}}` is the correct relative prefix +for the page's depth (`./`, `../`, ...), so the same template works at any +depth. \ No newline at end of file diff --git a/convert.go b/convert.go new file mode 100644 index 0000000..1673785 --- /dev/null +++ b/convert.go @@ -0,0 +1,430 @@ +package main + +import ( + "flag" + "fmt" + "io/fs" + "os" + "path/filepath" + "regexp" + "sort" + "strconv" + "strings" + "time" +) + +// runConvert is a one-time migrator for the old hand-written static site. +// It reads <src>/index.html and <src>/archives/*.html, extracts every +// <div id="pNN" class="entry"> block, merges each ">>> More / Read More" +// pointer with the article page it points to, and writes post fragments +// into <dst>/posts/. The boilerplate pages (about/special/releases and +// special/*) become page fragments, and static assets are copied to +// <dst>/static/. The source tree is never modified. +// +// It also rewrites the relative links inside content ("./assets/..." and +// "../assets/...") into absolute form ("/assets/..."), because fragments +// are now rendered at different URL depths than the old static pages; this +// incidentally fixes a few links that were already broken on the old site. +// Internal anchors like href="#p1" keep working because each converted +// post keeps its original id via an `id:` meta comment. + +type convEntry struct { + id string + title string + date time.Time + excerpt string + article string // basename of the article page this entry points to, or "" + articleBody string + suffix int +} + +var ( + entryOpenRe = regexp.MustCompile(`<div id="(p\d+)" class="entry">`) + divTokenRe = regexp.MustCompile(`<div\b|</div>`) + h1Re = regexp.MustCompile(`(?s)<h1[^>]*>(.*?)</h1>`) + datePRe = regexp.MustCompile(`^<p>\s*(\d{4})\.(\d{1,2})\.(\d{1,2})\s*</p>`) + dateBareRe = regexp.MustCompile(`^(\d{4})\.(\d{1,2})\.(\d{1,2})(?:\s|$)`) + // ">>> MORE" / ">>> More" / ">> Read More" links to ./ or ../articles/ + articleLinkRe = regexp.MustCompile(`(?s)<p>\s*<a href="(?:\./|\.\./)?articles/([0-9A-Za-z-]+\.html)">([^<]*>[^<]*)</a>\s*</p>`) + contentCellRe = regexp.MustCompile(`(?s)<td style="padding-left: 2em">\s*(.*?)\s*</td>`) + titleTagRe = regexp.MustCompile(`(?s)<title>(.*?)`) + backLinkRe = regexp.MustCompile(`(?s)\s*

\s*\s*Back\s*\s*

\s*$`) + subtitleRe = regexp.MustCompile(`(?s)^

\s*

`) +) + +var relRewrites = strings.NewReplacer( + `href="./`, `href="/`, + `href="../`, `href="/`, + `src="./`, `src="/`, + `src="../`, `src="/`, +) + +func rewriteRelative(s string) string { + return relRewrites.Replace(s) +} + +func parseYMD(y, m, d string) (time.Time, error) { + yy, err1 := strconv.Atoi(y) + mm, err2 := strconv.Atoi(m) + dd, err3 := strconv.Atoi(d) + if err1 != nil || err2 != nil || err3 != nil || mm < 1 || mm > 12 || dd < 1 || dd > 31 { + return time.Time{}, fmt.Errorf("bad date %s.%s.%s", y, m, d) + } + return time.Date(yy, time.Month(mm), dd, 0, 0, 0, 0, time.UTC), nil +} + +func runConvert(args []string) error { + fs := flag.NewFlagSet("convert", flag.ExitOnError) + src := fs.String("src", ".", "path of the old static site (the directory containing index.html)") + dst := fs.String("dst", "./site", "output content root (posts/, pages/, static/)") + fs.Parse(args) + + if _, err := os.Stat(filepath.Join(*src, "index.html")); err != nil { + return fmt.Errorf("cannot read %s/index.html: %w", *src, err) + } + postsDir := filepath.Join(*dst, "posts") + pagesDir := filepath.Join(*dst, "pages") + staticDir := filepath.Join(*dst, "static") + for _, d := range []string{postsDir, pagesDir, staticDir} { + if err := os.MkdirAll(d, 0o755); err != nil { + return err + } + } + + // 1. Collect entries from all listing pages (index first, then archives, + // which are already in newest-first order). + listings := []string{filepath.Join(*src, "index.html")} + archiveFiles, err := filepath.Glob(filepath.Join(*src, "archives", "*.html")) + if err != nil { + return err + } + sort.Strings(archiveFiles) + listings = append(listings, archiveFiles...) + var entries []convEntry + for _, f := range listings { + data, err := os.ReadFile(f) + if err != nil { + return err + } + entries = append(entries, extractEntries(string(data))...) + } + if len(entries) == 0 { + return fmt.Errorf("no entries found under %s", *src) + } + + // 2. Merge article bodies into the entries that point at them. + usedArticles := map[string]bool{} + for i := range entries { + e := &entries[i] + if e.article == "" { + continue + } + title, body, err := extractArticle(*src, e.article) + if err != nil { + return err + } + if e.title == "" { + e.title = title + } + e.articleBody = body + usedArticles[strings.TrimSuffix(e.article, ".html")] = true + } + + // 3. Assign filename suffixes so several posts on the same date keep + // their display order: within one date every post gets -N.html + // where newer posts have larger N (the listing sorts by descending + // filename within a date), matching the old listing order. + dateCount := map[string]int{} + for _, e := range entries { + dateCount[e.date.Format("20060102")]++ + } + seen := map[string]int{} + for i := range entries { + key := entries[i].date.Format("20060102") + seen[key]++ + entries[i].suffix = dateCount[key] - seen[key] + 1 + } + + // 4. Write post fragments. + fmt.Println("posts:") + for _, e := range entries { + fname := e.date.Format("20060102") + if dateCount[fname] > 1 { + fname += "-" + strconv.Itoa(e.suffix) + } + fname += ".html" + var b strings.Builder + fmt.Fprintf(&b, "\n", e.id) + if e.title != "" { + fmt.Fprintf(&b, "\n", e.title) + } + content := rewriteRelative(e.excerpt) + if e.article != "" { + fmt.Fprintf(&b, "\n", strings.TrimSuffix(e.article, ".html")) + b.WriteString("\n") + if content != "" { + b.WriteString(content) + b.WriteString("\n") + } + b.WriteString(rewriteRelative(e.articleBody)) + b.WriteString("\n") + fmt.Printf(" %-22s <- #%s (%s), article %s merged\n", fname, e.id, e.date.Format("2006.1.2"), e.article) + } else { + b.WriteString(content) + b.WriteString("\n") + fmt.Printf(" %-22s <- #%s (%s)\n", fname, e.id, e.date.Format("2006.1.2")) + } + if err := os.WriteFile(filepath.Join(postsDir, fname), []byte(b.String()), 0o644); err != nil { + return err + } + } + + // 5. Convert boilerplate pages into fragments. + fmt.Println("pages:") + pages := []string{"about.html", "special.html", "releases.html"} + specials, err := filepath.Glob(filepath.Join(*src, "special", "*.html")) + if err != nil { + return err + } + for _, sp := range specials { + rel, err := filepath.Rel(*src, sp) + if err != nil { + return err + } + pages = append(pages, filepath.ToSlash(rel)) + } + for _, rel := range pages { + data, err := os.ReadFile(filepath.Join(*src, filepath.FromSlash(rel))) + if err != nil { + fmt.Fprintf(os.Stderr, "warning: page %s: %v\n", rel, err) + continue + } + suffix, content, err := extractPage(data) + if err != nil { + fmt.Fprintf(os.Stderr, "warning: page %s: %v\n", rel, err) + continue + } + var b strings.Builder + if suffix != "" { + fmt.Fprintf(&b, "\n", suffix) + } + b.WriteString(rewriteRelative(content)) + b.WriteString("\n") + out := filepath.Join(pagesDir, filepath.FromSlash(rel)) + if err := os.MkdirAll(filepath.Dir(out), 0o755); err != nil { + return err + } + if err := os.WriteFile(out, []byte(b.String()), 0o644); err != nil { + return err + } + fmt.Printf(" /%s\n", rel) + } + + // 6. Copy static assets. + fmt.Println("static:") + nStatic := copyStatic(*src, staticDir) + + // 7. Report anything that was not referenced by any entry. + articleFiles, _ := filepath.Glob(filepath.Join(*src, "articles", "*.html")) + for _, a := range articleFiles { + stem := strings.TrimSuffix(filepath.Base(a), ".html") + if !usedArticles[stem] { + fmt.Printf(" skipped orphan article %s (no entry points to it; kept in source tree)\n", filepath.Base(a)) + } + } + fmt.Printf("\ndone: %d posts, %d pages, %d static files written to %s\n", len(entries), len(pages), nStatic, *dst) + return nil +} + +// extractEntries pulls every
block out of a +// listing page, honouring div nesting when finding the matching
. +func extractEntries(src string) []convEntry { + var out []convEntry + for _, loc := range entryOpenRe.FindAllStringSubmatchIndex(src, -1) { + id := src[loc[2]:loc[3]] + start := loc[1] + end := -1 + depth := 1 + for _, tok := range divTokenRe.FindAllStringIndex(src[start:], -1) { + if strings.HasPrefix(src[start+tok[0]:], "

") { + depth-- + } else { + depth++ + } + if depth == 0 { + end = start + tok[0] + break + } + } + if end < 0 { + fmt.Fprintf(os.Stderr, "warning: entry #%s: unbalanced divs, skipping the rest\n", id) + break + } + e, err := parseConvEntry(id, src[start:end]) + if err != nil { + fmt.Fprintf(os.Stderr, "warning: entry #%s: %v\n", id, err) + continue + } + out = append(out, e) + } + return out +} + +// parseConvEntry pulls the title (

, which may come before or after the +// date), the date (wrapped in

or bare text, as found in the archives) +// and the optional ">>> More" article pointer out of one entry. +func parseConvEntry(id, inner string) (convEntry, error) { + e := convEntry{id: id} + if m := h1Re.FindStringSubmatchIndex(inner); m != nil { + e.title = strings.TrimSpace(inner[m[2]:m[3]]) + inner = inner[:m[0]] + inner[m[1]:] + } + inner = strings.TrimSpace(inner) + var date time.Time + if m := datePRe.FindStringSubmatchIndex(inner); m != nil { + var err error + date, err = parseYMD(inner[m[2]:m[3]], inner[m[4]:m[5]], inner[m[6]:m[7]]) + if err != nil { + return e, err + } + inner = strings.TrimSpace(inner[m[1]:]) + } else if m := dateBareRe.FindStringSubmatchIndex(inner); m != nil { + var err error + date, err = parseYMD(inner[m[2]:m[3]], inner[m[4]:m[5]], inner[m[6]:m[7]]) + if err != nil { + return e, err + } + inner = strings.TrimSpace(inner[m[1]:]) + } else { + return e, fmt.Errorf("no date found") + } + e.date = date + if m := articleLinkRe.FindStringSubmatchIndex(inner); m != nil { + e.article = inner[m[2]:m[3]] + inner = inner[:m[0]] + inner[m[1]:] + } + e.excerpt = strings.TrimSpace(inner) + return e, nil +} + +// extractArticle returns the title and body of an old article page, with +// the surrounding boilerplate (h1, date, subtitle, "Back" link) removed. +func extractArticle(src, name string) (title, body string, err error) { + data, err := os.ReadFile(filepath.Join(src, "articles", name)) + if err != nil { + return "", "", err + } + m := contentCellRe.FindStringSubmatch(string(data)) + if m == nil { + return "", "", fmt.Errorf("articles/%s: content cell not found", name) + } + body = m[1] + if h := h1Re.FindStringSubmatchIndex(body); h != nil { + title = strings.TrimSpace(body[h[2]:h[3]]) + body = body[:h[0]] + body[h[1]:] + } + body = strings.TrimSpace(body) + body = subtitleRe.ReplaceAllString(body, "") + if dm := datePRe.FindStringSubmatchIndex(body); dm != nil { + body = strings.TrimSpace(body[dm[1]:]) + } else if dm := dateBareRe.FindStringSubmatchIndex(body); dm != nil { + body = strings.TrimSpace(body[dm[1]:]) + } + body = strings.TrimSpace(backLinkRe.ReplaceAllString(body, "")) + return title, body, nil +} + +// extractPage returns the suffix and the content cell of a +// boilerplate page. +func extractPage(data []byte) (suffix, content string, err error) { + suffix = "" + if m := titleTagRe.FindStringSubmatch(string(data)); m != nil { + suffix = strings.TrimSpace(m[1]) + suffix = strings.TrimSpace(strings.TrimSuffix(suffix, " :: 明月樓閒話 Mingyuet Comments")) + } + m := contentCellRe.FindStringSubmatch(string(data)) + if m == nil { + return "", "", fmt.Errorf("content cell not found") + } + return suffix, strings.TrimSpace(m[1]), nil +} + +// copyStatic copies the site's non-HTML assets: root-level files (style.css, +// images, robots.txt, ...) and the known asset directories (assets/, +// releases/). HTML files, editor backups (*~) and directories handled as +// content (archives/, articles/, special/) or code (server/) are excluded. +func copyStatic(src, dst string) int { + n := 0 + rootEntries, err := os.ReadDir(src) + if err != nil { + fmt.Fprintf(os.Stderr, "warning: reading %s: %v\n", src, err) + return 0 + } + assetDirs := map[string]bool{"assets": true, "releases": true} + for _, ent := range rootEntries { + name := ent.Name() + if ent.IsDir() { + if assetDirs[name] { + n += copyDir(filepath.Join(src, name), filepath.Join(dst, name)) + continue + } + fmt.Printf(" skipped directory %s/\n", name) + continue + } + if strings.HasSuffix(name, "~") || strings.HasSuffix(name, ".html") || strings.HasPrefix(name, ".") { + continue + } + if copyFile(filepath.Join(src, name), filepath.Join(dst, name)) { + fmt.Printf(" /%s\n", name) + n++ + } + } + return n +} + +func copyDir(src, dst string) int { + n := 0 + filepath.WalkDir(src, func(path string, d fs.DirEntry, err error) error { + if err != nil { + return nil + } + if d.IsDir() { + return os.MkdirAll(filepath.Join(dst, mustRel(src, path)), 0o755) + } + if strings.HasSuffix(path, "~") || strings.HasPrefix(d.Name(), ".") { + return nil + } + rel := mustRel(src, path) + if copyFile(path, filepath.Join(dst, rel)) { + fmt.Printf(" /%s\n", filepath.ToSlash(rel)) + n++ + } + return nil + }) + return n +} + +func copyFile(src, dst string) bool { + data, err := os.ReadFile(src) + if err != nil { + fmt.Fprintf(os.Stderr, "warning: %v\n", err) + return false + } + if err := os.MkdirAll(filepath.Dir(dst), 0o755); err != nil { + fmt.Fprintf(os.Stderr, "warning: %v\n", err) + return false + } + if err := os.WriteFile(dst, data, 0o644); err != nil { + fmt.Fprintf(os.Stderr, "warning: %v\n", err) + return false + } + return true +} + +func mustRel(base, target string) string { + rel, err := filepath.Rel(base, target) + if err != nil { + return filepath.Base(target) + } + return rel +} diff --git a/feed.go b/feed.go new file mode 100644 index 0000000..27e18be --- /dev/null +++ b/feed.go @@ -0,0 +1,78 @@ +package main + +import ( + "fmt" + "html" + "net/http" + "strings" + "time" +) + +// handleFeed serves an RSS 2.0 feed (/feed.xml, alias /rss.xml) generated +// from the newest posts. Item titles use the post's `title:` meta if it +// has one, otherwise the date. Descriptions carry the post's HTML, cut off +// with a pointer to the post page once they exceed -feed-maxlen characters. +func (s *Server) handleFeed(w http.ResponseWriter, r *http.Request) { + posts := s.site.Posts() + if len(posts) > s.feedItems { + posts = posts[:s.feedItems] + } + var b strings.Builder + b.WriteString(`<?xml version="1.0" encoding="UTF-8"?>` + "\n") + b.WriteString("<rss version=\"2.0\">\n<channel>\n") + fmt.Fprintf(&b, " <title>%s\n", xmlEsc(siteName)) + fmt.Fprintf(&b, " %s\n", xmlEsc(s.baseURL)) + b.WriteString(" Casual Words From The Moonlight Tower\n") + fmt.Fprintf(&b, " %s\n", time.Now().UTC().Format(time.RFC1123Z)) + for _, p := range posts { + title := p.TitleText + if title == "" { + title = p.DateStr + } + link := s.baseURL + "/post/" + p.Name + ".html" + var desc strings.Builder + if p.Title != "" { + fmt.Fprintf(&desc, "

%s

\n", p.Title) + } + fmt.Fprintf(&desc, "

%s

\n", p.DateStr) + desc.WriteString(string(p.Body)) + b.WriteString(" \n") + fmt.Fprintf(&b, " %s\n", xmlEsc(title)) + fmt.Fprintf(&b, " %s\n", xmlEsc(link)) + fmt.Fprintf(&b, " %s\n", xmlEsc(link)) + fmt.Fprintf(&b, " %s\n", p.Date.UTC().Format(time.RFC1123Z)) + fmt.Fprintf(&b, " %s\n", xmlEsc(s.truncateDescription(desc.String()))) + b.WriteString(" \n") + } + b.WriteString("\n\n") + w.Header().Set("Content-Type", "application/rss+xml; charset=utf-8") + w.Header().Set("Cache-Control", "no-cache") + w.Write([]byte(b.String())) +} + +const feedMoreNote = "\n

(more on the source page)

" + +// truncateDescription cuts an HTML description at max characters (runes), +// backing off so it doesn't split a tag or an entity in half, and appends +// a pointer to the post page. max <= 0 disables truncation. +func (s *Server) truncateDescription(desc string) string { + if s.feedMaxLen <= 0 || len([]rune(desc)) <= s.feedMaxLen { + return desc + } + cut := string([]rune(desc)[:s.feedMaxLen]) + // Back off if the cut landed inside a tag. + if i := strings.LastIndex(cut, "<"); i > strings.LastIndex(cut, ">") { + cut = cut[:i] + } + // Back off if the cut landed inside an entity like &. + if j := strings.LastIndex(cut, "&"); j > strings.LastIndex(cut, ";") { + cut = cut[:j] + } + return strings.TrimRight(cut, " \t\r\n") + feedMoreNote +} + +// xmlEsc escapes text for XML character data. html.EscapeString's output +// (& < > ' ") is valid XML. +func xmlEsc(s string) string { + return html.EscapeString(s) +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..6327547 --- /dev/null +++ b/go.mod @@ -0,0 +1,3 @@ +module mingyuet/server + +go 1.27 \ No newline at end of file diff --git a/main.go b/main.go new file mode 100644 index 0000000..6a1d39f --- /dev/null +++ b/main.go @@ -0,0 +1,291 @@ +// Package main implements mingyuet-server, a minimal blogging server for +// 明月樓閒話 Mingyuet Comments. +// +// Content lives in a directory tree ("content root"): +// +// /posts/*.html post fragments (hand-written HTML, no boilerplate) +// /pages/*.html standalone page fragments (About, Special, ...) +// /static/* served verbatim (style.css, images, robots.txt, ...) +// /layout.html optional layout template override +// +// The server renders the layout (sidebar, navigation, footer) around the +// fragments, generates archive pages and an RSS feed automatically, and +// rate-limits clients (max requests per IP per minute). +package main + +import ( + "flag" + "fmt" + "html/template" + "math" + "net" + "net/http" + "os" + "path" + "path/filepath" + "regexp" + "strconv" + "strings" + "time" + + // Embed a timezone database in the binary so IANA zone names in + // `time:` metas ("Asia/Hong_Kong", "Europe/Dublin", ...) resolve even + // when the host system has no tzdata installed. + _ "time/tzdata" +) + +const version = "1.0.0" + +func main() { + if len(os.Args) < 2 { + usage() + os.Exit(2) + } + var err error + switch os.Args[1] { + case "serve": + err = runServe(os.Args[2:]) + case "convert": + err = runConvert(os.Args[2:]) + case "version", "-v", "--version": + fmt.Println("mingyuet-server", version) + case "help", "-h", "--help": + usage() + default: + fmt.Fprintf(os.Stderr, "unknown command %q\n\n", os.Args[1]) + usage() + os.Exit(2) + } + if err != nil { + fmt.Fprintln(os.Stderr, "error:", err) + os.Exit(1) + } +} + +func usage() { + fmt.Fprint(os.Stderr, `mingyuet-server — minimal blogging server for 明月樓閒話 Mingyuet Comments + +Usage: + mingyuet-server serve [flags] run the web server + mingyuet-server convert [flags] convert the old static site into content fragments + +Run a subcommand with -h for its flags. See server/README.md for the +content format and full documentation. +`) +} + +// Server holds runtime configuration and state. +type Server struct { + site *Site + layout *template.Template + staticRoot string + fileServer http.Handler + pageSize int + feedItems int + feedMaxLen int + baseURL string + trustProxy bool + limiter *RateLimiter +} + +func runServe(args []string) error { + fs := flag.NewFlagSet("serve", flag.ExitOnError) + addr := fs.String("addr", ":8080", "listen address") + siteRoot := fs.String("site", "./site", "content root directory (posts/, pages/, static/, optional layout.html)") + baseURL := fs.String("base-url", "http://localhost:8080", "public base URL, used for links in the RSS feed") + pageSize := fs.Int("page-size", 22, "posts per page (page 1 = index, page 2 = archives/01.html, ...)") + feedItems := fs.Int("feed-items", 25, "number of items in the RSS feed") + feedMaxLen := fs.Int("feed-maxlen", 2000, "cut RSS descriptions longer than this many characters, ending with a note pointing at the post page (0 = never cut)") + rate := fs.Int("rate", 60, "max requests per client IP per rate-window; beyond that respond 429") + rateWindow := fs.Duration("rate-window", time.Minute, "rate limit window") + trustProxy := fs.Bool("trust-proxy", false, `use the first value of "X-Forwarded-For" as the client IP (use only behind a reverse proxy)`) + scanInterval := fs.Duration("scan-interval", 5*time.Second, "rescan the content root for new or changed posts at most this often") + fs.Parse(args) + + layout, err := loadLayout(*siteRoot) + if err != nil { + return err + } + s := &Server{ + site: NewSite(*siteRoot, *scanInterval), + layout: layout, + staticRoot: filepath.Join(*siteRoot, "static"), + pageSize: *pageSize, + feedItems: *feedItems, + feedMaxLen: *feedMaxLen, + baseURL: strings.TrimSuffix(*baseURL, "/"), + trustProxy: *trustProxy, + limiter: NewRateLimiter(*rate, *rateWindow), + } + s.fileServer = http.FileServer(http.Dir(s.staticRoot)) + s.site.Reload() + posts := s.site.Posts() + fmt.Printf("mingyuet-server %s: %d posts, %d pages from %s\n", version, len(posts), len(s.site.Pages()), *siteRoot) + if len(posts) == 0 { + fmt.Println("warning: no posts found — run `convert` first, or check the -site flag") + } + + mux := http.NewServeMux() + mux.HandleFunc("GET /{$}", func(w http.ResponseWriter, r *http.Request) { s.handleListing(w, r, 1) }) + mux.HandleFunc("GET /index.html", func(w http.ResponseWriter, r *http.Request) { s.handleListing(w, r, 1) }) + mux.HandleFunc("GET /feed.xml", s.handleFeed) + mux.HandleFunc("GET /rss.xml", s.handleFeed) + mux.HandleFunc("GET /archives/{name}", s.handleArchive) + mux.HandleFunc("GET /post/{name}", s.handlePost) + mux.HandleFunc("GET /articles/{name}", s.handleArticleRedirect) + mux.HandleFunc("/", s.handleFallback) + + fmt.Printf("listening on %s (base URL %s)\n", *addr, s.baseURL) + srv := &http.Server{ + Addr: *addr, + Handler: s.withRateLimit(mux), + ReadHeaderTimeout: 10 * time.Second, + } + return srv.ListenAndServe() +} + +var ( + postNameRe = regexp.MustCompile(`^[0-9A-Za-z_-]+\.html$`) + archiveNameRe = regexp.MustCompile(`^(\d+)\.html$`) +) + +// handleListing renders the index (pageNum 1) or an archive page +// (pageNum 2 → archives/01.html, pageNum 3 → archives/02.html, ...). +func (s *Server) handleListing(w http.ResponseWriter, r *http.Request, pageNum int) { + posts := s.site.Posts() + start := (pageNum - 1) * s.pageSize + if start >= len(posts) && pageNum > 1 { + s.renderNotFound(w, r) + return + } + end := start + s.pageSize + if end > len(posts) { + end = len(posts) + } + root := rootFor(r.URL.Path) + var b strings.Builder + for _, p := range posts[start:end] { + b.WriteString(renderEntry(p, root)) + b.WriteString("\n") + } + if pageNum > 1 { + if pageNum == 2 { + fmt.Fprintf(&b, "\n\t\t \n", root) + } else { + fmt.Fprintf(&b, "\n\t\t \n", root, pageNum-2, pageNum-2) + } + } + if end < len(posts) { + fmt.Fprintf(&b, "\n\t\t \n", root, pageNum, pageNum) + } + s.render(w, r, http.StatusOK, "", template.HTML(b.String())) +} + +func (s *Server) handleArchive(w http.ResponseWriter, r *http.Request) { + name := r.PathValue("name") + m := archiveNameRe.FindStringSubmatch(name) + if m == nil { + s.renderNotFound(w, r) + return + } + num, err := strconv.Atoi(m[1]) + if err != nil || num == 0 { + http.Redirect(w, r, "/", http.StatusMovedPermanently) + return + } + s.handleListing(w, r, num+1) +} + +// handlePost renders a single post with its own permalink page. +func (s *Server) handlePost(w http.ResponseWriter, r *http.Request) { + name := r.PathValue("name") + if !postNameRe.MatchString(name) { + s.renderNotFound(w, r) + return + } + p := s.site.PostByName(strings.TrimSuffix(name, ".html")) + if p == nil { + s.renderNotFound(w, r) + return + } + root := rootFor(r.URL.Path) + var b strings.Builder + if p.Title != "" { + fmt.Fprintf(&b, "

%s

\n", p.Title) + } + fmt.Fprintf(&b, "

%s

\n", p.DateStr) + b.WriteString(string(p.Body)) + fmt.Fprintf(&b, "\n\t\t

Back

\n", root) + s.render(w, r, http.StatusOK, p.TitleText, template.HTML(b.String())) +} + +// handleArticleRedirect keeps old inbound links alive: +// /articles/.html → 301 → /post/.html (matched by name or alias). +func (s *Server) handleArticleRedirect(w http.ResponseWriter, r *http.Request) { + name := r.PathValue("name") + if !postNameRe.MatchString(name) { + s.renderNotFound(w, r) + return + } + p := s.site.PostByAlias(strings.TrimSuffix(name, ".html")) + if p == nil { + s.renderNotFound(w, r) + return + } + http.Redirect(w, r, "/post/"+p.Name+".html", http.StatusMovedPermanently) +} + +// handleFallback serves page fragments (any /pages/**.html, mapped +// 1:1 to URLs), then static files, then a themed 404. +func (s *Server) handleFallback(w http.ResponseWriter, r *http.Request) { + p := path.Clean(r.URL.Path) + if p == "/" { + s.handleListing(w, r, 1) + return + } + if strings.Contains(p, "..") { + s.renderNotFound(w, r) + return + } + if page := s.site.Page(p); page != nil { + s.render(w, r, http.StatusOK, page.TitleSuffix, page.Content) + return + } + if _, err := os.Stat(filepath.Join(s.staticRoot, filepath.FromSlash(strings.TrimPrefix(p, "/")))); err == nil { + s.fileServer.ServeHTTP(w, r) + return + } + s.renderNotFound(w, r) +} + +// withRateLimit is the anti-abuse middleware: at most -rate requests per +// client IP per -rate-window; excess requests get 429 with Retry-After. +func (s *Server) withRateLimit(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + ok, retry := s.limiter.Allow(s.clientIP(r)) + if !ok { + w.Header().Set("Retry-After", strconv.Itoa(int(math.Ceil(retry.Seconds())))) + http.Error(w, "Too many requests. Please slow down.", http.StatusTooManyRequests) + return + } + next.ServeHTTP(w, r) + }) +} + +func (s *Server) clientIP(r *http.Request) string { + if s.trustProxy { + if xff := r.Header.Get("X-Forwarded-For"); xff != "" { + if i := strings.IndexByte(xff, ','); i >= 0 { + xff = xff[:i] + } + if v := strings.TrimSpace(xff); v != "" { + return v + } + } + } + host, _, err := net.SplitHostPort(r.RemoteAddr) + if err != nil { + return r.RemoteAddr + } + return host +} diff --git a/ratelimit.go b/ratelimit.go new file mode 100644 index 0000000..b088fbc --- /dev/null +++ b/ratelimit.go @@ -0,0 +1,59 @@ +package main + +import ( + "sync" + "time" +) + +// RateLimiter is a fixed-window per-key request limiter: at most max +// requests per key within each window. Keys are client IPs. It is the +// "max requests per minute" anti-abuse guard; excess requests are denied +// until the current window rolls over. State is in memory only. +type RateLimiter struct { + mu sync.Mutex + max int + window time.Duration + visitors map[string]*visitor + lastGC time.Time +} + +type visitor struct { + count int + resetAt time.Time +} + +func NewRateLimiter(max int, window time.Duration) *RateLimiter { + if max < 1 { + max = 1 + } + if window <= 0 { + window = time.Minute + } + return &RateLimiter{max: max, window: window, visitors: make(map[string]*visitor)} +} + +// Allow reports whether key may make one more request. If not, it returns +// how long the caller should wait before retrying. +func (rl *RateLimiter) Allow(key string) (bool, time.Duration) { + rl.mu.Lock() + defer rl.mu.Unlock() + now := time.Now() + v, ok := rl.visitors[key] + if !ok || now.After(v.resetAt) { + v = &visitor{count: 0, resetAt: now.Add(rl.window)} + rl.visitors[key] = v + } + if now.Sub(rl.lastGC) > rl.window { + for k, e := range rl.visitors { + if now.After(e.resetAt) { + delete(rl.visitors, k) + } + } + rl.lastGC = now + } + if v.count >= rl.max { + return false, time.Until(v.resetAt) + } + v.count++ + return true, 0 +} diff --git a/render.go b/render.go new file mode 100644 index 0000000..16784f4 --- /dev/null +++ b/render.go @@ -0,0 +1,134 @@ +package main + +import ( + "bytes" + "fmt" + "html/template" + "net/http" + "os" + "path" + "path/filepath" + "strings" +) + +// The default layout replicates the original hand-written site shell +// (table-based two-column layout with sidebar and footer). A file named +// layout.html in the content root overrides it; it must keep using the +// {{.FullTitle}}, {{.Root}} and {{.Content}} actions. +const defaultLayout = ` + + + + + {{.FullTitle}} + + + + + + + + + + + + +
+
+
Mingyuet Comments logo
+ +
+ Inquiries:
+ zaaktin.lam {at} outlook.com +
+
+
+ {{.Content}} +
© 2025-2026 Mingyuet Comments
+ + +` + +const siteName = "明月樓閒話 Mingyuet Comments" + +type layoutData struct { + FullTitle string + Root string + Content template.HTML +} + +func fullTitle(suffix string) string { + if suffix == "" { + return siteName + } + return suffix + " :: " + siteName +} + +// rootFor returns the relative prefix that points back at the site root +// from the given URL path ("./" at depth 0, "../" at depth 1, ...), the +// same convention the original hand-written pages used. +func rootFor(urlPath string) string { + trimmed := strings.Trim(path.Clean(urlPath), "/") + if trimmed == "" { + return "./" + } + n := strings.Count(trimmed, "/") + if n == 0 { + return "./" + } + return strings.Repeat("../", n) +} + +func loadLayout(siteRoot string) (*template.Template, error) { + if data, err := os.ReadFile(filepath.Join(siteRoot, "layout.html")); err == nil { + t, err := template.New("layout").Parse(string(data)) + if err != nil { + return nil, fmt.Errorf("parsing %s/layout.html: %w", siteRoot, err) + } + return t, nil + } + return template.New("layout").Parse(defaultLayout) +} + +// render wraps content in the layout and writes it out. +func (s *Server) render(w http.ResponseWriter, r *http.Request, status int, titleSuffix string, content template.HTML) { + w.Header().Set("Content-Type", "text/html; charset=utf-8") + w.Header().Set("Cache-Control", "no-cache") + w.WriteHeader(status) + var b bytes.Buffer + s.layout.Execute(&b, layoutData{ + FullTitle: fullTitle(titleSuffix), + Root: rootFor(r.URL.Path), + Content: content, + }) + w.Write(b.Bytes()) +} + +// renderEntry renders one post as a listing-page entry, in the same shape +// as the original hand-written
blocks. The +// date doubles as a link to the post's own page. +func renderEntry(p *Post, root string) string { + var b strings.Builder + fmt.Fprintf(&b, "\n\t\t
\n", p.ID) + if p.Title != "" { + fmt.Fprintf(&b, "\t\t\t

%s

\n", p.Title) + } + fmt.Fprintf(&b, "\t\t\t

%s

\n", root, p.Name, p.DateStr) + if p.HasMore { + b.WriteString(string(p.Excerpt)) + b.WriteString("\n") + fmt.Fprintf(&b, "\t\t\t

>>> More

\n", root, p.Name) + } else { + b.WriteString(string(p.Excerpt)) + b.WriteString("\n") + } + b.WriteString("\t\t
") + return b.String() +} + +func (s *Server) renderNotFound(w http.ResponseWriter, r *http.Request) { + s.render(w, r, http.StatusNotFound, "Not Found", + "

Page Not Found

\n\t\t

The requested page was not found.

") +} diff --git a/site.go b/site.go new file mode 100644 index 0000000..5a64af5 --- /dev/null +++ b/site.go @@ -0,0 +1,378 @@ +package main + +import ( + "fmt" + "html" + "html/template" + "io/fs" + "os" + "path/filepath" + "regexp" + "sort" + "strconv" + "strings" + "sync" + "time" +) + +// Post is a single blog post loaded from /posts/.html. +type Post struct { + Name string // file stem, used in the /post/.html URL + ID string // id= attribute of the entry
on listing pages + Title template.HTML + TitleText string // plain-text form of Title, for and RSS + DateText string // raw value of the `date:` meta comment, if any + Date time.Time + DateStr string // display form, e.g. "2025.12.2" + Aliases []string + HasMore bool + Excerpt template.HTML // part before <!-- more --> + Body template.HTML // full content (excerpt + remainder) +} + +// Page is a standalone page loaded from <root>/pages/**.html. +type Page struct { + URL string // e.g. "/about.html" + TitleSuffix string // e.g. "About" + Content template.HTML +} + +// Fragment format (see README): +// +// <!-- id: optional-div-id --> +// <!-- title: optional raw HTML for the <h1> --> +// <!-- date: 2006-01-02 --> (only needed when the filename is not YYYYMMDD[-N].html) +// <!-- alias: old-url-stem --> +// <body html> +// <!-- more --> +// <rest of body, only shown on the post page> +// +// Meta comments must sit on their own lines at the top of the file. + +var ( + metaLineRe = regexp.MustCompile(`^<!--\s*(id|title|date|time|alias)\s*:\s*(.*?)\s*-->$`) + moreRe = regexp.MustCompile(`<!--\s*more\s*-->`) + nameDateRe = regexp.MustCompile(`^(\d{4})(\d{2})(\d{2})(?:-[0-9]+)?$`) + timeClockRe = regexp.MustCompile(`^(\d{1,2}):(\d{2})(?::(\d{2}))?$`) + zoneOffsetRe = regexp.MustCompile(`^([+-])(\d{2})(?::?(\d{2}))?$`) + tagRe = regexp.MustCompile(`<[^>]*>`) + wsRe = regexp.MustCompile(`\s+`) +) + +func stripTags(s string) string { + s = tagRe.ReplaceAllString(s, " ") + s = html.UnescapeString(s) + return strings.TrimSpace(wsRe.ReplaceAllString(s, " ")) +} + +var dateLayouts = []string{"2006-01-02", "2006-1-2", "2006.01.02", "2006.1.2"} + +// parseMetaBlock consumes leading meta-comment lines (and blank lines) and +// returns the rest of the file plus the collected values. +func parseMetaBlock(data string) (rest, id, title, date, timeText, alias string) { + for data != "" { + line, remainder, _ := strings.Cut(data, "\n") + trimmed := strings.TrimSpace(line) + if m := metaLineRe.FindStringSubmatch(trimmed); m != nil { + switch m[1] { + case "id": + id = m[2] + case "title": + title = m[2] + case "date": + date = m[2] + case "time": + timeText = m[2] + case "alias": + alias = m[2] + } + data = remainder + } else if trimmed == "" { + data = remainder + } else { + break + } + } + return data, id, title, date, timeText, alias +} + +// parsePostWhen resolves the post's date from its filename or `date:` meta +// and, if a `time:` meta is present, applies that clock time in the given +// time zone to the pubDate in the RSS feed. The site's own date display +// stays date-only. +func parsePostWhen(name, dateText, timeText string) (time.Time, error) { + var t time.Time + if m := nameDateRe.FindStringSubmatch(name); m != nil { + y, err1 := strconv.Atoi(m[1]) + mo, err2 := strconv.Atoi(m[2]) + d, err3 := strconv.Atoi(m[3]) + if err1 != nil || err2 != nil || err3 != nil { + return time.Time{}, fmt.Errorf("bad date in filename %q", name) + } + t = time.Date(y, time.Month(mo), d, 0, 0, 0, 0, time.UTC) + } else { + if dateText == "" { + return time.Time{}, fmt.Errorf("no date: give the file a YYYYMMDD name or add a `date:` meta comment") + } + parsed := false + for _, layout := range dateLayouts { + if pt, err := time.Parse(layout, dateText); err == nil { + t = time.Date(pt.Year(), pt.Month(), pt.Day(), 0, 0, 0, 0, time.UTC) + parsed = true + break + } + } + if !parsed { + return time.Time{}, fmt.Errorf("unparseable date %q (want 2006-01-02 or 2006.1.2)", dateText) + } + } + if timeText == "" { + return t, nil + } + hh, mm, ss, loc, err := parseTimeSpec(timeText) + if err != nil { + return time.Time{}, err + } + return time.Date(t.Year(), t.Month(), t.Day(), hh, mm, ss, 0, loc), nil +} + +// parseTimeSpec parses a `time:` meta value: "HH:MM[:SS]" optionally +// followed by a time zone ("13:45 Asia/Hong_Kong", "21:05 +08:00"). +// Without a zone the time is taken as UTC. +func parseTimeSpec(spec string) (hh, mm, ss int, loc *time.Location, err error) { + fields := strings.Fields(spec) + if len(fields) == 0 || len(fields) > 2 { + return 0, 0, 0, nil, fmt.Errorf("bad time %q (want HH:MM[:SS] [ZONE])", spec) + } + m := timeClockRe.FindStringSubmatch(fields[0]) + if m == nil { + return 0, 0, 0, nil, fmt.Errorf("bad time %q (want HH:MM[:SS] [ZONE])", spec) + } + hh, _ = strconv.Atoi(m[1]) + mm, _ = strconv.Atoi(m[2]) + if m[3] != "" { + ss, _ = strconv.Atoi(m[3]) + } + if hh > 23 || mm > 59 || ss > 59 { + return 0, 0, 0, nil, fmt.Errorf("time out of range %q", fields[0]) + } + loc = time.UTC + if len(fields) == 2 { + if loc, err = parseZoneSpec(fields[1]); err != nil { + return 0, 0, 0, nil, err + } + } + return hh, mm, ss, loc, nil +} + +// parseZoneSpec understands IANA zone names ("Asia/Hong_Kong", "Europe/Dublin"), +// "UTC"/"Z", and fixed numeric offsets ("+08", "+08:00", "-0530"). +func parseZoneSpec(spec string) (*time.Location, error) { + switch strings.ToUpper(spec) { + case "UTC", "Z": + return time.UTC, nil + } + if m := zoneOffsetRe.FindStringSubmatch(spec); m != nil { + sign := 1 + if m[1] == "-" { + sign = -1 + } + hh, _ := strconv.Atoi(m[2]) + mm := 0 + if m[3] != "" { + mm, _ = strconv.Atoi(m[3]) + } + if hh > 23 || mm > 59 { + return nil, fmt.Errorf("zone offset out of range %q", spec) + } + return time.FixedZone(spec, sign*(hh*3600+mm*60)), nil + } + loc, err := time.LoadLocation(spec) + if err != nil { + return nil, fmt.Errorf("unknown time zone %q", spec) + } + return loc, nil +} + +func parsePost(path string) (*Post, error) { + data, err := os.ReadFile(path) + if err != nil { + return nil, err + } + name := strings.TrimSuffix(filepath.Base(path), ".html") + p := &Post{Name: name, ID: name} + rest, id, title, date, timeText, alias := parseMetaBlock(string(data)) + if id != "" { + p.ID = id + } + if title != "" { + p.Title = template.HTML(title) + p.TitleText = stripTags(title) + } + p.DateText = date + if alias != "" { + p.Aliases = strings.Fields(alias) + } + t, err := parsePostWhen(name, date, timeText) + if err != nil { + return nil, err + } + p.Date = t + p.DateStr = fmt.Sprintf("%d.%d.%d", t.Year(), int(t.Month()), t.Day()) + + if loc := moreRe.FindStringIndex(rest); loc != nil { + p.HasMore = true + p.Excerpt = template.HTML(rest[:loc[0]]) + p.Body = template.HTML(rest[:loc[0]] + rest[loc[1]:]) + } else { + p.Excerpt = template.HTML(rest) + p.Body = p.Excerpt + } + return p, nil +} + +func parsePage(path string) (*Page, error) { + data, err := os.ReadFile(path) + if err != nil { + return nil, err + } + rest, _, title, _, _, _ := parseMetaBlock(string(data)) + return &Page{TitleSuffix: title, Content: template.HTML(rest)}, nil +} + +// Site loads and caches the content of a content root. It rescans the +// directories at most once per interval so new posts appear without a +// restart. Loaded slices/maps are never mutated after publication, so +// concurrent readers can safely use the returned values. +type Site struct { + root string + interval time.Duration + + mu sync.Mutex + loadedAt time.Time + posts []*Post + byName map[string]*Post + byAlias map[string]*Post + pages map[string]*Page +} + +func NewSite(root string, interval time.Duration) *Site { + if interval < 0 { + interval = 0 + } + return &Site{root: root, interval: interval} +} + +// Reload rescans the content root now. Unreadable or unparseable files are +// reported on stderr and skipped; the rest of the site keeps working. +func (s *Site) Reload() { + s.mu.Lock() + defer s.mu.Unlock() + s.loadedAt = time.Now() + + posts := []*Post{} + byName := map[string]*Post{} + byAlias := map[string]*Post{} + files, err := filepath.Glob(filepath.Join(s.root, "posts", "*.html")) + if err != nil { + fmt.Fprintln(os.Stderr, "warning:", err) + } + for _, f := range files { + p, err := parsePost(f) + if err != nil { + fmt.Fprintf(os.Stderr, "warning: skipping post %s: %v\n", filepath.Base(f), err) + continue + } + if _, dup := byName[p.Name]; dup { + fmt.Fprintf(os.Stderr, "warning: duplicate post name %q\n", p.Name) + continue + } + posts = append(posts, p) + byName[p.Name] = p + for _, a := range p.Aliases { + byAlias[a] = p + } + } + // Newest first; ties broken by descending filename so that, within one + // date, 20250709-2.html is considered newer than 20250709-1.html. + sort.SliceStable(posts, func(i, j int) bool { + if !posts[i].Date.Equal(posts[j].Date) { + return posts[i].Date.After(posts[j].Date) + } + return posts[i].Name > posts[j].Name + }) + + pages := map[string]*Page{} + pagesRoot := filepath.Join(s.root, "pages") + filepath.WalkDir(pagesRoot, func(path string, d fs.DirEntry, err error) error { + if err != nil { + return nil // missing pages/ dir or unreadable entry: keep going + } + if d.IsDir() || !strings.HasSuffix(path, ".html") || strings.HasSuffix(path, "~") { + return nil + } + pg, err := parsePage(path) + if err != nil { + fmt.Fprintf(os.Stderr, "warning: skipping page %s: %v\n", path, err) + return nil + } + rel, err := filepath.Rel(pagesRoot, path) + if err != nil { + return nil + } + pg.URL = "/" + filepath.ToSlash(rel) + pages[pg.URL] = pg + return nil + }) + + s.posts, s.byName, s.byAlias, s.pages = posts, byName, byAlias, pages +} + +func (s *Site) maybeRefresh() { + s.mu.Lock() + stale := time.Since(s.loadedAt) > s.interval + s.mu.Unlock() + if stale { + s.Reload() + } +} + +func (s *Site) Posts() []*Post { + s.maybeRefresh() + s.mu.Lock() + defer s.mu.Unlock() + return s.posts +} + +func (s *Site) Pages() map[string]*Page { + s.maybeRefresh() + s.mu.Lock() + defer s.mu.Unlock() + return s.pages +} + +func (s *Site) PostByName(name string) *Post { + s.maybeRefresh() + s.mu.Lock() + defer s.mu.Unlock() + return s.byName[name] +} + +// PostByAlias matches either the post's own name or one of its aliases +// (used by the /articles/... compatibility redirect). +func (s *Site) PostByAlias(name string) *Post { + s.maybeRefresh() + s.mu.Lock() + defer s.mu.Unlock() + if p := s.byAlias[name]; p != nil { + return p + } + return s.byName[name] +} + +func (s *Site) Page(url string) *Page { + s.maybeRefresh() + s.mu.Lock() + defer s.mu.Unlock() + return s.pages[url] +} -- cgit v1.2.3