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 }