| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140 |
- // posts serves a Markdown blog: each .md file in CONTENT_DIR is one post.
- package main
- import (
- "html/template"
- "io/fs"
- "log"
- "net/http"
- "net/url"
- "os"
- "strings"
- "time"
- )
- type app struct {
- store *Store
- pages map[string]*template.Template
- siteURL string // absolute base URL, no trailing slash
- siteName string
- }
- func newApp(contentDir, siteURL string) (*app, error) {
- pages, err := loadTemplates()
- if err != nil {
- return nil, err
- }
- siteURL = strings.TrimRight(siteURL, "/")
- u, err := url.Parse(siteURL)
- if err != nil {
- return nil, err
- }
- return &app{
- store: NewStore(contentDir, newMarkdown()),
- pages: pages,
- siteURL: siteURL,
- siteName: u.Host,
- }, nil
- }
- func (a *app) routes() http.Handler {
- static, err := fs.Sub(staticFS, "static")
- if err != nil {
- panic(err)
- }
- files := http.StripPrefix("/static/", http.FileServerFS(static))
- mux := http.NewServeMux()
- mux.HandleFunc("GET /{$}", a.index)
- mux.HandleFunc("GET /posts/{slug}", a.post)
- mux.HandleFunc("GET /feed.xml", a.feed)
- mux.HandleFunc("GET /static/", func(w http.ResponseWriter, r *http.Request) {
- if strings.HasSuffix(r.URL.Path, "/") { // no directory listings
- a.notFound(w, r)
- return
- }
- w.Header().Set("Cache-Control", "public, max-age=3600")
- files.ServeHTTP(w, r)
- })
- mux.HandleFunc("/", a.notFound)
- return securityHeaders(mux)
- }
- func (a *app) index(w http.ResponseWriter, r *http.Request) {
- idx, err := a.store.Index()
- if err != nil {
- a.serverError(w, err)
- return
- }
- a.render(w, http.StatusOK, "index", pageData{Posts: idx.posts})
- }
- func (a *app) post(w http.ResponseWriter, r *http.Request) {
- idx, err := a.store.Index()
- if err != nil {
- a.serverError(w, err)
- return
- }
- i, ok := idx.bySlug[r.PathValue("slug")]
- if !ok {
- a.notFound(w, r)
- return
- }
- data := pageData{Post: idx.posts[i]}
- if i > 0 {
- data.Newer = idx.posts[i-1]
- }
- if i+1 < len(idx.posts) {
- data.Older = idx.posts[i+1]
- }
- a.render(w, http.StatusOK, "post", data)
- }
- func (a *app) notFound(w http.ResponseWriter, r *http.Request) {
- a.render(w, http.StatusNotFound, "error", pageData{Status: 404, Message: "That page doesn't exist."})
- }
- func (a *app) serverError(w http.ResponseWriter, err error) {
- log.Printf("error: %v", err)
- a.render(w, http.StatusInternalServerError, "error", pageData{Status: 500, Message: "Something went wrong."})
- }
- // securityHeaders sets a strict policy: posts never contain scripts, and
- // images may come from anywhere over HTTPS.
- func securityHeaders(next http.Handler) http.Handler {
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- h := w.Header()
- h.Set("Content-Security-Policy", "default-src 'self'; img-src 'self' https: data:; script-src 'none'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'")
- h.Set("X-Content-Type-Options", "nosniff")
- h.Set("Referrer-Policy", "strict-origin-when-cross-origin")
- next.ServeHTTP(w, r)
- })
- }
- func getenv(key, def string) string {
- if v := os.Getenv(key); v != "" {
- return v
- }
- return def
- }
- func main() {
- port := os.Getenv("PORT")
- if port == "" {
- log.Fatal("PORT not set")
- }
- a, err := newApp(getenv("CONTENT_DIR", "content"), getenv("SITE_URL", "https://posts.monoaf.com"))
- if err != nil {
- log.Fatal(err)
- }
- srv := &http.Server{
- Addr: "127.0.0.1:" + port,
- Handler: a.routes(),
- ReadHeaderTimeout: 5 * time.Second,
- ReadTimeout: 10 * time.Second,
- WriteTimeout: 30 * time.Second,
- IdleTimeout: 2 * time.Minute,
- }
- log.Printf("listening on %s", srv.Addr)
- log.Fatal(srv.ListenAndServe())
- }
|