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
101
102
103
104
105
106
107
108
109
110
|
package page
import (
"os"
"io/fs"
"errors"
"path/filepath"
"net/http"
"sanine.net/git/phlox/config"
)
type Pages struct {
Login string
LoggedIn string
Error404 string
Error500 string
}
func (p Pages) ServeLogin(w http.ResponseWriter) {
w.Write([]byte(p.Login))
}
func (p Pages) ServeLoggedIn(w http.ResponseWriter) {
w.Write([]byte(p.LoggedIn))
}
func (p Pages) ServeError404(w http.ResponseWriter) {
w.WriteHeader(http.StatusNotFound)
w.Write([]byte(p.Error404))
}
func (p Pages) ServeError500(w http.ResponseWriter) {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(p.Error500))
}
type DefaultPage func() (string, error)
func fileExists(filename string) (bool, error) {
_, err := os.Stat(filename)
if err == nil {
return true, nil
} else if errors.Is(err, fs.ErrNotExist) {
return false, nil
} else {
// unknown error
return false, err
}
}
func loadPage(c config.Config, filename string, fallback DefaultPage) (string, error) {
fullPath := filepath.Join(c.AssetDirectory, filename)
exist, err := fileExists(fullPath)
if err != nil {
return "", err
}
if exist {
bytes, err := os.ReadFile(fullPath)
if err != nil {
return "", err
}
return string(bytes), nil
} else {
// file does not exist
// use built-in
str, err := fallback()
if err != nil {
return "", err
}
return str, nil
}
}
func LoadPages(c config.Config) (Pages, error) {
var pages Pages
var err error
pages.Login, err = loadPage(c, "login.html", DefaultLogin)
if err != nil {
return Pages{}, err
}
pages.LoggedIn, err = loadPage(c, "logged_in.html", DefaultLoggedIn)
if err != nil {
return Pages{}, err
}
pages.Error404, err = loadPage(c, "404.html", DefaultError404)
if err != nil {
return Pages{}, err
}
pages.Error500, err = loadPage(c, "500.html", DefaultError500)
if err != nil {
return Pages{}, err
}
return pages, nil
}
|