aboutsummaryrefslogtreecommitdiff
path: root/cmd/server/handlers.go
blob: 61bb623c8e142b0fe45a40cccb7288bf147b544d (plain) (blame)
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
package main

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

	"github.com/gorilla/mux"
	"riedstra.dev/mitch/go-website/page"
	"riedstra.dev/mitch/go-website/rediscache"
)

func (a *App) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	rtr := mux.NewRouter()
	rtr.HandleFunc(a.ReIndexPath, a.RebuildIndexHandler)
	rtr.PathPrefix("/static/").Handler(a.StaticHandler())
	rtr.PathPrefix(fmt.Sprintf("/%s/{tag}", a.FeedPrefix)).HandlerFunc(
		a.FeedHandler)

	if a.redisPool != nil {
		rtr.PathPrefix("/").Handler(rediscache.Handle(
			a.redisPool, a.RedisKey, http.HandlerFunc(a.PageHandler)))
	} else {
		rtr.PathPrefix("/").Handler(http.HandlerFunc(a.PageHandler))
	}

	rtr.ServeHTTP(w, r)
}

func (a *App) PageHandler(w http.ResponseWriter, r *http.Request) {
	u := r.URL.Path
	if u == "/" {
		u = "/index"
	}

	u = filepath.Join(".", u)

	page.RenderForPath(w, r, u)
}

func (a *App) RebuildIndexHandler(w http.ResponseWriter, r *http.Request) {
	u := r.URL.Path
	if u == "/" {
		u = "/index"
	}

	u = filepath.Join(".", u)

	p := page.NewPage("index")
	err := p.RebuildIndex()

	page.RenderWithVars(w, r, u, map[string]interface{}{
		"IndexError": err,
	})
}

// StaticHandler simply returns a HTTP handler that looks at the current
// directory and exposes `static` via HTTP `/static`.
func (a *App) StaticHandler() http.Handler {
	return http.StripPrefix("/static/", http.FileServer(http.Dir(a.StaticDirectory)))
}