aboutsummaryrefslogtreecommitdiff
path: root/page/render.go
blob: 6cbabf97ab7e3db43f512f89263c7d402cc4d27b (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
package page

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

// Render is a lower level option, allowing you to specify local
// variables and the status code in which to return.
func Render(w http.ResponseWriter, r *http.Request,
	path string, vars map[string]interface{}, statusCode int) {
	u := r.URL.Path
	if u == "/" {
		u = "/index"
	}

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

	// Sepcifically use the specified path for the page
	p := NewPage(path)

	if vars != nil {
		p.Vars = vars
	}

	err := p.Render(w)
	if err != nil {
		if strings.HasSuffix(err.Error(), "no such file or directory") {
			Logger.Printf("%s %s %d %s",
				r.RemoteAddr,
				r.Method,
				http.StatusNotFound,
				u)

			p = NewPage("404")

			w.WriteHeader(http.StatusNotFound)

			err := p.Render(w)
			if err != nil {
				Logger.Printf("%s %s path: %s while trying 404: %s",
					r.RemoteAddr,
					r.Method,
					u,
					err)
				http.Error(w, "Internal server error",
					http.StatusInternalServerError)

				return
			}

			return
		}

		Logger.Printf("%s %s path: %s encountered: %s",
			r.RemoteAddr,
			r.Method,
			u,
			err)
		http.Error(w, "Internal server error",
			http.StatusInternalServerError)

		return
	}

	Logger.Printf("%s %s %d %s", r.RemoteAddr, r.Method, statusCode, u)
}

// RenderWithVars allows you to specify a specific page and whether or not
// you wish to override vars. If left nil they will not be overridden.
// Also see RenderForPath if you don't need to override them.
func RenderWithVars(w http.ResponseWriter, r *http.Request,
	path string, vars map[string]interface{}) {
	Render(w, r, path, vars, http.StatusOK)
}

// RenderForPath takes the path to a page and finish up the rendering
// Allowing you to place logic on what page is rendered by your handlers.
func RenderForPath(w http.ResponseWriter, r *http.Request, path string) {
	RenderWithVars(w, r, path, nil)
}