summaryrefslogtreecommitdiffhomepage
path: root/modules
diff options
context:
space:
mode:
authorMatthew Holt <[email protected]>2021-01-11 13:49:20 -0700
committerMatthew Holt <[email protected]>2021-01-11 13:49:20 -0700
commit14f50d9dfb6c0da0da636829175a37b1864d23cf (patch)
treed46d0f93a4bc8cc59ec6a2db269e3759e9455a7f /modules
parent0bf2046da7f2f5bf1b7d9fa055ae28de9a06ddaf (diff)
downloadcaddy-14f50d9dfb6c0da0da636829175a37b1864d23cf.tar.gz
caddy-14f50d9dfb6c0da0da636829175a37b1864d23cf.zip
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.
Diffstat (limited to 'modules')
-rw-r--r--modules/caddyhttp/templates/tplcontext.go26
1 files changed, 24 insertions, 2 deletions
diff --git a/modules/caddyhttp/templates/tplcontext.go b/modules/caddyhttp/templates/tplcontext.go
index 8bdaeec7e..1212ee20f 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.)