1
Fork 0
mirror of https://github.com/caddyserver/caddy.git synced 2024-12-16 21:56:40 -05:00

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.
This commit is contained in:
Matthew Holt 2021-01-11 13:49:20 -07:00
parent 0bf2046da7
commit 14f50d9dfb
No known key found for this signature in database
GPG key ID: 2A349DD577D586A5

View file

@ -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.)