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

import (
	"bytes"
	"errors"
	"io/fs"
	"net/http"
	"path/filepath"
)

// RenderMarkdown is analogous to Render, except it spits out rendered markdown
// as text/plain
func RenderMarkdown(w http.ResponseWriter, r *http.Request,
	path string, vars map[string]interface{}, statusCode int) {
	u := getURLPath(r)

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

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

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

	buf := &bytes.Buffer{}

	err := p.Render(buf)
	if err != nil {
		if errors.Is(err, fs.ErrNotExist) {
			w.WriteHeader(http.StatusNotFound)
			w.Header().Set("Content-type", "text/plain")
			w.Write([]byte("Not found"))

			return
		}

		Logger.Printf("%s %s path: %s rendering encountered: %s",
			r.RemoteAddr,
			r.Method,
			u,
			err)
		w.WriteHeader(http.StatusInternalServerError)
		w.Header().Set("Content-type", "text/plain")
		w.Write([]byte("Internal server error"))

		return
	}

	// Error was handled above
	md, _ := p.GetMarkdown()

	w.WriteHeader(statusCode)
	w.Header().Set("Content-type", "text/plain")

	_, err = w.Write([]byte(md))
	if err != nil {
		Logger.Printf("%s %s %d %s: while writing buf: %s",
			r.RemoteAddr,
			r.Method,
			statusCode,
			u,
			err)

		return
	}

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