1
1

main.go 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. // posts serves a Markdown blog: each .md file in CONTENT_DIR is one post.
  2. package main
  3. import (
  4. "bytes"
  5. "html/template"
  6. "io/fs"
  7. "log"
  8. "net/http"
  9. "net/url"
  10. "os"
  11. "path/filepath"
  12. "strings"
  13. "time"
  14. )
  15. type app struct {
  16. store *Store
  17. config *configFile
  18. pages map[string]*template.Template
  19. assets map[string]string // static file -> content hash
  20. about template.HTML
  21. siteURL string // absolute base URL, no trailing slash
  22. siteName string
  23. commit string
  24. }
  25. func newApp(contentDir, siteURL string) (*app, error) {
  26. pages, err := loadTemplates()
  27. if err != nil {
  28. return nil, err
  29. }
  30. siteURL = strings.TrimRight(siteURL, "/")
  31. u, err := url.Parse(siteURL)
  32. if err != nil {
  33. return nil, err
  34. }
  35. assets, err := assetHashes()
  36. if err != nil {
  37. return nil, err
  38. }
  39. md := newMarkdown()
  40. var about bytes.Buffer
  41. if err := md.Convert(aboutMarkdown, &about); err != nil {
  42. return nil, err
  43. }
  44. return &app{
  45. store: NewStore(contentDir, md),
  46. config: newConfigFile(filepath.Join(contentDir, "site.json")),
  47. pages: pages,
  48. assets: assets,
  49. about: template.HTML(about.String()),
  50. siteURL: siteURL,
  51. siteName: u.Host,
  52. commit: buildCommit(),
  53. }, nil
  54. }
  55. func (a *app) routes() http.Handler {
  56. static, err := fs.Sub(staticFS, "static")
  57. if err != nil {
  58. panic(err)
  59. }
  60. files := http.StripPrefix("/static/", http.FileServerFS(static))
  61. mux := http.NewServeMux()
  62. mux.HandleFunc("GET /{$}", a.index)
  63. mux.HandleFunc("GET /posts/{slug}", a.post)
  64. mux.HandleFunc("GET /about", a.aboutPage)
  65. mux.HandleFunc("GET /feed.xml", a.feed)
  66. mux.HandleFunc("GET /static/", func(w http.ResponseWriter, r *http.Request) {
  67. if strings.HasSuffix(r.URL.Path, "/") { // no directory listings
  68. a.notFound(w, r)
  69. return
  70. }
  71. // A URL carrying the file's current hash never changes content, so it
  72. // can be cached for a year; anything else gets an hour.
  73. cache := "public, max-age=3600"
  74. if v := r.URL.Query().Get("v"); v != "" && v == a.assets[strings.TrimPrefix(r.URL.Path, "/static/")] {
  75. cache = "public, max-age=31536000, immutable"
  76. }
  77. w.Header().Set("Cache-Control", cache)
  78. files.ServeHTTP(w, r)
  79. })
  80. mux.HandleFunc("/", a.notFound)
  81. return securityHeaders(mux)
  82. }
  83. func (a *app) index(w http.ResponseWriter, r *http.Request) {
  84. idx, err := a.store.Index()
  85. if err != nil {
  86. a.serverError(w, err)
  87. return
  88. }
  89. a.render(w, http.StatusOK, "index", pageData{Posts: idx.posts})
  90. }
  91. func (a *app) post(w http.ResponseWriter, r *http.Request) {
  92. idx, err := a.store.Index()
  93. if err != nil {
  94. a.serverError(w, err)
  95. return
  96. }
  97. i, ok := idx.bySlug[r.PathValue("slug")]
  98. if !ok {
  99. a.notFound(w, r)
  100. return
  101. }
  102. data := pageData{Post: idx.posts[i]}
  103. if i > 0 {
  104. data.Newer = idx.posts[i-1]
  105. }
  106. if i+1 < len(idx.posts) {
  107. data.Older = idx.posts[i+1]
  108. }
  109. a.render(w, http.StatusOK, "post", data)
  110. }
  111. func (a *app) aboutPage(w http.ResponseWriter, r *http.Request) {
  112. idx, err := a.store.Index()
  113. if err != nil {
  114. a.serverError(w, err)
  115. return
  116. }
  117. a.render(w, http.StatusOK, "about", pageData{
  118. Posts: idx.posts,
  119. Version: version,
  120. Commit: a.commit,
  121. About: a.about,
  122. })
  123. }
  124. func (a *app) notFound(w http.ResponseWriter, r *http.Request) {
  125. a.render(w, http.StatusNotFound, "error", pageData{Status: 404, Message: "That page doesn't exist."})
  126. }
  127. func (a *app) serverError(w http.ResponseWriter, err error) {
  128. log.Printf("error: %v", err)
  129. a.render(w, http.StatusInternalServerError, "error", pageData{Status: 500, Message: "Something went wrong."})
  130. }
  131. // securityHeaders sets a strict policy: posts never contain scripts, and
  132. // images may come from anywhere over HTTPS.
  133. func securityHeaders(next http.Handler) http.Handler {
  134. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  135. h := w.Header()
  136. 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'")
  137. h.Set("X-Content-Type-Options", "nosniff")
  138. h.Set("Referrer-Policy", "strict-origin-when-cross-origin")
  139. next.ServeHTTP(w, r)
  140. })
  141. }
  142. func getenv(key, def string) string {
  143. if v := os.Getenv(key); v != "" {
  144. return v
  145. }
  146. return def
  147. }
  148. func main() {
  149. port := os.Getenv("PORT")
  150. if port == "" {
  151. log.Fatal("PORT not set")
  152. }
  153. a, err := newApp(getenv("CONTENT_DIR", "content"), getenv("SITE_URL", "https://posts.monoaf.com"))
  154. if err != nil {
  155. log.Fatal(err)
  156. }
  157. srv := &http.Server{
  158. Addr: "127.0.0.1:" + port,
  159. Handler: a.routes(),
  160. ReadHeaderTimeout: 5 * time.Second,
  161. ReadTimeout: 10 * time.Second,
  162. WriteTimeout: 30 * time.Second,
  163. IdleTimeout: 2 * time.Minute,
  164. }
  165. log.Printf("listening on %s", srv.Addr)
  166. log.Fatal(srv.ListenAndServe())
  167. }