@marcel91200 / caddy Mirror · read-only / commits / 2943c418
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 13, 04:15 UTC

templates: Add `fileStat` function (#5497)

* Add isDir template function * Update modules/caddyhttp/templates/tplcontext.go Co-authored-by: Mohammed Al Sahaf <msaa1990@gmail.com> * Fix funcIsDir return value on error * Fix funcIsDir return false when root file system not specified * Add stat function, remove isDir function * Remove isDir function (really) * Rename stat to fileStat --------- Co-authored-by: Mohammed Al Sahaf <msaa1990@gmail.com>

Stéphane Mourey committed Apr 24, 2023 at 18:36 UTC 2943c41884278ec5fc44bcb55d2b9b088838cdc2
1 file changed +17
modules/caddyhttp/templates/tplcontext.go
+17
@@ -18,6 +18,7 @@ import (
18 "bytes"
19 "fmt"
20 "io"
21 + "io/fs"
22 "net"
23 "net/http"
24 "os"
@@ -79,6 +80,7 @@ func (c *TemplateContext) NewTemplate(tplName string) *template.Template {
80 "markdown": c.funcMarkdown,
81 "splitFrontMatter": c.funcSplitFrontMatter,
82 "listFiles": c.funcListFiles,
83 + "fileStat": c.funcFileStat,
84 "env": c.funcEnv,
85 "placeholder": c.funcPlaceholder,
86 "fileExists": c.funcFileExists,
@@ -395,6 +397,21 @@ func (c TemplateContext) funcFileExists(filename string) (bool, error) {
397 return false, nil
398 }
399
400 +// funcStat returns Stat of a filename
401 +func (c TemplateContext) funcFileStat(filename string) (fs.FileInfo, error) {
402 + if c.Root == nil {
403 + return nil, fmt.Errorf("root file system not specified")
404 + }
405 +
406 + file, err := c.Root.Open(path.Clean(filename))
407 + if err != nil {
408 + return nil, err
409 + }
410 + defer file.Close()
411 +
412 + return file.Stat()
413 +}
414 +
415 // funcHTTPError returns a structured HTTP handler error. EXPERIMENTAL; SUBJECT TO CHANGE.
416 // Example usage: `{{if not (fileExists $includeFile)}}{{httpError 404}}{{end}}`
417 func (c TemplateContext) funcHTTPError(statusCode int) (bool, error) {