From e425cd2afeb7e50b62ce4ecb2df6aed839e8c5f0 Mon Sep 17 00:00:00 2001 From: Laria Carolin Chabowski Date: Fri, 15 Oct 2021 17:38:58 +0200 Subject: Make template directory configurable on the command line The new --template-dir= flag allows the user to optionally specify the directory where the templates are located. It will default to the old way of using $GOPATH to find the template directory in the source directory of startpage. Being able to use --template-dir= can be especially useful, if you want to launch startpage when $GOPATH is not (yet) defined (e.g. when using systemd to bring up startpage). --- main.go | 30 ++++++++++++++++++++++++++---- 1 file changed, 26 insertions(+), 4 deletions(-) diff --git a/main.go b/main.go index cdae7f3..01c8c60 100644 --- a/main.go +++ b/main.go @@ -18,7 +18,17 @@ import ( var tpl *template.Template -func loadTemplate() { +func loadTemplateFromDir(templateDir string) error { + var err error + tpl, err = template.ParseFiles(path.Join(templateDir, "template.html")) + + if err != nil { + return fmt.Errorf("Could not load template from '%s': %w", templateDir, err) + } + return nil +} + +func loadTemplateFromGoPath() error { gopaths := strings.Split(os.Getenv("GOPATH"), ":") for _, p := range gopaths { var err error @@ -26,11 +36,19 @@ func loadTemplate() { path.Join(p, "src", "github.com", "silvasur", "startpage", "templates", "template.html"), ) if err == nil { - return + return nil } } - panic(errors.New("could not find template in $GOPATH/src/github.com/silvasur/startpage")) + return errors.New("could not find template in $GOPATH/src/github.com/silvasur/startpage") +} + +func loadTemplate(templateDir string) error { + if templateDir != "" { + return loadTemplateFromDir(templateDir) + } else { + return loadTemplateFromGoPath() + } } func buildWeatherProvider(config Config) *weather.WeatherProvider { @@ -52,9 +70,13 @@ func buildRedditImageProvider(config Config) *reddit_background.RedditImageProvi func main() { laddr := flag.String("laddr", ":25145", "Listen on this port") + templateDir := flag.String("template-dir", "", "Search for templates in this directory instead of default") + flag.Parse() - loadTemplate() + if err := loadTemplate(*templateDir); err != nil { + log.Fatalf("Failed loading template: %s", err) + } config, err := LoadConfig() if err != nil { -- cgit v1.2.3-54-g00ecf