2016-06-05 23:39:23 -05:00
|
|
|
package templates
|
|
|
|
|
|
|
|
import (
|
2017-04-21 20:54:25 -05:00
|
|
|
"bytes"
|
2016-06-05 23:39:23 -05:00
|
|
|
"net/http"
|
2017-04-21 20:54:25 -05:00
|
|
|
"sync"
|
2016-06-05 23:39:23 -05:00
|
|
|
|
|
|
|
"github.com/mholt/caddy"
|
|
|
|
"github.com/mholt/caddy/caddyhttp/httpserver"
|
|
|
|
)
|
|
|
|
|
|
|
|
func init() {
|
2016-06-06 16:31:03 -05:00
|
|
|
caddy.RegisterPlugin("templates", caddy.Plugin{
|
2016-06-05 23:39:23 -05:00
|
|
|
ServerType: "http",
|
|
|
|
Action: setup,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
// setup configures a new Templates middleware instance.
|
|
|
|
func setup(c *caddy.Controller) error {
|
|
|
|
rules, err := templatesParse(c)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2016-06-20 12:44:20 -05:00
|
|
|
cfg := httpserver.GetConfig(c)
|
2016-06-05 23:39:23 -05:00
|
|
|
|
|
|
|
tmpls := Templates{
|
|
|
|
Rules: rules,
|
|
|
|
Root: cfg.Root,
|
|
|
|
FileSys: http.Dir(cfg.Root),
|
2017-04-21 20:54:25 -05:00
|
|
|
BufPool: &sync.Pool{
|
|
|
|
New: func() interface{} {
|
|
|
|
return new(bytes.Buffer)
|
|
|
|
},
|
|
|
|
},
|
2016-06-05 23:39:23 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
cfg.AddMiddleware(func(next httpserver.Handler) httpserver.Handler {
|
|
|
|
tmpls.Next = next
|
|
|
|
return tmpls
|
|
|
|
})
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func templatesParse(c *caddy.Controller) ([]Rule, error) {
|
|
|
|
var rules []Rule
|
|
|
|
|
|
|
|
for c.Next() {
|
|
|
|
var rule Rule
|
|
|
|
|
|
|
|
rule.Path = defaultTemplatePath
|
|
|
|
rule.Extensions = defaultTemplateExtensions
|
|
|
|
|
|
|
|
args := c.RemainingArgs()
|
|
|
|
|
|
|
|
switch len(args) {
|
|
|
|
case 0:
|
|
|
|
// Optional block
|
|
|
|
for c.NextBlock() {
|
|
|
|
switch c.Val() {
|
|
|
|
case "path":
|
|
|
|
args := c.RemainingArgs()
|
|
|
|
if len(args) != 1 {
|
|
|
|
return nil, c.ArgErr()
|
|
|
|
}
|
|
|
|
rule.Path = args[0]
|
|
|
|
|
|
|
|
case "ext":
|
|
|
|
args := c.RemainingArgs()
|
|
|
|
if len(args) == 0 {
|
|
|
|
return nil, c.ArgErr()
|
|
|
|
}
|
|
|
|
rule.Extensions = args
|
|
|
|
|
|
|
|
case "between":
|
|
|
|
args := c.RemainingArgs()
|
|
|
|
if len(args) != 2 {
|
|
|
|
return nil, c.ArgErr()
|
|
|
|
}
|
|
|
|
rule.Delims[0] = args[0]
|
|
|
|
rule.Delims[1] = args[1]
|
|
|
|
}
|
|
|
|
}
|
|
|
|
default:
|
|
|
|
// First argument would be the path
|
|
|
|
rule.Path = args[0]
|
|
|
|
|
|
|
|
// Any remaining arguments are extensions
|
|
|
|
rule.Extensions = args[1:]
|
|
|
|
if len(rule.Extensions) == 0 {
|
|
|
|
rule.Extensions = defaultTemplateExtensions
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, ext := range rule.Extensions {
|
|
|
|
rule.IndexFiles = append(rule.IndexFiles, "index"+ext)
|
|
|
|
}
|
|
|
|
|
|
|
|
rules = append(rules, rule)
|
|
|
|
}
|
|
|
|
return rules, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
const defaultTemplatePath = "/"
|
|
|
|
|
|
|
|
var defaultTemplateExtensions = []string{".html", ".htm", ".tmpl", ".tpl", ".txt"}
|