2019-07-01 01:07:58 +03: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-18 20:13:12 +03:00
|
|
|
package templates
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"fmt"
|
|
|
|
"io"
|
2023-04-24 19:36:37 +03:00
|
|
|
"io/fs"
|
2019-06-18 20:13:12 +03:00
|
|
|
"net"
|
|
|
|
"net/http"
|
2020-04-07 21:26:08 +03:00
|
|
|
"os"
|
2019-06-18 20:13:12 +03:00
|
|
|
"path"
|
2019-10-17 00:18:02 +03:00
|
|
|
"strconv"
|
2019-06-18 20:13:12 +03:00
|
|
|
"strings"
|
|
|
|
"sync"
|
2020-04-06 21:50:54 +03:00
|
|
|
"text/template"
|
2022-05-25 02:47:08 +03:00
|
|
|
"time"
|
2019-06-18 20:13:12 +03:00
|
|
|
|
2019-10-11 00:47:26 +03:00
|
|
|
"github.com/Masterminds/sprig/v3"
|
2023-02-08 20:49:17 +03:00
|
|
|
"github.com/alecthomas/chroma/v2/formatters/html"
|
2020-07-21 02:17:38 +03:00
|
|
|
"github.com/caddyserver/caddy/v2"
|
2019-07-02 21:37:06 +03:00
|
|
|
"github.com/caddyserver/caddy/v2/modules/caddyhttp"
|
2022-05-25 02:47:08 +03:00
|
|
|
"github.com/dustin/go-humanize"
|
2019-12-23 22:56:41 +03:00
|
|
|
"github.com/yuin/goldmark"
|
2023-02-08 20:49:17 +03:00
|
|
|
highlighting "github.com/yuin/goldmark-highlighting/v2"
|
2019-12-23 22:56:41 +03:00
|
|
|
"github.com/yuin/goldmark/extension"
|
|
|
|
"github.com/yuin/goldmark/parser"
|
|
|
|
gmhtml "github.com/yuin/goldmark/renderer/html"
|
2019-06-18 20:13:12 +03:00
|
|
|
)
|
|
|
|
|
2021-05-01 05:17:23 +03:00
|
|
|
// TemplateContext is the TemplateContext with which HTTP templates are executed.
|
|
|
|
type TemplateContext struct {
|
2022-05-02 23:55:34 +03:00
|
|
|
Root http.FileSystem
|
|
|
|
Req *http.Request
|
2022-08-02 23:39:09 +03:00
|
|
|
Args []any // defined by arguments to funcInclude
|
2022-05-02 23:55:34 +03:00
|
|
|
RespHeader WrappedHeader
|
|
|
|
CustomFuncs []template.FuncMap // functions added by plugins
|
2019-06-19 00:17:48 +03:00
|
|
|
|
|
|
|
config *Templates
|
2021-09-17 22:00:36 +03:00
|
|
|
tpl *template.Template
|
2019-06-18 20:13:12 +03:00
|
|
|
}
|
|
|
|
|
2021-05-01 05:17:23 +03:00
|
|
|
// NewTemplate returns a new template intended to be evaluated with this
|
|
|
|
// context, as it is initialized with configuration from this context.
|
2021-09-17 22:00:36 +03:00
|
|
|
func (c *TemplateContext) NewTemplate(tplName string) *template.Template {
|
|
|
|
c.tpl = template.New(tplName)
|
2021-05-01 05:17:23 +03:00
|
|
|
|
|
|
|
// customize delimiters, if applicable
|
|
|
|
if c.config != nil && len(c.config.Delimiters) == 2 {
|
2021-09-17 22:00:36 +03:00
|
|
|
c.tpl.Delims(c.config.Delimiters[0], c.config.Delimiters[1])
|
2021-05-01 05:17:23 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// add sprig library
|
2021-09-17 22:00:36 +03:00
|
|
|
c.tpl.Funcs(sprigFuncMap)
|
2021-05-01 05:17:23 +03:00
|
|
|
|
2022-05-02 23:55:34 +03:00
|
|
|
// add all custom functions
|
|
|
|
for _, funcMap := range c.CustomFuncs {
|
|
|
|
c.tpl.Funcs(funcMap)
|
|
|
|
}
|
|
|
|
|
2021-05-01 05:17:23 +03:00
|
|
|
// add our own library
|
2021-09-17 22:00:36 +03:00
|
|
|
c.tpl.Funcs(template.FuncMap{
|
2021-05-01 05:17:23 +03:00
|
|
|
"include": c.funcInclude,
|
2021-09-17 22:00:36 +03:00
|
|
|
"import": c.funcImport,
|
2021-05-01 05:17:23 +03:00
|
|
|
"httpInclude": c.funcHTTPInclude,
|
|
|
|
"stripHTML": c.funcStripHTML,
|
|
|
|
"markdown": c.funcMarkdown,
|
|
|
|
"splitFrontMatter": c.funcSplitFrontMatter,
|
|
|
|
"listFiles": c.funcListFiles,
|
2023-04-24 19:36:37 +03:00
|
|
|
"fileStat": c.funcFileStat,
|
2021-05-01 05:17:23 +03:00
|
|
|
"env": c.funcEnv,
|
|
|
|
"placeholder": c.funcPlaceholder,
|
|
|
|
"fileExists": c.funcFileExists,
|
|
|
|
"httpError": c.funcHTTPError,
|
2022-05-25 02:47:08 +03:00
|
|
|
"humanize": c.funcHumanize,
|
2021-05-01 05:17:23 +03:00
|
|
|
})
|
2021-09-17 22:00:36 +03:00
|
|
|
return c.tpl
|
2021-05-01 05:17:23 +03:00
|
|
|
}
|
|
|
|
|
2019-12-23 22:56:41 +03:00
|
|
|
// OriginalReq returns the original, unmodified, un-rewritten request as
|
|
|
|
// it originally came in over the wire.
|
2021-05-01 05:17:23 +03:00
|
|
|
func (c TemplateContext) OriginalReq() http.Request {
|
2019-12-23 22:56:41 +03:00
|
|
|
or, _ := c.Req.Context().Value(caddyhttp.OriginalRequestCtxKey).(http.Request)
|
|
|
|
return or
|
|
|
|
}
|
|
|
|
|
2021-09-17 22:00:36 +03:00
|
|
|
// funcInclude returns the contents of filename relative to the site root and renders it in place.
|
2019-06-27 22:30:41 +03: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-02 23:39:09 +03:00
|
|
|
func (c TemplateContext) funcInclude(filename string, args ...any) (string, error) {
|
2021-11-29 20:29:40 +03:00
|
|
|
|
|
|
|
bodyBuf := bufPool.Get().(*bytes.Buffer)
|
|
|
|
bodyBuf.Reset()
|
|
|
|
defer bufPool.Put(bodyBuf)
|
|
|
|
|
|
|
|
err := c.readFileToBuffer(filename, bodyBuf)
|
2021-09-17 22:00:36 +03:00
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
|
|
|
|
c.Args = args
|
|
|
|
|
|
|
|
err = c.executeTemplateInBuffer(filename, bodyBuf)
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
|
|
|
|
return bodyBuf.String(), nil
|
|
|
|
}
|
|
|
|
|
2021-11-29 20:29:40 +03:00
|
|
|
// readFileToBuffer reads a file into a buffer
|
|
|
|
func (c TemplateContext) readFileToBuffer(filename string, bodyBuf *bytes.Buffer) error {
|
2019-06-18 20:13:12 +03:00
|
|
|
if c.Root == nil {
|
2021-11-29 20:29:40 +03:00
|
|
|
return fmt.Errorf("root file system not specified")
|
2019-06-18 20:13:12 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
file, err := c.Root.Open(filename)
|
|
|
|
if err != nil {
|
2021-11-29 20:29:40 +03:00
|
|
|
return err
|
2019-06-18 20:13:12 +03:00
|
|
|
}
|
|
|
|
defer file.Close()
|
|
|
|
|
|
|
|
_, err = io.Copy(bodyBuf, file)
|
|
|
|
if err != nil {
|
2021-11-29 20:29:40 +03:00
|
|
|
return err
|
2019-06-18 20:13:12 +03:00
|
|
|
}
|
|
|
|
|
2021-11-29 20:29:40 +03:00
|
|
|
return nil
|
2019-06-18 20:13:12 +03:00
|
|
|
}
|
|
|
|
|
2019-12-23 22:56:41 +03:00
|
|
|
// funcHTTPInclude returns the body of a virtual (lightweight) request
|
2019-06-27 22:30:41 +03: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 05:17:23 +03:00
|
|
|
func (c TemplateContext) funcHTTPInclude(uri string) (string, error) {
|
2019-10-17 00:18:02 +03: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-18 20:13:12 +03: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 00:18:02 +03:00
|
|
|
virtReq.Host = c.Req.Host
|
|
|
|
virtReq.Header = c.Req.Header.Clone()
|
2021-10-16 18:09:16 +03:00
|
|
|
virtReq.Header.Set("Accept-Encoding", "identity") // https://github.com/caddyserver/caddy/issues/4352
|
2019-10-17 00:18:02 +03:00
|
|
|
virtReq.Trailer = c.Req.Trailer.Clone()
|
|
|
|
virtReq.Header.Set(recursionPreventionHeader, strconv.Itoa(recursionCount))
|
2019-06-18 20:13:12 +03: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 00:17:48 +03:00
|
|
|
err = c.executeTemplateInBuffer(uri, buf)
|
2019-06-18 20:13:12 +03:00
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
|
2020-04-06 21:50:54 +03:00
|
|
|
return buf.String(), nil
|
2019-06-19 00:17:48 +03:00
|
|
|
}
|
|
|
|
|
2021-09-17 22:00:36 +03: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-29 20:29:40 +03:00
|
|
|
|
|
|
|
bodyBuf := bufPool.Get().(*bytes.Buffer)
|
|
|
|
bodyBuf.Reset()
|
|
|
|
defer bufPool.Put(bodyBuf)
|
|
|
|
|
|
|
|
err := c.readFileToBuffer(filename, bodyBuf)
|
2021-09-17 22:00:36 +03: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-23 22:56:41 +03:00
|
|
|
|
2021-09-17 22:00:36 +03:00
|
|
|
_, err := c.tpl.Parse(buf.String())
|
2019-06-18 20:13:12 +03:00
|
|
|
if err != nil {
|
2019-06-19 00:17:48 +03:00
|
|
|
return err
|
2019-06-18 20:13:12 +03:00
|
|
|
}
|
|
|
|
|
2019-06-19 00:17:48 +03:00
|
|
|
buf.Reset() // reuse buffer for output
|
|
|
|
|
2021-09-17 22:00:36 +03:00
|
|
|
return c.tpl.Execute(buf, c)
|
2019-06-18 20:13:12 +03:00
|
|
|
}
|
|
|
|
|
2021-05-01 05:17:23 +03:00
|
|
|
func (c TemplateContext) funcPlaceholder(name string) string {
|
2020-07-21 02:17:38 +03:00
|
|
|
repl := c.Req.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer)
|
|
|
|
value, _ := repl.GetString(name)
|
|
|
|
return value
|
|
|
|
}
|
|
|
|
|
2021-05-01 05:17:23 +03:00
|
|
|
func (TemplateContext) funcEnv(varName string) string {
|
2020-04-07 21:26:08 +03:00
|
|
|
return os.Getenv(varName)
|
|
|
|
}
|
|
|
|
|
2019-06-18 20:13:12 +03:00
|
|
|
// Cookie gets the value of a cookie with name name.
|
2021-05-01 05:17:23 +03:00
|
|
|
func (c TemplateContext) Cookie(name string) string {
|
2019-06-18 20:13:12 +03:00
|
|
|
cookies := c.Req.Cookies()
|
|
|
|
for _, cookie := range cookies {
|
|
|
|
if cookie.Name == name {
|
|
|
|
return cookie.Value
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return ""
|
|
|
|
}
|
|
|
|
|
2019-06-21 17:08:26 +03:00
|
|
|
// RemoteIP gets the IP address of the client making the request.
|
2021-05-01 05:17:23 +03:00
|
|
|
func (c TemplateContext) RemoteIP() string {
|
2019-06-18 20:13:12 +03:00
|
|
|
ip, _, err := net.SplitHostPort(c.Req.RemoteAddr)
|
|
|
|
if err != nil {
|
|
|
|
return c.Req.RemoteAddr
|
|
|
|
}
|
|
|
|
return ip
|
|
|
|
}
|
|
|
|
|
|
|
|
// Host returns the hostname portion of the Host header
|
|
|
|
// from the HTTP request.
|
2021-05-01 05:17:23 +03:00
|
|
|
func (c TemplateContext) Host() (string, error) {
|
2019-06-18 20:13:12 +03: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-23 22:56:41 +03:00
|
|
|
// funcStripHTML returns s without HTML tags. It is fairly naive
|
2019-06-18 20:13:12 +03:00
|
|
|
// but works with most valid HTML inputs.
|
2021-05-01 05:17:23 +03:00
|
|
|
func (TemplateContext) funcStripHTML(s string) string {
|
2019-06-18 20:13:12 +03: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-23 22:56:41 +03:00
|
|
|
// funcMarkdown renders the markdown body as HTML. The resulting
|
2019-06-27 22:30:41 +03:00
|
|
|
// HTML is NOT escaped so that it can be rendered as HTML.
|
2022-08-02 23:39:09 +03:00
|
|
|
func (TemplateContext) funcMarkdown(input any) (string, error) {
|
2022-09-02 06:15:20 +03:00
|
|
|
inputStr := caddy.ToString(input)
|
2019-12-23 22:56:41 +03:00
|
|
|
|
|
|
|
md := goldmark.New(
|
|
|
|
goldmark.WithExtensions(
|
|
|
|
extension.GFM,
|
2020-03-19 08:38:37 +03:00
|
|
|
extension.Footnote,
|
2019-12-23 22:56:41 +03:00
|
|
|
highlighting.NewHighlighting(
|
|
|
|
highlighting.WithFormatOptions(
|
|
|
|
html.WithClasses(true),
|
|
|
|
),
|
|
|
|
),
|
|
|
|
),
|
|
|
|
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 00:50:29 +03:00
|
|
|
err := md.Convert([]byte(inputStr), buf)
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
2019-12-23 22:56:41 +03:00
|
|
|
|
2020-04-06 21:50:54 +03:00
|
|
|
return buf.String(), nil
|
2019-12-23 22:56:41 +03: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-02 23:39:09 +03:00
|
|
|
func (TemplateContext) funcSplitFrontMatter(input any) (parsedMarkdownDoc, error) {
|
2022-09-02 06:15:20 +03:00
|
|
|
meta, body, err := extractFrontMatter(caddy.ToString(input))
|
2019-12-23 22:56:41 +03:00
|
|
|
if err != nil {
|
|
|
|
return parsedMarkdownDoc{}, err
|
|
|
|
}
|
|
|
|
return parsedMarkdownDoc{Meta: meta, Body: body}, nil
|
2019-06-18 20:13:12 +03:00
|
|
|
}
|
|
|
|
|
2019-12-23 22:56:41 +03:00
|
|
|
// funcListFiles reads and returns a slice of names from the given
|
2019-06-18 20:13:12 +03:00
|
|
|
// directory relative to the root of c.
|
2021-05-01 05:17:23 +03:00
|
|
|
func (c TemplateContext) funcListFiles(name string) ([]string, error) {
|
2019-06-18 20:13:12 +03: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-11 23:49:20 +03:00
|
|
|
// funcFileExists returns true if filename can be opened successfully.
|
2021-05-01 05:17:23 +03:00
|
|
|
func (c TemplateContext) funcFileExists(filename string) (bool, error) {
|
2021-01-11 23:49:20 +03: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 18:54:42 +03:00
|
|
|
// funcFileStat returns Stat of a filename
|
2023-04-24 19:36:37 +03: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 18:55:57 +03:00
|
|
|
// funcHTTPError returns a structured HTTP handler error. EXPERIMENTAL; SUBJECT TO CHANGE.
|
|
|
|
// Example usage: `{{if not (fileExists $includeFile)}}{{httpError 404}}{{end}}`
|
2021-05-01 05:17:23 +03:00
|
|
|
func (c TemplateContext) funcHTTPError(statusCode int) (bool, error) {
|
2021-01-11 23:49:20 +03:00
|
|
|
return false, caddyhttp.Error(statusCode, nil)
|
|
|
|
}
|
|
|
|
|
2022-05-25 02:47:08 +03: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")
|
|
|
|
}
|
|
|
|
|
2021-05-01 05:17:23 +03:00
|
|
|
// WrappedHeader wraps niladic functions so that they
|
2019-06-18 20:13:12 +03:00
|
|
|
// can be used in templates. (Template functions must
|
|
|
|
// return a value.)
|
2021-05-01 05:17:23 +03:00
|
|
|
type WrappedHeader struct{ http.Header }
|
2019-06-18 20:13:12 +03:00
|
|
|
|
|
|
|
// Add adds a header field value, appending val to
|
|
|
|
// existing values for that field. It returns an
|
|
|
|
// empty string.
|
2021-05-01 05:17:23 +03:00
|
|
|
func (h WrappedHeader) Add(field, val string) string {
|
2019-06-18 20:13:12 +03: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 05:17:23 +03:00
|
|
|
func (h WrappedHeader) Set(field, val string) string {
|
2019-06-18 20:13:12 +03:00
|
|
|
h.Header.Set(field, val)
|
|
|
|
return ""
|
|
|
|
}
|
|
|
|
|
|
|
|
// Del deletes a header field. It returns an empty string.
|
2021-05-01 05:17:23 +03:00
|
|
|
func (h WrappedHeader) Del(field string) string {
|
2019-06-18 20:13:12 +03:00
|
|
|
h.Header.Del(field)
|
|
|
|
return ""
|
|
|
|
}
|
|
|
|
|
|
|
|
var bufPool = sync.Pool{
|
2022-08-02 23:39:09 +03:00
|
|
|
New: func() any {
|
2019-06-18 20:13:12 +03:00
|
|
|
return new(bytes.Buffer)
|
|
|
|
},
|
|
|
|
}
|
|
|
|
|
2019-12-23 22:56:41 +03:00
|
|
|
// at time of writing, sprig.FuncMap() makes a copy, thus
|
|
|
|
// involves iterating the whole map, so do it just once
|
2020-04-06 21:50:54 +03:00
|
|
|
var sprigFuncMap = sprig.TxtFuncMap()
|
2019-12-23 22:56:41 +03:00
|
|
|
|
2019-06-18 20:13:12 +03:00
|
|
|
const recursionPreventionHeader = "Caddy-Templates-Include"
|