aboutsummaryrefslogtreecommitdiff
path: root/page/misc.go
blob: 4b679456079184a348eea5817ae8a3c2107d1a93 (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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package page

import (
	"encoding/json"
	"net/http"
	"path/filepath"

	"gopkg.in/yaml.v3"
)

// logReq just maks that we've done a request in the log, format is roughly:
// remoteAddr, Method, statusCode, page path.
func logReq(r *http.Request, statusCode int) {
	Logger.Printf("%s %s %d %s",
		r.RemoteAddr,
		r.Method,
		statusCode,
		GetPagePath(r))
}

// logErr logs messages in the format of:
// RemoteAddr, Method, path: pagePath, message, error.
func logErr(r *http.Request, msg string, err error) {
	Logger.Printf("%s %s path: %s %s: %s",
		r.RemoteAddr,
		r.Method,
		GetPagePath(r),
		msg,
		err)
}

// plainResp sends a text/plain response down to the writer with the appropriate
// status code and a body of msg.
func plainResp(w http.ResponseWriter, statusCode int, msg string) {
	w.Header().Set("Content-type", "text/plain")
	w.WriteHeader(statusCode)
	_, _ = w.Write([]byte(msg))
}

// GetURLPath returns r.URL.Path, unless it's merely a slash, then
// it returns "index". Usefulf for defining your own handlers.
func GetURLPath(r *http.Request) string {
	u := r.URL.Path
	if u == "/" {
		u = "/index"
	}

	return u
}

// GetPagePath is the same as GetURLPath except that it joins it with
// the current directory ".". Also useful in defining your own handlers.
func GetPagePath(r *http.Request) string {
	return filepath.Join(".", GetURLPath(r))
}

// EncodeYaml is meant to be used in templating functions to encode
// arbitrary information as a yaml string.
func (p Page) EncodeYaml(data interface{}) string {
	if data == nil {
		data = p
	}

	b, err := yaml.Marshal(data)
	if err != nil {
		Logger.Println("Encountered error in EncodeYaml: ", err)
	}

	return string(b)
}

// EncodeJSON is meant to be used in templating functions to encode
// arbitrary information as a JSON string.
func (p Page) EncodeJSON(data interface{}) string {
	if data == nil {
		data = p
	}

	b, err := json.MarshalIndent(data, "", "  ")
	if err != nil {
		Logger.Println("Encountered error in EncodeJson: ", err)
	}

	return string(b)
}

// EncodeJSON is meant to be used in templating functions to encode
// arbitrary information as a JSON string.
func (p Page) EncodeJSONCompact(data interface{}) string {
	if data == nil {
		data = p
	}

	b, err := json.Marshal(data)
	if err != nil {
		Logger.Println("Encountered error in EncodeJSONCompact: ", err)
	}

	return string(b)
}