2019-07-01 06:07:58 +08:00
|
|
|
// Copyright 2015 Matthew Holt and The Caddy Authors
|
|
|
|
//
|
|
|
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
// you may not use this file except in compliance with the License.
|
|
|
|
// You may obtain a copy of the License at
|
|
|
|
//
|
|
|
|
// http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
//
|
|
|
|
// Unless required by applicable law or agreed to in writing, software
|
|
|
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
// See the License for the specific language governing permissions and
|
|
|
|
// limitations under the License.
|
|
|
|
|
2019-06-19 01:13:12 +08:00
|
|
|
package templates
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"fmt"
|
|
|
|
"io"
|
2023-04-25 00:36:37 +08:00
|
|
|
"io/fs"
|
2019-06-19 01:13:12 +08:00
|
|
|
"net"
|
|
|
|
"net/http"
|
2024-05-19 02:55:36 +08:00
|
|
|
"net/url"
|
2020-04-08 02:26:08 +08:00
|
|
|
"os"
|
2019-06-19 01:13:12 +08:00
|
|
|
"path"
|
2023-11-29 00:39:14 +08:00
|
|
|
"reflect"
|
2019-10-17 05:18:02 +08:00
|
|
|
"strconv"
|
2019-06-19 01:13:12 +08:00
|
|
|
"strings"
|
|
|
|
"sync"
|
2020-04-07 02:50:54 +08:00
|
|
|
"text/template"
|
2022-05-25 07:47:08 +08:00
|
|
|
"time"
|
2019-06-19 01:13:12 +08:00
|
|
|
|
2019-10-11 05:47:26 +08:00
|
|
|
"github.com/Masterminds/sprig/v3"
|
2023-05-27 00:16:28 +08:00
|
|
|
chromahtml "github.com/alecthomas/chroma/v2/formatters/html"
|
2022-05-25 07:47:08 +08:00
|
|
|
"github.com/dustin/go-humanize"
|
2019-12-24 03:56:41 +08:00
|
|
|
"github.com/yuin/goldmark"
|
2023-02-09 01:49:17 +08:00
|
|
|
highlighting "github.com/yuin/goldmark-highlighting/v2"
|
2019-12-24 03:56:41 +08:00
|
|
|
"github.com/yuin/goldmark/extension"
|
|
|
|
"github.com/yuin/goldmark/parser"
|
|
|
|
gmhtml "github.com/yuin/goldmark/renderer/html"
|
2023-11-29 00:39:14 +08:00
|
|
|
"go.uber.org/zap"
|
2023-08-14 23:41:15 +08:00
|
|
|
|
|
|
|
"github.com/caddyserver/caddy/v2"
|
|
|
|
"github.com/caddyserver/caddy/v2/modules/caddyhttp"
|
2019-06-19 01:13:12 +08:00
|
|
|
)
|
|
|
|
|
2021-05-01 10:17:23 +08:00
|
|
|
// TemplateContext is the TemplateContext with which HTTP templates are executed.
|
|
|
|
type TemplateContext struct {
|
2022-05-03 04:55:34 +08:00
|
|
|
Root http.FileSystem
|
|
|
|
Req *http.Request
|
2022-08-03 04:39:09 +08:00
|
|
|
Args []any // defined by arguments to funcInclude
|
2022-05-03 04:55:34 +08:00
|
|
|
RespHeader WrappedHeader
|
|
|
|
CustomFuncs []template.FuncMap // functions added by plugins
|
2019-06-19 05:17:48 +08:00
|
|
|
|
|
|
|
config *Templates
|
2021-09-18 03:00:36 +08:00
|
|
|
tpl *template.Template
|
2019-06-19 01:13:12 +08:00
|
|
|
}
|
|
|
|
|
2021-05-01 10:17:23 +08:00
|
|
|
// NewTemplate returns a new template intended to be evaluated with this
|
|
|
|
// context, as it is initialized with configuration from this context.
|
2021-09-18 03:00:36 +08:00
|
|
|
func (c *TemplateContext) NewTemplate(tplName string) *template.Template {
|
2023-11-29 00:39:14 +08:00
|
|
|
c.tpl = template.New(tplName).Option("missingkey=zero")
|
2021-05-01 10:17:23 +08:00
|
|
|
|
|
|
|
// customize delimiters, if applicable
|
|
|
|
if c.config != nil && len(c.config.Delimiters) == 2 {
|
2021-09-18 03:00:36 +08:00
|
|
|
c.tpl.Delims(c.config.Delimiters[0], c.config.Delimiters[1])
|
2021-05-01 10:17:23 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
// add sprig library
|
2021-09-18 03:00:36 +08:00
|
|
|
c.tpl.Funcs(sprigFuncMap)
|
2021-05-01 10:17:23 +08:00
|
|
|
|
2022-05-03 04:55:34 +08:00
|
|
|
// add all custom functions
|
|
|
|
for _, funcMap := range c.CustomFuncs {
|
|
|
|
c.tpl.Funcs(funcMap)
|
|
|
|
}
|
|
|
|
|
2021-05-01 10:17:23 +08:00
|
|
|
// add our own library
|
2021-09-18 03:00:36 +08:00
|
|
|
c.tpl.Funcs(template.FuncMap{
|
2021-05-01 10:17:23 +08:00
|
|
|
"include": c.funcInclude,
|
2023-05-27 00:16:28 +08:00
|
|
|
"readFile": c.funcReadFile,
|
2021-09-18 03:00:36 +08:00
|
|
|
"import": c.funcImport,
|
2021-05-01 10:17:23 +08:00
|
|
|
"httpInclude": c.funcHTTPInclude,
|
|
|
|
"stripHTML": c.funcStripHTML,
|
|
|
|
"markdown": c.funcMarkdown,
|
|
|
|
"splitFrontMatter": c.funcSplitFrontMatter,
|
|
|
|
"listFiles": c.funcListFiles,
|
2023-04-25 00:36:37 +08:00
|
|
|
"fileStat": c.funcFileStat,
|
2021-05-01 10:17:23 +08:00
|
|
|
"env": c.funcEnv,
|
|
|
|
"placeholder": c.funcPlaceholder,
|
|
|
|
"fileExists": c.funcFileExists,
|
|
|
|
"httpError": c.funcHTTPError,
|
2022-05-25 07:47:08 +08:00
|
|
|
"humanize": c.funcHumanize,
|
2023-11-29 00:39:14 +08:00
|
|
|
"maybe": c.funcMaybe,
|
2024-05-19 02:55:36 +08:00
|
|
|
"pathEscape": url.PathEscape,
|
2021-05-01 10:17:23 +08:00
|
|
|
})
|
2021-09-18 03:00:36 +08:00
|
|
|
return c.tpl
|
2021-05-01 10:17:23 +08:00
|
|
|
}
|
|
|
|
|
2019-12-24 03:56:41 +08:00
|
|
|
// OriginalReq returns the original, unmodified, un-rewritten request as
|
|
|
|
// it originally came in over the wire.
|
2021-05-01 10:17:23 +08:00
|
|
|
func (c TemplateContext) OriginalReq() http.Request {
|
2019-12-24 03:56:41 +08:00
|
|
|
or, _ := c.Req.Context().Value(caddyhttp.OriginalRequestCtxKey).(http.Request)
|
|
|
|
return or
|
|
|
|
}
|
|
|
|
|
2021-09-18 03:00:36 +08:00
|
|
|
// funcInclude returns the contents of filename relative to the site root and renders it in place.
|
2019-06-28 03:30:41 +08:00
|
|
|
// Note that included files are NOT escaped, so you should only include
|
|
|
|
// trusted files. If it is not trusted, be sure to use escaping functions
|
|
|
|
// in your template.
|
2022-08-03 04:39:09 +08:00
|
|
|
func (c TemplateContext) funcInclude(filename string, args ...any) (string, error) {
|
2021-11-30 01:29:40 +08:00
|
|
|
bodyBuf := bufPool.Get().(*bytes.Buffer)
|
|
|
|
bodyBuf.Reset()
|
|
|
|
defer bufPool.Put(bodyBuf)
|
|
|
|
|
|
|
|
err := c.readFileToBuffer(filename, bodyBuf)
|
2021-09-18 03:00:36 +08:00
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
|
|
|
|
c.Args = args
|
|
|
|
|
|
|
|
err = c.executeTemplateInBuffer(filename, bodyBuf)
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
|
|
|
|
return bodyBuf.String(), nil
|
|
|
|
}
|
|
|
|
|
2023-05-27 00:16:28 +08:00
|
|
|
// funcReadFile returns the contents of a filename relative to the site root.
|
|
|
|
// Note that included files are NOT escaped, so you should only include
|
|
|
|
// trusted files. If it is not trusted, be sure to use escaping functions
|
|
|
|
// in your template.
|
|
|
|
func (c TemplateContext) funcReadFile(filename string) (string, error) {
|
|
|
|
bodyBuf := bufPool.Get().(*bytes.Buffer)
|
|
|
|
bodyBuf.Reset()
|
|
|
|
defer bufPool.Put(bodyBuf)
|
|
|
|
|
|
|
|
err := c.readFileToBuffer(filename, bodyBuf)
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
|
|
|
|
return bodyBuf.String(), nil
|
|
|
|
}
|
|
|
|
|
2021-11-30 01:29:40 +08:00
|
|
|
// readFileToBuffer reads a file into a buffer
|
|
|
|
func (c TemplateContext) readFileToBuffer(filename string, bodyBuf *bytes.Buffer) error {
|
2019-06-19 01:13:12 +08:00
|
|
|
if c.Root == nil {
|
2021-11-30 01:29:40 +08:00
|
|
|
return fmt.Errorf("root file system not specified")
|
2019-06-19 01:13:12 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
file, err := c.Root.Open(filename)
|
|
|
|
if err != nil {
|
2021-11-30 01:29:40 +08:00
|
|
|
return err
|
2019-06-19 01:13:12 +08:00
|
|
|
}
|
|
|
|
defer file.Close()
|
|
|
|
|
|
|
|
_, err = io.Copy(bodyBuf, file)
|
|
|
|
if err != nil {
|
2021-11-30 01:29:40 +08:00
|
|
|
return err
|
2019-06-19 01:13:12 +08:00
|
|
|
}
|
|
|
|
|
2021-11-30 01:29:40 +08:00
|
|
|
return nil
|
2019-06-19 01:13:12 +08:00
|
|
|
}
|
|
|
|
|
2019-12-24 03:56:41 +08:00
|
|
|
// funcHTTPInclude returns the body of a virtual (lightweight) request
|
2019-06-28 03:30:41 +08:00
|
|
|
// to the given URI on the same server. Note that included bodies
|
|
|
|
// are NOT escaped, so you should only include trusted resources.
|
|
|
|
// If it is not trusted, be sure to use escaping functions yourself.
|
2021-05-01 10:17:23 +08:00
|
|
|
func (c TemplateContext) funcHTTPInclude(uri string) (string, error) {
|
2019-10-17 05:18:02 +08:00
|
|
|
// prevent virtual request loops by counting how many levels
|
|
|
|
// deep we are; and if we get too deep, return an error
|
|
|
|
recursionCount := 1
|
|
|
|
if numStr := c.Req.Header.Get(recursionPreventionHeader); numStr != "" {
|
|
|
|
num, err := strconv.Atoi(numStr)
|
|
|
|
if err != nil {
|
|
|
|
return "", fmt.Errorf("parsing %s: %v", recursionPreventionHeader, err)
|
|
|
|
}
|
|
|
|
if num >= 3 {
|
|
|
|
return "", fmt.Errorf("virtual request cycle")
|
|
|
|
}
|
|
|
|
recursionCount = num + 1
|
2019-06-19 01:13:12 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
buf := bufPool.Get().(*bytes.Buffer)
|
|
|
|
buf.Reset()
|
|
|
|
defer bufPool.Put(buf)
|
|
|
|
|
|
|
|
virtReq, err := http.NewRequest("GET", uri, nil)
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
2019-10-17 05:18:02 +08:00
|
|
|
virtReq.Host = c.Req.Host
|
2023-10-08 04:47:34 +08:00
|
|
|
virtReq.RemoteAddr = "127.0.0.1:10000" // https://github.com/caddyserver/caddy/issues/5835
|
2019-10-17 05:18:02 +08:00
|
|
|
virtReq.Header = c.Req.Header.Clone()
|
2021-10-16 23:09:16 +08:00
|
|
|
virtReq.Header.Set("Accept-Encoding", "identity") // https://github.com/caddyserver/caddy/issues/4352
|
2019-10-17 05:18:02 +08:00
|
|
|
virtReq.Trailer = c.Req.Trailer.Clone()
|
|
|
|
virtReq.Header.Set(recursionPreventionHeader, strconv.Itoa(recursionCount))
|
2019-06-19 01:13:12 +08:00
|
|
|
|
|
|
|
vrw := &virtualResponseWriter{body: buf, header: make(http.Header)}
|
|
|
|
server := c.Req.Context().Value(caddyhttp.ServerCtxKey).(http.Handler)
|
|
|
|
|
|
|
|
server.ServeHTTP(vrw, virtReq)
|
|
|
|
if vrw.status >= 400 {
|
|
|
|
return "", fmt.Errorf("http %d", vrw.status)
|
|
|
|
}
|
|
|
|
|
2019-06-19 05:17:48 +08:00
|
|
|
err = c.executeTemplateInBuffer(uri, buf)
|
2019-06-19 01:13:12 +08:00
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
|
2020-04-07 02:50:54 +08:00
|
|
|
return buf.String(), nil
|
2019-06-19 05:17:48 +08:00
|
|
|
}
|
|
|
|
|
2021-09-18 03:00:36 +08:00
|
|
|
// funcImport parses the filename into the current template stack. The imported
|
|
|
|
// file will be rendered within the current template by calling {{ block }} or
|
|
|
|
// {{ template }} from the standard template library. If the imported file has
|
|
|
|
// no {{ define }} blocks, the name of the import will be the path
|
|
|
|
func (c *TemplateContext) funcImport(filename string) (string, error) {
|
2021-11-30 01:29:40 +08:00
|
|
|
bodyBuf := bufPool.Get().(*bytes.Buffer)
|
|
|
|
bodyBuf.Reset()
|
|
|
|
defer bufPool.Put(bodyBuf)
|
|
|
|
|
|
|
|
err := c.readFileToBuffer(filename, bodyBuf)
|
2021-09-18 03:00:36 +08:00
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
|
|
|
|
_, err = c.tpl.Parse(bodyBuf.String())
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
return "", nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *TemplateContext) executeTemplateInBuffer(tplName string, buf *bytes.Buffer) error {
|
|
|
|
c.NewTemplate(tplName)
|
2019-12-24 03:56:41 +08:00
|
|
|
|
2021-09-18 03:00:36 +08:00
|
|
|
_, err := c.tpl.Parse(buf.String())
|
2019-06-19 01:13:12 +08:00
|
|
|
if err != nil {
|
2019-06-19 05:17:48 +08:00
|
|
|
return err
|
2019-06-19 01:13:12 +08:00
|
|
|
}
|
|
|
|
|
2019-06-19 05:17:48 +08:00
|
|
|
buf.Reset() // reuse buffer for output
|
|
|
|
|
2021-09-18 03:00:36 +08:00
|
|
|
return c.tpl.Execute(buf, c)
|
2019-06-19 01:13:12 +08:00
|
|
|
}
|
|
|
|
|
2021-05-01 10:17:23 +08:00
|
|
|
func (c TemplateContext) funcPlaceholder(name string) string {
|
2020-07-21 07:17:38 +08:00
|
|
|
repl := c.Req.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer)
|
2024-04-25 04:26:18 +08:00
|
|
|
|
|
|
|
// For safety, we don't want to allow the file placeholder in
|
|
|
|
// templates because it could be used to read arbitrary files
|
|
|
|
// if the template contents were not trusted.
|
|
|
|
repl = repl.WithoutFile()
|
|
|
|
|
2020-07-21 07:17:38 +08:00
|
|
|
value, _ := repl.GetString(name)
|
|
|
|
return value
|
|
|
|
}
|
|
|
|
|
2021-05-01 10:17:23 +08:00
|
|
|
func (TemplateContext) funcEnv(varName string) string {
|
2020-04-08 02:26:08 +08:00
|
|
|
return os.Getenv(varName)
|
|
|
|
}
|
|
|
|
|
2024-03-25 23:05:45 +08:00
|
|
|
// Cookie gets the value of a cookie with name.
|
2021-05-01 10:17:23 +08:00
|
|
|
func (c TemplateContext) Cookie(name string) string {
|
2019-06-19 01:13:12 +08:00
|
|
|
cookies := c.Req.Cookies()
|
|
|
|
for _, cookie := range cookies {
|
|
|
|
if cookie.Name == name {
|
|
|
|
return cookie.Value
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return ""
|
|
|
|
}
|
|
|
|
|
2023-10-16 08:58:46 +08:00
|
|
|
// RemoteIP gets the IP address of the connection's remote IP.
|
2021-05-01 10:17:23 +08:00
|
|
|
func (c TemplateContext) RemoteIP() string {
|
2019-06-19 01:13:12 +08:00
|
|
|
ip, _, err := net.SplitHostPort(c.Req.RemoteAddr)
|
|
|
|
if err != nil {
|
|
|
|
return c.Req.RemoteAddr
|
|
|
|
}
|
|
|
|
return ip
|
|
|
|
}
|
|
|
|
|
2023-10-16 08:58:46 +08:00
|
|
|
// ClientIP gets the IP address of the real client making the request
|
|
|
|
// if the request is trusted (see trusted_proxies), otherwise returns
|
|
|
|
// the connection's remote IP.
|
|
|
|
func (c TemplateContext) ClientIP() string {
|
|
|
|
address := caddyhttp.GetVar(c.Req.Context(), caddyhttp.ClientIPVarKey).(string)
|
|
|
|
clientIP, _, err := net.SplitHostPort(address)
|
|
|
|
if err != nil {
|
|
|
|
clientIP = address // no port
|
|
|
|
}
|
|
|
|
return clientIP
|
|
|
|
}
|
|
|
|
|
2019-06-19 01:13:12 +08:00
|
|
|
// Host returns the hostname portion of the Host header
|
|
|
|
// from the HTTP request.
|
2021-05-01 10:17:23 +08:00
|
|
|
func (c TemplateContext) Host() (string, error) {
|
2019-06-19 01:13:12 +08:00
|
|
|
host, _, err := net.SplitHostPort(c.Req.Host)
|
|
|
|
if err != nil {
|
|
|
|
if !strings.Contains(c.Req.Host, ":") {
|
|
|
|
// common with sites served on the default port 80
|
|
|
|
return c.Req.Host, nil
|
|
|
|
}
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
return host, nil
|
|
|
|
}
|
|
|
|
|
2019-12-24 03:56:41 +08:00
|
|
|
// funcStripHTML returns s without HTML tags. It is fairly naive
|
2019-06-19 01:13:12 +08:00
|
|
|
// but works with most valid HTML inputs.
|
2021-05-01 10:17:23 +08:00
|
|
|
func (TemplateContext) funcStripHTML(s string) string {
|
2019-06-19 01:13:12 +08:00
|
|
|
var buf bytes.Buffer
|
|
|
|
var inTag, inQuotes bool
|
|
|
|
var tagStart int
|
|
|
|
for i, ch := range s {
|
|
|
|
if inTag {
|
|
|
|
if ch == '>' && !inQuotes {
|
|
|
|
inTag = false
|
|
|
|
} else if ch == '<' && !inQuotes {
|
|
|
|
// false start
|
|
|
|
buf.WriteString(s[tagStart:i])
|
|
|
|
tagStart = i
|
|
|
|
} else if ch == '"' {
|
|
|
|
inQuotes = !inQuotes
|
|
|
|
}
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
if ch == '<' {
|
|
|
|
inTag = true
|
|
|
|
tagStart = i
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
buf.WriteRune(ch)
|
|
|
|
}
|
|
|
|
if inTag {
|
|
|
|
// false start
|
|
|
|
buf.WriteString(s[tagStart:])
|
|
|
|
}
|
|
|
|
return buf.String()
|
|
|
|
}
|
|
|
|
|
2019-12-24 03:56:41 +08:00
|
|
|
// funcMarkdown renders the markdown body as HTML. The resulting
|
2019-06-28 03:30:41 +08:00
|
|
|
// HTML is NOT escaped so that it can be rendered as HTML.
|
2022-08-03 04:39:09 +08:00
|
|
|
func (TemplateContext) funcMarkdown(input any) (string, error) {
|
2022-09-02 11:15:20 +08:00
|
|
|
inputStr := caddy.ToString(input)
|
2019-12-24 03:56:41 +08:00
|
|
|
|
|
|
|
md := goldmark.New(
|
|
|
|
goldmark.WithExtensions(
|
|
|
|
extension.GFM,
|
2020-03-19 13:38:37 +08:00
|
|
|
extension.Footnote,
|
2019-12-24 03:56:41 +08:00
|
|
|
highlighting.NewHighlighting(
|
|
|
|
highlighting.WithFormatOptions(
|
2023-05-27 00:16:28 +08:00
|
|
|
chromahtml.WithClasses(true),
|
2019-12-24 03:56:41 +08:00
|
|
|
),
|
|
|
|
),
|
|
|
|
),
|
|
|
|
goldmark.WithParserOptions(
|
|
|
|
parser.WithAutoHeadingID(),
|
|
|
|
),
|
|
|
|
goldmark.WithRendererOptions(
|
|
|
|
gmhtml.WithUnsafe(), // TODO: this is not awesome, maybe should be configurable?
|
|
|
|
),
|
|
|
|
)
|
|
|
|
|
|
|
|
buf := bufPool.Get().(*bytes.Buffer)
|
|
|
|
buf.Reset()
|
|
|
|
defer bufPool.Put(buf)
|
|
|
|
|
2020-11-23 05:50:29 +08:00
|
|
|
err := md.Convert([]byte(inputStr), buf)
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
2019-12-24 03:56:41 +08:00
|
|
|
|
2020-04-07 02:50:54 +08:00
|
|
|
return buf.String(), nil
|
2019-12-24 03:56:41 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
// splitFrontMatter parses front matter out from the beginning of input,
|
|
|
|
// and returns the separated key-value pairs and the body/content. input
|
|
|
|
// must be a "stringy" value.
|
2022-08-03 04:39:09 +08:00
|
|
|
func (TemplateContext) funcSplitFrontMatter(input any) (parsedMarkdownDoc, error) {
|
2022-09-02 11:15:20 +08:00
|
|
|
meta, body, err := extractFrontMatter(caddy.ToString(input))
|
2019-12-24 03:56:41 +08:00
|
|
|
if err != nil {
|
|
|
|
return parsedMarkdownDoc{}, err
|
|
|
|
}
|
|
|
|
return parsedMarkdownDoc{Meta: meta, Body: body}, nil
|
2019-06-19 01:13:12 +08:00
|
|
|
}
|
|
|
|
|
2019-12-24 03:56:41 +08:00
|
|
|
// funcListFiles reads and returns a slice of names from the given
|
2019-06-19 01:13:12 +08:00
|
|
|
// directory relative to the root of c.
|
2021-05-01 10:17:23 +08:00
|
|
|
func (c TemplateContext) funcListFiles(name string) ([]string, error) {
|
2019-06-19 01:13:12 +08:00
|
|
|
if c.Root == nil {
|
|
|
|
return nil, fmt.Errorf("root file system not specified")
|
|
|
|
}
|
|
|
|
|
|
|
|
dir, err := c.Root.Open(path.Clean(name))
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
defer dir.Close()
|
|
|
|
|
|
|
|
stat, err := dir.Stat()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
if !stat.IsDir() {
|
|
|
|
return nil, fmt.Errorf("%v is not a directory", name)
|
|
|
|
}
|
|
|
|
|
|
|
|
dirInfo, err := dir.Readdir(0)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
names := make([]string, len(dirInfo))
|
|
|
|
for i, fileInfo := range dirInfo {
|
|
|
|
names[i] = fileInfo.Name()
|
|
|
|
}
|
|
|
|
|
|
|
|
return names, nil
|
|
|
|
}
|
|
|
|
|
2021-01-12 04:49:20 +08:00
|
|
|
// funcFileExists returns true if filename can be opened successfully.
|
2021-05-01 10:17:23 +08:00
|
|
|
func (c TemplateContext) funcFileExists(filename string) (bool, error) {
|
2021-01-12 04:49:20 +08:00
|
|
|
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
|
|
|
|
}
|
|
|
|
|
2023-04-25 23:54:42 +08:00
|
|
|
// funcFileStat returns Stat of a filename
|
2023-04-25 00:36:37 +08:00
|
|
|
func (c TemplateContext) funcFileStat(filename string) (fs.FileInfo, error) {
|
|
|
|
if c.Root == nil {
|
|
|
|
return nil, fmt.Errorf("root file system not specified")
|
|
|
|
}
|
|
|
|
|
|
|
|
file, err := c.Root.Open(path.Clean(filename))
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
defer file.Close()
|
|
|
|
|
|
|
|
return file.Stat()
|
|
|
|
}
|
|
|
|
|
2021-09-15 23:55:57 +08:00
|
|
|
// funcHTTPError returns a structured HTTP handler error. EXPERIMENTAL; SUBJECT TO CHANGE.
|
|
|
|
// Example usage: `{{if not (fileExists $includeFile)}}{{httpError 404}}{{end}}`
|
2021-05-01 10:17:23 +08:00
|
|
|
func (c TemplateContext) funcHTTPError(statusCode int) (bool, error) {
|
2023-10-19 06:43:14 +08:00
|
|
|
// Delete some headers that may have been set by the underlying
|
|
|
|
// handler (such as file_server) which may break the error response.
|
|
|
|
c.RespHeader.Header.Del("Content-Length")
|
|
|
|
c.RespHeader.Header.Del("Content-Type")
|
|
|
|
c.RespHeader.Header.Del("Etag")
|
|
|
|
c.RespHeader.Header.Del("Last-Modified")
|
|
|
|
c.RespHeader.Header.Del("Accept-Ranges")
|
|
|
|
|
2021-01-12 04:49:20 +08:00
|
|
|
return false, caddyhttp.Error(statusCode, nil)
|
|
|
|
}
|
|
|
|
|
2022-05-25 07:47:08 +08:00
|
|
|
// funcHumanize transforms size and time inputs to a human readable format.
|
|
|
|
//
|
|
|
|
// Size inputs are expected to be integers, and are formatted as a
|
|
|
|
// byte size, such as "83 MB".
|
|
|
|
//
|
|
|
|
// Time inputs are parsed using the given layout (default layout is RFC1123Z)
|
|
|
|
// and are formatted as a relative time, such as "2 weeks ago".
|
|
|
|
// See https://pkg.go.dev/time#pkg-constants for time layout docs.
|
|
|
|
func (c TemplateContext) funcHumanize(formatType, data string) (string, error) {
|
|
|
|
// The format type can optionally be followed
|
|
|
|
// by a colon to provide arguments for the format
|
|
|
|
parts := strings.Split(formatType, ":")
|
|
|
|
|
|
|
|
switch parts[0] {
|
|
|
|
case "size":
|
|
|
|
dataint, dataerr := strconv.ParseUint(data, 10, 64)
|
|
|
|
if dataerr != nil {
|
|
|
|
return "", fmt.Errorf("humanize: size cannot be parsed: %s", dataerr.Error())
|
|
|
|
}
|
|
|
|
return humanize.Bytes(dataint), nil
|
|
|
|
|
|
|
|
case "time":
|
|
|
|
timelayout := time.RFC1123Z
|
|
|
|
if len(parts) > 1 {
|
|
|
|
timelayout = parts[1]
|
|
|
|
}
|
|
|
|
|
|
|
|
dataint, dataerr := time.Parse(timelayout, data)
|
|
|
|
if dataerr != nil {
|
|
|
|
return "", fmt.Errorf("humanize: time cannot be parsed: %s", dataerr.Error())
|
|
|
|
}
|
|
|
|
return humanize.Time(dataint), nil
|
|
|
|
}
|
|
|
|
|
|
|
|
return "", fmt.Errorf("no know function was given")
|
|
|
|
}
|
|
|
|
|
2023-11-29 00:39:14 +08:00
|
|
|
// funcMaybe invokes the plugged-in function named functionName if it is plugged in
|
|
|
|
// (is a module in the 'http.handlers.templates.functions' namespace). If it is not
|
|
|
|
// available, a log message is emitted.
|
|
|
|
//
|
|
|
|
// The first argument is the function name, and the rest of the arguments are
|
|
|
|
// passed on to the actual function.
|
|
|
|
//
|
|
|
|
// This function is useful for executing templates that use components that may be
|
|
|
|
// considered as optional in some cases (like during local development) where you do
|
|
|
|
// not want to require everyone to have a custom Caddy build to be able to execute
|
|
|
|
// your template.
|
|
|
|
//
|
|
|
|
// NOTE: This function is EXPERIMENTAL and subject to change or removal.
|
|
|
|
func (c TemplateContext) funcMaybe(functionName string, args ...any) (any, error) {
|
|
|
|
for _, funcMap := range c.CustomFuncs {
|
|
|
|
if fn, ok := funcMap[functionName]; ok {
|
|
|
|
val := reflect.ValueOf(fn)
|
|
|
|
if val.Kind() != reflect.Func {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
argVals := make([]reflect.Value, len(args))
|
|
|
|
for i, arg := range args {
|
|
|
|
argVals[i] = reflect.ValueOf(arg)
|
|
|
|
}
|
|
|
|
returnVals := val.Call(argVals)
|
|
|
|
switch len(returnVals) {
|
|
|
|
case 0:
|
|
|
|
return "", nil
|
|
|
|
case 1:
|
|
|
|
return returnVals[0].Interface(), nil
|
|
|
|
case 2:
|
|
|
|
var err error
|
|
|
|
if !returnVals[1].IsNil() {
|
|
|
|
err = returnVals[1].Interface().(error)
|
|
|
|
}
|
|
|
|
return returnVals[0].Interface(), err
|
|
|
|
default:
|
|
|
|
return nil, fmt.Errorf("maybe %s: invalid number of return values: %d", functionName, len(returnVals))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
c.config.logger.Named("maybe").Warn("template function could not be found; ignoring invocation", zap.String("name", functionName))
|
|
|
|
return "", nil
|
|
|
|
}
|
|
|
|
|
2021-05-01 10:17:23 +08:00
|
|
|
// WrappedHeader wraps niladic functions so that they
|
2019-06-19 01:13:12 +08:00
|
|
|
// can be used in templates. (Template functions must
|
|
|
|
// return a value.)
|
2021-05-01 10:17:23 +08:00
|
|
|
type WrappedHeader struct{ http.Header }
|
2019-06-19 01:13:12 +08:00
|
|
|
|
|
|
|
// Add adds a header field value, appending val to
|
|
|
|
// existing values for that field. It returns an
|
|
|
|
// empty string.
|
2021-05-01 10:17:23 +08:00
|
|
|
func (h WrappedHeader) Add(field, val string) string {
|
2019-06-19 01:13:12 +08:00
|
|
|
h.Header.Add(field, val)
|
|
|
|
return ""
|
|
|
|
}
|
|
|
|
|
|
|
|
// Set sets a header field value, overwriting any
|
|
|
|
// other values for that field. It returns an
|
|
|
|
// empty string.
|
2021-05-01 10:17:23 +08:00
|
|
|
func (h WrappedHeader) Set(field, val string) string {
|
2019-06-19 01:13:12 +08:00
|
|
|
h.Header.Set(field, val)
|
|
|
|
return ""
|
|
|
|
}
|
|
|
|
|
|
|
|
// Del deletes a header field. It returns an empty string.
|
2021-05-01 10:17:23 +08:00
|
|
|
func (h WrappedHeader) Del(field string) string {
|
2019-06-19 01:13:12 +08:00
|
|
|
h.Header.Del(field)
|
|
|
|
return ""
|
|
|
|
}
|
|
|
|
|
|
|
|
var bufPool = sync.Pool{
|
2022-08-03 04:39:09 +08:00
|
|
|
New: func() any {
|
2019-06-19 01:13:12 +08:00
|
|
|
return new(bytes.Buffer)
|
|
|
|
},
|
|
|
|
}
|
|
|
|
|
2019-12-24 03:56:41 +08:00
|
|
|
// at time of writing, sprig.FuncMap() makes a copy, thus
|
|
|
|
// involves iterating the whole map, so do it just once
|
2020-04-07 02:50:54 +08:00
|
|
|
var sprigFuncMap = sprig.TxtFuncMap()
|
2019-12-24 03:56:41 +08:00
|
|
|
|
2019-06-19 01:13:12 +08:00
|
|
|
const recursionPreventionHeader = "Caddy-Templates-Include"
|