summaryrefslogtreecommitdiff
path: root/srv/src/http/index.go
blob: a39236144549d9ea5802464f586605901f1a3a4e (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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package http

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

	"github.com/mediocregopher/blog.mediocregopher.com/srv/http/apiutil"
	"github.com/mediocregopher/blog.mediocregopher.com/srv/post"
)

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
		}

		page, err := apiutil.StrToInt(r.FormValue("p"), 0)
		if err != nil {
			apiutil.BadRequest(
				rw, r, fmt.Errorf("invalid page number: %w", err),
			)
			return
		}

		tag := r.FormValue("tag")

		var (
			posts   []post.StoredPost
			hasMore bool
		)

		if tag == "" {
			posts, hasMore, err = a.params.PostStore.Get(page, pageCount)
		} else {
			posts, err = a.params.PostStore.GetByTag(tag)
		}

		if err != nil {
			apiutil.InternalServerError(
				rw, r, fmt.Errorf("fetching page %d of posts: %w", page, err),
			)
			return
		}

		tags, err := a.params.PostStore.GetTags()
		if err != nil {
			apiutil.InternalServerError(
				rw, r, fmt.Errorf("fething tags: %w", err),
			)
			return
		}

		tplPayload := struct {
			Posts              []post.StoredPost
			PrevPage, NextPage int
			Tags               []string
		}{
			Posts:    posts,
			PrevPage: -1,
			NextPage: -1,
			Tags:     tags,
		}

		if page > 0 {
			tplPayload.PrevPage = page - 1
		}

		if hasMore {
			tplPayload.NextPage = page + 1
		}

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