summaryrefslogtreecommitdiff
path: root/modules/caddyhttp
diff options
context:
space:
mode:
Diffstat (limited to 'modules/caddyhttp')
-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 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.)