// 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
Newer Posts
\n", root) } else { fmt.Fprintf(&b, "\n\t\t
Newer Posts (Collection #%02d)
\n", root, pageNum-2, pageNum-2) } } if end < len(posts) { fmt.Fprintf(&b, "\n\t\t
Older Posts (Collection #%02d)
\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 }