aboutsummaryrefslogtreecommitdiff
path: root/page/http.go
blob: 7e1d780941c960a614cfe8a2d18c6afd71630a8a (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
package page

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

func SetupHandlers() {
	http.Handle("/static/", StaticHandler())
	http.HandleFunc("/", PageHandler)
}

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

	p := &Page{Path: 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", p.Path)
			p.Path = "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 StaticHandler() (h http.Handler) {
	return http.StripPrefix("/static/", http.FileServer(http.Dir("static")))
}