@marcel91200 / caddy Mirror · read-only / commits / 14f50d9d
Fork 0

Fast and extensible multi-platform HTTP/1-2-3 web server with automatic HTTPS

Mirrored from https://github.com/Slazee/caddy.git

Synced Nov 14, 05:15 UTC

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.

Matthew Holt committed Jan 11, 2021 at 13:49 UTC 14f50d9dfb6c0da0da636829175a37b1864d23cf
1 file changed +24 -2
modules/caddyhttp/templates/tplcontext.go
+24 -2
@@ -153,7 +153,9 @@ func (c templateContext) executeTemplateInBuffer(tplName string, buf *bytes.Buff
153 "splitFrontMatter": c.funcSplitFrontMatter,
154 "listFiles": c.funcListFiles,
155 "env": c.funcEnv,
156 - "placeholder": c.placeholder,
156 + "placeholder": c.funcPlaceholder,
157 + "fileExists": c.funcFileExists,
158 + "httpError": c.funcHTTPError,
159 })
160
161 parsedTpl, err := tpl.Parse(buf.String())
@@ -166,7 +168,7 @@ func (c templateContext) executeTemplateInBuffer(tplName string, buf *bytes.Buff
168 return parsedTpl.Execute(buf, c)
169 }
170
169 -func (c templateContext) placeholder(name string) string {
171 +func (c templateContext) funcPlaceholder(name string) string {
172 repl := c.Req.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer)
173 value, _ := repl.GetString(name)
174 return value
@@ -323,6 +325,26 @@ func (c templateContext) funcListFiles(name string) ([]string, error) {
325 return names, nil
326 }
327
328 +// funcFileExists returns true if filename can be opened successfully.
329 +func (c templateContext) funcFileExists(filename string) (bool, error) {
330 + if c.Root == nil {
331 + return false, fmt.Errorf("root file system not specified")
332 + }
333 + file, err := c.Root.Open(filename)
334 + if err == nil {
335 + file.Close()
336 + return true, nil
337 + }
338 + return false, nil
339 +}
340 +
341 +// funcHTTPError returns a structured HTTP handler error. EXPERIMENTAL.
342 +// TODO: Requires https://github.com/golang/go/issues/34201 to be fixed.
343 +// Example usage might be: `{{if not (fileExists $includeFile)}}{{httpError 404}}{{end}}`
344 +func (c templateContext) funcHTTPError(statusCode int) (bool, error) {
345 + return false, caddyhttp.Error(statusCode, nil)
346 +}
347 +
348 // tplWrappedHeader wraps niladic functions so that they
349 // can be used in templates. (Template functions must
350 // return a value.)