GoBlog/http.go

397 lines
13 KiB
Go
Raw Normal View History

2020-07-28 19:17:07 +00:00
package main
import (
2020-10-19 19:09:51 +00:00
"compress/flate"
2020-12-13 14:16:47 +00:00
"fmt"
2020-07-28 19:17:07 +00:00
"net/http"
"strconv"
"sync/atomic"
2020-09-25 17:23:01 +00:00
"github.com/caddyserver/certmagic"
2021-01-23 16:24:47 +00:00
"github.com/dchest/captcha"
2020-09-25 17:23:01 +00:00
"github.com/go-chi/chi"
"github.com/go-chi/chi/middleware"
2020-07-28 19:17:07 +00:00
)
const (
contentType = "Content-Type"
2020-07-31 14:23:29 +00:00
charsetUtf8Suffix = "; charset=utf-8"
contentTypeHTML = "text/html"
contentTypeJSON = "application/json"
contentTypeWWWForm = "application/x-www-form-urlencoded"
contentTypeMultipartForm = "multipart/form-data"
contentTypeAS = "application/activity+json"
contentTypeHTMLUTF8 = contentTypeHTML + charsetUtf8Suffix
contentTypeJSONUTF8 = contentTypeJSON + charsetUtf8Suffix
contentTypeASUTF8 = contentTypeAS + charsetUtf8Suffix
userAgent = "User-Agent"
appUserAgent = "GoBlog"
)
var (
2020-12-15 16:40:14 +00:00
d *dynamicHandler
)
2020-07-31 19:44:16 +00:00
2020-08-01 15:49:46 +00:00
func startServer() (err error) {
2020-11-03 17:58:32 +00:00
// Start
d = &dynamicHandler{}
err = reloadRouter()
if err != nil {
2020-08-01 15:49:46 +00:00
return
2020-07-28 19:17:07 +00:00
}
2020-08-04 17:42:09 +00:00
localAddress := ":" + strconv.Itoa(appConfig.Server.Port)
2020-10-06 17:07:48 +00:00
if appConfig.Server.PublicHTTPS {
certmagic.Default.Storage = &certmagic.FileStorage{Path: "data/https"}
certmagic.DefaultACME.Agreed = true
certmagic.DefaultACME.Email = appConfig.Server.LetsEncryptMail
certmagic.DefaultACME.CA = certmagic.LetsEncryptProductionCA
2020-12-24 10:00:16 +00:00
hosts := []string{appConfig.Server.publicHostname}
if appConfig.Server.shortPublicHostname != "" {
hosts = append(hosts, appConfig.Server.shortPublicHostname)
}
err = certmagic.HTTPS(hosts, securityHeaders(d))
2020-08-01 15:49:46 +00:00
} else {
err = http.ListenAndServe(localAddress, d)
2020-07-29 14:41:36 +00:00
}
2020-08-01 15:49:46 +00:00
return
}
2020-07-29 14:41:36 +00:00
2020-07-31 19:44:16 +00:00
func reloadRouter() error {
h, err := buildHandler()
if err != nil {
return err
}
purgeCache()
2020-07-31 19:44:16 +00:00
d.swapHandler(h)
return nil
}
func buildHandler() (http.Handler, error) {
r := chi.NewRouter()
2020-08-04 17:42:09 +00:00
if appConfig.Server.Logging {
2020-11-03 17:58:32 +00:00
r.Use(logMiddleware)
2020-07-28 19:52:56 +00:00
}
2020-11-03 17:58:32 +00:00
r.Use(middleware.Recoverer)
2020-10-19 19:09:51 +00:00
r.Use(middleware.Compress(flate.DefaultCompression))
2020-12-24 10:00:16 +00:00
r.Use(redirectShortDomain)
2020-11-05 16:06:42 +00:00
r.Use(middleware.RedirectSlashes)
2020-12-22 19:29:25 +00:00
r.Use(middleware.CleanPath)
2020-10-19 19:09:51 +00:00
r.Use(middleware.GetHead)
if !appConfig.Cache.Enable {
r.Use(middleware.NoCache)
}
2020-12-15 16:40:14 +00:00
r.Use(checkIsLogin)
2021-01-23 16:24:47 +00:00
r.Use(checkIsCaptcha)
2020-10-12 18:23:21 +00:00
// Profiler
if appConfig.Server.Debug {
r.Mount("/debug", middleware.Profiler())
}
// API
2020-07-31 19:44:16 +00:00
r.Route("/api", func(apiRouter chi.Router) {
apiRouter.Use(middleware.NoCache, authMiddleware)
apiRouter.Post("/hugo", apiPostCreateHugo)
2020-07-31 19:44:16 +00:00
})
2020-10-06 17:07:48 +00:00
// Micropub
r.Route(micropubPath, func(mpRouter chi.Router) {
2020-12-13 10:01:57 +00:00
mpRouter.Use(checkIndieAuth, middleware.NoCache, minifier.Middleware)
mpRouter.Get("/", serveMicropubQuery)
mpRouter.Post("/", serveMicropubPost)
2021-01-10 14:59:43 +00:00
mpRouter.Post(micropubMediaSubPath, serveMicropubMedia)
})
2020-10-06 17:07:48 +00:00
2020-10-13 19:35:39 +00:00
// IndieAuth
r.Route("/indieauth", func(indieauthRouter chi.Router) {
2020-12-13 10:01:57 +00:00
indieauthRouter.Use(middleware.NoCache, minifier.Middleware)
indieauthRouter.Get("/", indieAuthRequest)
2020-10-13 19:35:39 +00:00
indieauthRouter.With(authMiddleware).Post("/accept", indieAuthAccept)
2020-12-09 16:25:09 +00:00
indieauthRouter.Post("/", indieAuthVerification)
2020-10-13 19:35:39 +00:00
indieauthRouter.Get("/token", indieAuthToken)
indieauthRouter.Post("/token", indieAuthToken)
})
// ActivityPub and stuff
if appConfig.ActivityPub.Enabled {
r.Post("/activitypub/inbox/{blog}", apHandleInbox)
2020-11-10 06:45:32 +00:00
r.Post("/activitypub/{blog}/inbox", apHandleInbox)
r.Get("/.well-known/webfinger", apHandleWebfinger)
2020-11-17 16:10:14 +00:00
r.With(cacheMiddleware).Get("/.well-known/host-meta", handleWellKnownHostMeta)
2021-01-21 16:59:47 +00:00
r.With(cacheMiddleware, minifier.Middleware).Get("/.well-known/nodeinfo", serveNodeInfoDiscover)
r.With(cacheMiddleware, minifier.Middleware).Get("/nodeinfo", serveNodeInfo)
}
// Webmentions
r.Route("/webmention", func(webmentionRouter chi.Router) {
webmentionRouter.Use(middleware.NoCache)
webmentionRouter.Post("/", handleWebmention)
2021-01-15 20:56:46 +00:00
webmentionRouter.With(minifier.Middleware, authMiddleware).Get("/", webmentionAdmin)
2020-12-19 10:06:55 +00:00
webmentionRouter.With(authMiddleware).Post("/delete", webmentionAdminDelete)
webmentionRouter.With(authMiddleware).Post("/approve", webmentionAdminApprove)
})
// Posts
2021-01-15 20:56:46 +00:00
pp, err := allPostPaths(statusPublished)
if err != nil {
return nil, err
2020-07-30 19:18:13 +00:00
}
var postMW []func(http.Handler) http.Handler
if appConfig.ActivityPub.Enabled {
postMW = []func(http.Handler) http.Handler{manipulateAsPath, cacheMiddleware, minifier.Middleware}
} else {
postMW = []func(http.Handler) http.Handler{cacheMiddleware, minifier.Middleware}
}
2021-01-15 20:56:46 +00:00
for _, path := range pp {
2020-07-30 19:18:13 +00:00
if path != "" {
r.With(postMW...).Get(path, servePost)
}
}
2021-01-15 20:56:46 +00:00
// Drafts
dp, err := allPostPaths(statusDraft)
if err != nil {
return nil, err
}
for _, path := range dp {
if path != "" {
2021-01-15 21:05:01 +00:00
r.With(middleware.NoCache, minifier.Middleware, authMiddleware).Get(path, servePost)
2021-01-15 20:56:46 +00:00
}
}
2020-11-09 17:33:56 +00:00
// Post aliases
allPostAliases, err := allPostAliases()
if err != nil {
return nil, err
2020-07-30 19:18:13 +00:00
}
2020-11-09 17:33:56 +00:00
for _, path := range allPostAliases {
2020-07-30 19:18:13 +00:00
if path != "" {
2020-11-09 17:33:56 +00:00
r.With(cacheMiddleware).Get(path, servePostAlias)
}
}
// Assets
for _, path := range allAssetPaths() {
r.Get(path, serveAsset)
}
2020-12-23 13:11:14 +00:00
// Static files
for _, path := range allStaticPaths() {
r.Get(path, serveStaticFile)
2020-12-23 13:11:14 +00:00
}
2021-01-10 14:59:43 +00:00
// Media files
r.Get(`/m/{file:[0-9a-fA-F]+(\.[0-9a-zA-Z]+)?}`, serveMediaFile)
2021-01-10 14:59:43 +00:00
2021-01-23 16:24:47 +00:00
// Captcha
r.Handle("/captcha/*", captcha.Server(500, 250))
2020-12-22 21:15:29 +00:00
// Short paths
r.With(cacheMiddleware).Get("/s/{id:[0-9a-fA-F]+}", redirectToLongPath)
2020-10-15 18:54:43 +00:00
paginationPath := "/page/{page:[0-9-]+}"
2020-10-15 17:50:34 +00:00
feedPath := ".{feed:rss|json|atom}"
2020-08-31 19:12:43 +00:00
2020-10-06 17:07:48 +00:00
for blog, blogConfig := range appConfig.Blogs {
2020-10-12 17:12:24 +00:00
fullBlogPath := blogConfig.Path
blogPath := fullBlogPath
2020-10-06 17:07:48 +00:00
if blogPath == "/" {
blogPath = ""
2020-08-31 19:12:43 +00:00
}
2020-10-06 17:07:48 +00:00
// Indexes, Feeds
for _, section := range blogConfig.Sections {
if section.Name != "" {
path := blogPath + "/" + section.Name
2020-11-01 17:37:21 +00:00
handler := serveSection(blog, path, section)
r.With(cacheMiddleware, minifier.Middleware).Get(path, handler)
r.With(cacheMiddleware, minifier.Middleware).Get(path+feedPath, handler)
r.With(cacheMiddleware, minifier.Middleware).Get(path+paginationPath, handler)
2020-08-31 19:12:43 +00:00
}
2020-10-06 17:07:48 +00:00
}
for _, taxonomy := range blogConfig.Taxonomies {
if taxonomy.Name != "" {
path := blogPath + "/" + taxonomy.Name
r.With(cacheMiddleware, minifier.Middleware).Get(path, serveTaxonomy(blog, taxonomy))
values, err := allTaxonomyValues(blog, taxonomy.Name)
if err != nil {
return nil, err
}
for _, tv := range values {
vPath := path + "/" + urlize(tv)
2020-11-01 17:37:21 +00:00
handler := serveTaxonomyValue(blog, vPath, taxonomy, tv)
r.With(cacheMiddleware, minifier.Middleware).Get(vPath, handler)
r.With(cacheMiddleware, minifier.Middleware).Get(vPath+feedPath, handler)
r.With(cacheMiddleware, minifier.Middleware).Get(vPath+paginationPath, handler)
2020-10-06 17:07:48 +00:00
}
2020-08-31 19:12:43 +00:00
}
2020-08-25 18:55:32 +00:00
}
2020-10-06 17:07:48 +00:00
// Photos
2021-01-04 19:29:49 +00:00
if blogConfig.Photos != nil && blogConfig.Photos.Enabled {
2020-11-10 15:48:59 +00:00
photoPath := blogPath + blogConfig.Photos.Path
handler := servePhotos(blog, photoPath)
r.With(cacheMiddleware, minifier.Middleware).Get(photoPath, handler)
r.With(cacheMiddleware, minifier.Middleware).Get(photoPath+paginationPath, handler)
2020-10-06 17:07:48 +00:00
}
2020-09-21 16:03:05 +00:00
2020-11-15 10:34:48 +00:00
// Search
2021-01-04 19:29:49 +00:00
if blogConfig.Search != nil && blogConfig.Search.Enabled {
2020-11-15 10:34:48 +00:00
searchPath := blogPath + blogConfig.Search.Path
handler := serveSearch(blog, searchPath)
r.With(cacheMiddleware, minifier.Middleware).Get(searchPath, handler)
r.With(cacheMiddleware, minifier.Middleware).Post(searchPath, handler)
searchResultPath := searchPath + "/" + searchPlaceholder
resultHandler := serveSearchResults(blog, searchResultPath)
r.With(cacheMiddleware, minifier.Middleware).Get(searchResultPath, resultHandler)
r.With(cacheMiddleware, minifier.Middleware).Get(searchResultPath+feedPath, resultHandler)
r.With(cacheMiddleware, minifier.Middleware).Get(searchResultPath+paginationPath, resultHandler)
}
2021-01-04 19:29:49 +00:00
// Stats
if blogConfig.BlogStats != nil && blogConfig.BlogStats.Enabled {
statsPath := blogPath + blogConfig.BlogStats.Path
r.With(cacheMiddleware, minifier.Middleware).Get(statsPath, serveBlogStats(blog, statsPath))
}
2020-12-13 14:16:47 +00:00
// Year / month archives
dates, err := allPublishedDates(blog)
2020-12-13 14:16:47 +00:00
if err != nil {
return nil, err
}
for _, d := range dates {
// Year
yearPath := blogPath + "/" + fmt.Sprintf("%0004d", d.year)
yearHandler := serveDate(blog, yearPath, d.year, 0, 0)
2020-12-13 14:16:47 +00:00
r.With(cacheMiddleware, minifier.Middleware).Get(yearPath, yearHandler)
r.With(cacheMiddleware, minifier.Middleware).Get(yearPath+feedPath, yearHandler)
r.With(cacheMiddleware, minifier.Middleware).Get(yearPath+paginationPath, yearHandler)
// Specific month
monthPath := yearPath + "/" + fmt.Sprintf("%02d", d.month)
monthHandler := serveDate(blog, monthPath, d.year, d.month, 0)
r.With(cacheMiddleware, minifier.Middleware).Get(monthPath, monthHandler)
r.With(cacheMiddleware, minifier.Middleware).Get(monthPath+feedPath, monthHandler)
r.With(cacheMiddleware, minifier.Middleware).Get(monthPath+paginationPath, monthHandler)
// Specific day
dayPath := monthPath + "/" + fmt.Sprintf("%02d", d.day)
dayHandler := serveDate(blog, monthPath, d.year, d.month, d.day)
r.With(cacheMiddleware, minifier.Middleware).Get(dayPath, dayHandler)
r.With(cacheMiddleware, minifier.Middleware).Get(dayPath+feedPath, dayHandler)
r.With(cacheMiddleware, minifier.Middleware).Get(dayPath+paginationPath, dayHandler)
// Generic month
genericMonthPath := blogPath + "/x/" + fmt.Sprintf("%02d", d.month)
genericMonthHandler := serveDate(blog, genericMonthPath, 0, d.month, 0)
r.With(cacheMiddleware, minifier.Middleware).Get(genericMonthPath, genericMonthHandler)
r.With(cacheMiddleware, minifier.Middleware).Get(genericMonthPath+feedPath, genericMonthHandler)
r.With(cacheMiddleware, minifier.Middleware).Get(genericMonthPath+paginationPath, genericMonthHandler)
// Specific day
genericMonthDayPath := genericMonthPath + "/" + fmt.Sprintf("%02d", d.day)
genericMonthDayHandler := serveDate(blog, genericMonthDayPath, 0, d.month, d.day)
r.With(cacheMiddleware, minifier.Middleware).Get(genericMonthDayPath, genericMonthDayHandler)
r.With(cacheMiddleware, minifier.Middleware).Get(genericMonthDayPath+feedPath, genericMonthDayHandler)
r.With(cacheMiddleware, minifier.Middleware).Get(genericMonthDayPath+paginationPath, genericMonthDayHandler)
2020-12-13 14:16:47 +00:00
}
2020-10-06 17:07:48 +00:00
// Blog
2020-12-23 15:53:10 +00:00
if !blogConfig.PostAsHome {
var mw []func(http.Handler) http.Handler
if appConfig.ActivityPub.Enabled {
mw = []func(http.Handler) http.Handler{manipulateAsPath, cacheMiddleware, minifier.Middleware}
} else {
mw = []func(http.Handler) http.Handler{cacheMiddleware, minifier.Middleware}
}
handler := serveHome(blog, blogPath)
r.With(mw...).Get(fullBlogPath, handler)
r.With(cacheMiddleware, minifier.Middleware).Get(fullBlogPath+feedPath, handler)
r.With(cacheMiddleware, minifier.Middleware).Get(blogPath+paginationPath, handler)
}
2020-10-13 11:40:16 +00:00
// Custom pages
for _, cp := range blogConfig.CustomPages {
2020-11-01 17:37:21 +00:00
handler := serveCustomPage(blogConfig, cp)
2020-10-13 11:40:16 +00:00
if cp.Cache {
2020-11-01 17:37:21 +00:00
r.With(cacheMiddleware, minifier.Middleware).Get(cp.Path, handler)
2020-10-13 11:40:16 +00:00
} else {
2020-11-01 17:37:21 +00:00
r.With(minifier.Middleware).Get(cp.Path, handler)
2020-10-13 11:40:16 +00:00
}
}
2021-01-17 11:53:07 +00:00
// Random post
if rp := blogConfig.RandomPost; rp != nil && rp.Enabled {
randomPath := rp.Path
if randomPath == "" {
randomPath = "/random"
}
r.Get(blogPath+randomPath, redirectToRandomPost(blog))
}
2021-01-17 11:53:07 +00:00
// Editor
r.Route(blogPath+"/editor", func(mpRouter chi.Router) {
mpRouter.Use(middleware.NoCache, minifier.Middleware, authMiddleware)
mpRouter.Get("/", serveEditor(blog))
mpRouter.Post("/", serveEditorPost(blog))
})
2021-01-23 16:24:47 +00:00
// Comments
if commentsConfig := blogConfig.Comments; commentsConfig != nil && commentsConfig.Enabled {
commentsPath := blogPath + "/comment"
r.Route(commentsPath, func(cr chi.Router) {
cr.With(cacheMiddleware, minifier.Middleware).Get("/{id:[0-9]+}", serveComment(blog))
cr.With(captchaMiddleware).Post("/", createComment(blog, commentsPath))
// Admin
cr.With(minifier.Middleware, authMiddleware).Get("/", commentsAdmin)
cr.With(authMiddleware).Post("/delete", commentsAdminDelete)
})
}
2020-08-05 17:14:10 +00:00
}
2020-09-22 15:08:34 +00:00
// Sitemap
2020-10-17 15:36:18 +00:00
r.With(cacheMiddleware, minifier.Middleware).Get(sitemapPath, serveSitemap)
2020-09-22 15:08:34 +00:00
// Robots.txt - doesn't need cache, because it's too simple
r.Get("/robots.txt", serveRobotsTXT)
2020-10-15 18:54:43 +00:00
// Check redirects, then serve 404
r.With(cacheMiddleware, checkRegexRedirects, minifier.Middleware).NotFound(serve404)
2020-12-24 09:09:34 +00:00
r.With(minifier.Middleware).MethodNotAllowed(func(rw http.ResponseWriter, r *http.Request) {
serveError(rw, r, "", http.StatusMethodNotAllowed)
})
return r, nil
2020-07-28 19:17:07 +00:00
}
2020-10-16 13:35:38 +00:00
func securityHeaders(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Strict-Transport-Security", "max-age=31536000;")
w.Header().Add("Referrer-Policy", "no-referrer")
w.Header().Add("X-Content-Type-Options", "nosniff")
w.Header().Add("X-Frame-Options", "SAMEORIGIN")
w.Header().Add("X-Xss-Protection", "1; mode=block")
// TODO: Add CSP
next.ServeHTTP(w, r)
})
}
type dynamicHandler struct {
realHandler atomic.Value
}
func (d *dynamicHandler) swapHandler(h http.Handler) {
d.realHandler.Store(h)
}
func (d *dynamicHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
2020-11-10 15:40:22 +00:00
// Fix to use Path routing instead of RawPath routing in Chi
r.URL.RawPath = ""
// Serve request
d.realHandler.Load().(http.Handler).ServeHTTP(w, r)
}