From 14f50d9dfb6c0da0da636829175a37b1864d23cf Mon Sep 17 00:00:00 2001 From: Matthew Holt Date: Mon, 11 Jan 2021 13:49:20 -0700 Subject: templates: Add fileExists and httpError template actions The httpError function isn't particularly useful until https://github.com/golang/go/issues/34201 is fixed in the Go standard lib. --- modules/caddyhttp/templates/tplcontext.go | 26 ++++++++++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) (limited to 'modules/caddyhttp/templates') diff --git a/modules/caddyhttp/templates/tplcontext.go b/modules/caddyhttp/templates/tplcontext.go index 8bdaeec..1212ee2 100644 --- a/modules/caddyhttp/templates/tplcontext.go +++ b/modules/caddyhttp/templates/tplcontext.go @@ -153,7 +153,9 @@ func (c templateContext) executeTemplateInBuffer(tplName string, buf *bytes.Buff "splitFrontMatter": c.funcSplitFrontMatter, "listFiles": c.funcListFiles, "env": c.funcEnv, - "placeholder": c.placeholder, + "placeholder": c.funcPlaceholder, + "fileExists": c.funcFileExists, + "httpError": c.funcHTTPError, }) parsedTpl, err := tpl.Parse(buf.String()) @@ -166,7 +168,7 @@ func (c templateContext) executeTemplateInBuffer(tplName string, buf *bytes.Buff return parsedTpl.Execute(buf, c) } -func (c templateContext) placeholder(name string) string { +func (c templateContext) funcPlaceholder(name string) string { repl := c.Req.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer) value, _ := repl.GetString(name) return value @@ -323,6 +325,26 @@ func (c templateContext) funcListFiles(name string) ([]string, error) { return names, nil } +// funcFileExists returns true if filename can be opened successfully. +func (c templateContext) funcFileExists(filename string) (bool, error) { + if c.Root == nil { + return false, fmt.Errorf("root file system not specified") + } + file, err := c.Root.Open(filename) + if err == nil { + file.Close() + return true, nil + } + return false, nil +} + +// funcHTTPError returns a structured HTTP handler error. EXPERIMENTAL. +// TODO: Requires https://github.com/golang/go/issues/34201 to be fixed. +// Example usage might be: `{{if not (fileExists $includeFile)}}{{httpError 404}}{{end}}` +func (c templateContext) funcHTTPError(statusCode int) (bool, error) { + return false, caddyhttp.Error(statusCode, nil) +} + // tplWrappedHeader wraps niladic functions so that they // can be used in templates. (Template functions must // return a value.) -- cgit v1.2.3