From 8ea45f96742f825c49e900f42a01928554b5a6a0 Mon Sep 17 00:00:00 2001 From: Agniva De Sarker Date: Tue, 9 Jan 2018 10:44:40 +0530 Subject: [PATCH] blog: show a helpful error for invalid template directory Currently, if the blog binary is executed outside the root directory without any additional flags, it bails out with the following error - "open template/root.tmpl: no such file or directory" This CL prints out a more user friendly error which allows the user to learn that there is a flag with which the template directory can be set. Fixes golang/go#22622 Change-Id: I726e7c28f5e5036146769ca01516368f45a6262c Reviewed-on: https://go-review.googlesource.com/86855 Run-TryBot: Andrew Gerrand TryBot-Result: Gobot Gobot Reviewed-by: Andrew Gerrand --- blog/blog.go | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/blog/blog.go b/blog/blog.go index 23c8dc6d..4055b1b7 100644 --- a/blog/blog.go +++ b/blog/blog.go @@ -73,10 +73,17 @@ type Server struct { func NewServer(cfg Config) (*Server, error) { present.PlayEnabled = cfg.PlayEnabled + if notExist(cfg.TemplatePath) { + return nil, fmt.Errorf("template directory not found: %s", cfg.TemplatePath) + } root := filepath.Join(cfg.TemplatePath, "root.tmpl") parse := func(name string) (*template.Template, error) { + path := filepath.Join(cfg.TemplatePath, name) + if notExist(path) { + return nil, fmt.Errorf("template %s was not found in %s", name, cfg.TemplatePath) + } t := template.New("").Funcs(funcMap) - return t.ParseFiles(root, filepath.Join(cfg.TemplatePath, name)) + return t.ParseFiles(root, path) } s := &Server{cfg: cfg} @@ -422,3 +429,9 @@ type docsByTime []*Doc func (s docsByTime) Len() int { return len(s) } func (s docsByTime) Swap(i, j int) { s[i], s[j] = s[j], s[i] } func (s docsByTime) Less(i, j int) bool { return s[i].Time.After(s[j].Time) } + +// notExist reports whether the path exists or not. +func notExist(path string) bool { + _, err := os.Stat(path) + return os.IsNotExist(err) +}