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.

") }