diff options
author | sanine <sanine.not@pm.me> | 2023-05-14 20:12:06 -0500 |
---|---|---|
committer | sanine <sanine.not@pm.me> | 2023-05-14 20:12:06 -0500 |
commit | 5b4251fd39c43e4cfed27e032a4efb2bbba28e38 (patch) | |
tree | f51840d5607eba0db9262045e330a1c8b8393449 /page/page.go | |
parent | 9571ccc4d87907067df98edeaa78f0c167fcff43 (diff) |
add auth & pages
Diffstat (limited to 'page/page.go')
-rw-r--r-- | page/page.go | 110 |
1 files changed, 110 insertions, 0 deletions
diff --git a/page/page.go b/page/page.go new file mode 100644 index 0000000..c58a344 --- /dev/null +++ b/page/page.go @@ -0,0 +1,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 +} |