summaryrefslogtreecommitdiff
path: root/src/http/index.go
blob: 21c6c1614913d88433714d553cf307794fa06759 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package http

import (
	"net/http"
	"path/filepath"
	"regexp"
	"strings"
)

func (a *api) renderIndexHandler() http.Handler {

	legacyPostPathRegexp := regexp.MustCompile(
		`^/[0-9]{4}/[0-9]{2}/[0-9]{2}/([^/.]+)\.html$`,
	)

	tpl := a.mustParseBasedTpl("index.html")
	const pageCount = 10

	return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {

		path := r.URL.Path

		if matches := legacyPostPathRegexp.FindStringSubmatch(path); len(matches) == 2 {
			id := matches[1]
			http.Redirect(rw, r, filepath.Join("/posts", id), http.StatusMovedPermanently)
			return
		}

		if !strings.HasSuffix(path, "/") && filepath.Base(path) != "index.html" {
			http.Error(rw, "Page not found", 404)
			return
		}

		executeTemplate(rw, r, tpl, nil)
	})
}