aboutsummaryrefslogtreecommitdiff
path: root/http/main.go
blob: a4ed7f62fb512b41c83e2869157d9a60ee942624 (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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
// A mostly self explanatory package, it handles website specific
// HTTP requests
package http

import (
	"fmt"
	"log"
	"net/http"
	"os"
	"path/filepath"
	"strings"

	"riedstra.dev/mitch/go-website/local"
	"riedstra.dev/mitch/go-website/page"

	"github.com/gorilla/mux"
)

// NewPage is required to specify how we acquire a new page from a given URL
// since an interface is used, you can swap this out with a different
// library to load pages from different sources
var NewPage func(string) page.Page = func(u string) page.Page {
	return &local.Page{Path: u}
}

// ReindexRedirectTo is the path that we'll redirect to when a call to rebuild
// index is called
var ReindexRedirectTo = "/fullIndex"

func GetHandler() *mux.Router {
	if NewPage == nil {
		fmt.Fprintln(os.Stderr, "Warning, global NewPage method is not defined!")
	}

	r := mux.NewRouter()
	r.HandleFunc("/rebuildIndex/", RebuildIndexHandler)
	r.PathPrefix("/static/").Handler(StaticHandler())
	r.PathPrefix("/").HandlerFunc(PageHandler)
	return r
}

func PageHandler(w http.ResponseWriter, r *http.Request) {
	u := r.URL.Path
	if u == "/" {
		u = "/index"
	}
	u = filepath.Join(".", u)
	log.Println(u)

	p := NewPage(u)
	err := p.Render(w)
	if err != nil {
		if strings.HasSuffix(err.Error(), "no such file or directory") {
			log.Printf("Page '%s' not found, trying 404", u)
			p = NewPage("404")
			w.WriteHeader(404)
			err := p.Render(w)
			if err != nil {
				log.Println(err)
				http.Error(w, "Internal server error", 500)
				return
			}
			return
		} else {
			log.Println(err)
			http.Error(w, "Internal server error", 500)
			return
		}
	}

}

func RebuildIndexHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method != "POST" {
		p := NewPage("index")
		_ = p.RebuildIndex()
		http.Redirect(w, r, ReindexRedirectTo, 302)
	}
}

func StaticHandler() http.Handler {
	return http.StripPrefix("/static/", http.FileServer(http.Dir("static")))
}