aboutsummaryrefslogtreecommitdiff
path: root/cmd/server/handlers.go
blob: 5ea89cdfd1c71a138d02b64b11ec8355e6fcf617 (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
62
63
64
65
66
package main

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

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

var FeedPrefixDefault = ".feeds"

type App struct {
	ReIndexPath     string
	StaticDirectory string

	// 	Related to the Atom feed
	Title       string
	Description string // aka, "subtitle"
	Author      Author
	SiteURL     string
	FeedId      string
	Updated     page.PageTime
	FeedPrefix  string
}

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)))
}

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)
	rtr.PathPrefix("/").HandlerFunc(a.PageHandler)
	rtr.ServeHTTP(w, r)
}