main.go 5.4 KB

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