mirror of
https://github.com/cloudflare/cloudflared.git
synced 2025-07-29 10:39:57 +00:00
TUN-528: Move cloudflared into a separate repo
This commit is contained in:
122
vendor/github.com/mholt/caddy/caddyhttp/templates/setup.go
generated
vendored
Normal file
122
vendor/github.com/mholt/caddy/caddyhttp/templates/setup.go
generated
vendored
Normal file
@@ -0,0 +1,122 @@
|
||||
// Copyright 2015 Light Code Labs, LLC
|
||||
//
|
||||
// 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.
|
||||
|
||||
package templates
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"net/http"
|
||||
"sync"
|
||||
|
||||
"github.com/mholt/caddy"
|
||||
"github.com/mholt/caddy/caddyhttp/httpserver"
|
||||
)
|
||||
|
||||
func init() {
|
||||
caddy.RegisterPlugin("templates", caddy.Plugin{
|
||||
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
|
||||
}
|
||||
|
||||
cfg := httpserver.GetConfig(c)
|
||||
|
||||
tmpls := Templates{
|
||||
Rules: rules,
|
||||
Root: cfg.Root,
|
||||
FileSys: http.Dir(cfg.Root),
|
||||
BufPool: &sync.Pool{
|
||||
New: func() interface{} {
|
||||
return new(bytes.Buffer)
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
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"}
|
122
vendor/github.com/mholt/caddy/caddyhttp/templates/setup_test.go
generated
vendored
Normal file
122
vendor/github.com/mholt/caddy/caddyhttp/templates/setup_test.go
generated
vendored
Normal file
@@ -0,0 +1,122 @@
|
||||
// Copyright 2015 Light Code Labs, LLC
|
||||
//
|
||||
// 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.
|
||||
|
||||
package templates
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"github.com/mholt/caddy"
|
||||
"github.com/mholt/caddy/caddyhttp/httpserver"
|
||||
)
|
||||
|
||||
func TestSetup(t *testing.T) {
|
||||
c := caddy.NewTestController("http", `templates`)
|
||||
err := setup(c)
|
||||
if err != nil {
|
||||
t.Errorf("Expected no errors, got: %v", err)
|
||||
}
|
||||
mids := httpserver.GetConfig(c).Middleware()
|
||||
if len(mids) == 0 {
|
||||
t.Fatal("Expected middleware, got 0 instead")
|
||||
}
|
||||
|
||||
handler := mids[0](httpserver.EmptyNext)
|
||||
myHandler, ok := handler.(Templates)
|
||||
|
||||
if !ok {
|
||||
t.Fatalf("Expected handler to be type Templates, got: %#v", handler)
|
||||
}
|
||||
|
||||
if myHandler.Rules[0].Path != defaultTemplatePath {
|
||||
t.Errorf("Expected / as the default Path")
|
||||
}
|
||||
if fmt.Sprint(myHandler.Rules[0].Extensions) != fmt.Sprint(defaultTemplateExtensions) {
|
||||
t.Errorf("Expected %v to be the Default Extensions", defaultTemplateExtensions)
|
||||
}
|
||||
var indexFiles []string
|
||||
for _, extension := range defaultTemplateExtensions {
|
||||
indexFiles = append(indexFiles, "index"+extension)
|
||||
}
|
||||
if fmt.Sprint(myHandler.Rules[0].IndexFiles) != fmt.Sprint(indexFiles) {
|
||||
t.Errorf("Expected %v to be the Default Index files", indexFiles)
|
||||
}
|
||||
if myHandler.Rules[0].Delims != [2]string{} {
|
||||
t.Errorf("Expected %v to be the Default Delims", [2]string{})
|
||||
}
|
||||
}
|
||||
|
||||
func TestTemplatesParse(t *testing.T) {
|
||||
tests := []struct {
|
||||
inputTemplateConfig string
|
||||
shouldErr bool
|
||||
expectedTemplateConfig []Rule
|
||||
}{
|
||||
{`templates /api1`, false, []Rule{{
|
||||
Path: "/api1",
|
||||
Extensions: defaultTemplateExtensions,
|
||||
Delims: [2]string{},
|
||||
}}},
|
||||
{`templates /api2 .txt .htm`, false, []Rule{{
|
||||
Path: "/api2",
|
||||
Extensions: []string{".txt", ".htm"},
|
||||
Delims: [2]string{},
|
||||
}}},
|
||||
|
||||
{`templates /api3 .htm .html
|
||||
templates /api4 .txt .tpl `, false, []Rule{{
|
||||
Path: "/api3",
|
||||
Extensions: []string{".htm", ".html"},
|
||||
Delims: [2]string{},
|
||||
}, {
|
||||
Path: "/api4",
|
||||
Extensions: []string{".txt", ".tpl"},
|
||||
Delims: [2]string{},
|
||||
}}},
|
||||
{`templates {
|
||||
path /api5
|
||||
ext .html
|
||||
between {% %}
|
||||
}`, false, []Rule{{
|
||||
Path: "/api5",
|
||||
Extensions: []string{".html"},
|
||||
Delims: [2]string{"{%", "%}"},
|
||||
}}},
|
||||
}
|
||||
for i, test := range tests {
|
||||
c := caddy.NewTestController("http", test.inputTemplateConfig)
|
||||
actualTemplateConfigs, err := templatesParse(c)
|
||||
|
||||
if err == nil && test.shouldErr {
|
||||
t.Errorf("Test %d didn't error, but it should have", i)
|
||||
} else if err != nil && !test.shouldErr {
|
||||
t.Errorf("Test %d errored, but it shouldn't have; got '%v'", i, err)
|
||||
}
|
||||
if len(actualTemplateConfigs) != len(test.expectedTemplateConfig) {
|
||||
t.Fatalf("Test %d expected %d no of Template configs, but got %d ",
|
||||
i, len(test.expectedTemplateConfig), len(actualTemplateConfigs))
|
||||
}
|
||||
for j, actualTemplateConfig := range actualTemplateConfigs {
|
||||
if actualTemplateConfig.Path != test.expectedTemplateConfig[j].Path {
|
||||
t.Errorf("Test %d expected %dth Template Config Path to be %s , but got %s",
|
||||
i, j, test.expectedTemplateConfig[j].Path, actualTemplateConfig.Path)
|
||||
}
|
||||
if fmt.Sprint(actualTemplateConfig.Extensions) != fmt.Sprint(test.expectedTemplateConfig[j].Extensions) {
|
||||
t.Errorf("Expected %v to be the Extensions , but got %v instead", test.expectedTemplateConfig[j].Extensions, actualTemplateConfig.Extensions)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
143
vendor/github.com/mholt/caddy/caddyhttp/templates/templates.go
generated
vendored
Normal file
143
vendor/github.com/mholt/caddy/caddyhttp/templates/templates.go
generated
vendored
Normal file
@@ -0,0 +1,143 @@
|
||||
// Copyright 2015 Light Code Labs, LLC
|
||||
//
|
||||
// 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.
|
||||
|
||||
// Package templates implements template execution for files to be
|
||||
// dynamically rendered for the client.
|
||||
package templates
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"mime"
|
||||
"net/http"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"text/template"
|
||||
"time"
|
||||
|
||||
"github.com/mholt/caddy/caddyhttp/httpserver"
|
||||
)
|
||||
|
||||
// ServeHTTP implements the httpserver.Handler interface.
|
||||
func (t Templates) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {
|
||||
// iterate rules, to find first one that matches the request path
|
||||
for _, rule := range t.Rules {
|
||||
if !httpserver.Path(r.URL.Path).Matches(rule.Path) {
|
||||
continue
|
||||
}
|
||||
|
||||
fpath := r.URL.Path
|
||||
|
||||
// get a buffer from the pool and make a response recorder
|
||||
buf := t.BufPool.Get().(*bytes.Buffer)
|
||||
buf.Reset()
|
||||
defer t.BufPool.Put(buf)
|
||||
|
||||
// only buffer the response when we want to execute a template
|
||||
shouldBuf := func(status int, header http.Header) bool {
|
||||
// see if this request matches a template extension
|
||||
reqExt := path.Ext(fpath)
|
||||
for _, ext := range rule.Extensions {
|
||||
if reqExt == "" {
|
||||
// request has no extension, so check response Content-Type
|
||||
ct := mime.TypeByExtension(ext)
|
||||
if ct != "" && strings.Contains(header.Get("Content-Type"), ct) {
|
||||
return true
|
||||
}
|
||||
} else if reqExt == ext {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// prepare a buffer to hold the response, if applicable
|
||||
rb := httpserver.NewResponseBuffer(buf, w, shouldBuf)
|
||||
|
||||
// pass request up the chain to let another middleware provide us the template
|
||||
code, err := t.Next.ServeHTTP(rb, r)
|
||||
if !rb.Buffered() || code >= 300 || err != nil {
|
||||
return code, err
|
||||
}
|
||||
|
||||
// create a new template
|
||||
templateName := filepath.Base(fpath)
|
||||
tpl := template.New(templateName)
|
||||
|
||||
// set delimiters
|
||||
if rule.Delims != [2]string{} {
|
||||
tpl.Delims(rule.Delims[0], rule.Delims[1])
|
||||
}
|
||||
|
||||
// add custom functions
|
||||
tpl.Funcs(httpserver.TemplateFuncs)
|
||||
|
||||
// parse the template
|
||||
parsedTpl, err := tpl.Parse(rb.Buffer.String())
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
|
||||
// create execution context for the template template
|
||||
ctx := httpserver.NewContextWithHeader(w.Header())
|
||||
ctx.Root = t.FileSys
|
||||
ctx.Req = r
|
||||
ctx.URL = r.URL
|
||||
|
||||
// execute the template
|
||||
buf.Reset()
|
||||
err = parsedTpl.Execute(buf, ctx)
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
|
||||
// copy the buffered header into the real ResponseWriter
|
||||
rb.CopyHeader()
|
||||
|
||||
// set the actual content length now that the template was executed
|
||||
w.Header().Set("Content-Length", strconv.Itoa(buf.Len()))
|
||||
|
||||
// get the modification time in preparation for http.ServeContent
|
||||
modTime, _ := time.Parse(http.TimeFormat, w.Header().Get("Last-Modified"))
|
||||
|
||||
// at last, write the rendered template to the response; make sure to use
|
||||
// use the proper status code, since ServeContent hard-codes 2xx codes...
|
||||
http.ServeContent(rb.StatusCodeWriter(w), r, templateName, modTime, bytes.NewReader(buf.Bytes()))
|
||||
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
return t.Next.ServeHTTP(w, r)
|
||||
}
|
||||
|
||||
// Templates is middleware to render templated files as the HTTP response.
|
||||
type Templates struct {
|
||||
Next httpserver.Handler
|
||||
Rules []Rule
|
||||
Root string
|
||||
FileSys http.FileSystem
|
||||
BufPool *sync.Pool // docs: "A Pool must not be copied after first use."
|
||||
}
|
||||
|
||||
// Rule represents a template rule. A template will only execute
|
||||
// with this rule if the request path matches the Path specified
|
||||
// and requests a resource with one of the extensions specified.
|
||||
type Rule struct {
|
||||
Path string
|
||||
Extensions []string
|
||||
IndexFiles []string
|
||||
Delims [2]string
|
||||
}
|
140
vendor/github.com/mholt/caddy/caddyhttp/templates/templates_test.go
generated
vendored
Normal file
140
vendor/github.com/mholt/caddy/caddyhttp/templates/templates_test.go
generated
vendored
Normal file
@@ -0,0 +1,140 @@
|
||||
// Copyright 2015 Light Code Labs, LLC
|
||||
//
|
||||
// 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.
|
||||
|
||||
package templates
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/mholt/caddy/caddyhttp/httpserver"
|
||||
"github.com/mholt/caddy/caddyhttp/staticfiles"
|
||||
)
|
||||
|
||||
func TestTemplates(t *testing.T) {
|
||||
siteRoot := "./testdata"
|
||||
tmpl := Templates{
|
||||
Next: staticfiles.FileServer{Root: http.Dir(siteRoot)},
|
||||
Rules: []Rule{
|
||||
{
|
||||
Extensions: []string{".html"},
|
||||
IndexFiles: []string{"index.html"},
|
||||
Path: "/photos",
|
||||
},
|
||||
{
|
||||
Extensions: []string{".html", ".htm"},
|
||||
IndexFiles: []string{"index.html", "index.htm"},
|
||||
Path: "/images",
|
||||
Delims: [2]string{"{%", "%}"},
|
||||
},
|
||||
},
|
||||
Root: siteRoot,
|
||||
FileSys: http.Dir(siteRoot),
|
||||
BufPool: &sync.Pool{New: func() interface{} { return new(bytes.Buffer) }},
|
||||
}
|
||||
|
||||
tmplroot := Templates{
|
||||
Next: staticfiles.FileServer{Root: http.Dir(siteRoot)},
|
||||
Rules: []Rule{
|
||||
{
|
||||
Extensions: []string{".html"},
|
||||
IndexFiles: []string{"index.html"},
|
||||
Path: "/",
|
||||
},
|
||||
},
|
||||
Root: siteRoot,
|
||||
FileSys: http.Dir(siteRoot),
|
||||
BufPool: &sync.Pool{New: func() interface{} { return new(bytes.Buffer) }},
|
||||
}
|
||||
|
||||
// register custom function which is used in template
|
||||
httpserver.TemplateFuncs["root"] = func() string { return "root" }
|
||||
|
||||
for _, c := range []struct {
|
||||
tpl Templates
|
||||
req string
|
||||
respCode int
|
||||
res string
|
||||
}{
|
||||
{
|
||||
tpl: tmpl,
|
||||
req: "/photos/test.html",
|
||||
respCode: http.StatusOK,
|
||||
res: `<!DOCTYPE html><html><head><title>test page</title></head><body><h1>Header title</h1>
|
||||
</body></html>
|
||||
`,
|
||||
},
|
||||
|
||||
{
|
||||
tpl: tmpl,
|
||||
req: "/images/img.htm",
|
||||
respCode: http.StatusOK,
|
||||
res: `<!DOCTYPE html><html><head><title>img</title></head><body><h1>Header title</h1>
|
||||
</body></html>
|
||||
`,
|
||||
},
|
||||
|
||||
{
|
||||
tpl: tmpl,
|
||||
req: "/images/img2.htm",
|
||||
respCode: http.StatusOK,
|
||||
res: `<!DOCTYPE html><html><head><title>img</title></head><body>{{.Include "header.html"}}</body></html>
|
||||
`,
|
||||
},
|
||||
|
||||
{
|
||||
tpl: tmplroot,
|
||||
req: "/root.html",
|
||||
respCode: http.StatusOK,
|
||||
res: `<!DOCTYPE html><html><head><title>root</title></head><body><h1>Header title</h1>
|
||||
</body></html>
|
||||
`,
|
||||
},
|
||||
|
||||
// test extension filter
|
||||
{
|
||||
tpl: tmplroot,
|
||||
req: "/as_it_is.txt",
|
||||
respCode: http.StatusOK,
|
||||
res: `<!DOCTYPE html><html><head><title>as it is</title></head><body>{{.Include "header.html"}}</body></html>
|
||||
`,
|
||||
},
|
||||
} {
|
||||
c := c
|
||||
t.Run("", func(t *testing.T) {
|
||||
req, err := http.NewRequest("GET", c.req, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("Test: Could not create HTTP request: %v", err)
|
||||
}
|
||||
req = req.WithContext(context.WithValue(req.Context(), httpserver.OriginalURLCtxKey, *req.URL))
|
||||
|
||||
rec := httptest.NewRecorder()
|
||||
|
||||
c.tpl.ServeHTTP(rec, req)
|
||||
|
||||
if rec.Code != c.respCode {
|
||||
t.Fatalf("Test: Wrong response code: %d, should be %d", rec.Code, c.respCode)
|
||||
}
|
||||
|
||||
respBody := rec.Body.String()
|
||||
if respBody != c.res {
|
||||
t.Fatalf("Test: the expected body %v is different from the response one: %v", c.res, respBody)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
1
vendor/github.com/mholt/caddy/caddyhttp/templates/testdata/as_it_is.txt
generated
vendored
Normal file
1
vendor/github.com/mholt/caddy/caddyhttp/templates/testdata/as_it_is.txt
generated
vendored
Normal file
@@ -0,0 +1 @@
|
||||
<!DOCTYPE html><html><head><title>as it is</title></head><body>{{.Include "header.html"}}</body></html>
|
1
vendor/github.com/mholt/caddy/caddyhttp/templates/testdata/header.html
generated
vendored
Normal file
1
vendor/github.com/mholt/caddy/caddyhttp/templates/testdata/header.html
generated
vendored
Normal file
@@ -0,0 +1 @@
|
||||
<h1>Header title</h1>
|
1
vendor/github.com/mholt/caddy/caddyhttp/templates/testdata/images/header.html
generated
vendored
Normal file
1
vendor/github.com/mholt/caddy/caddyhttp/templates/testdata/images/header.html
generated
vendored
Normal file
@@ -0,0 +1 @@
|
||||
<h1>Header title</h1>
|
1
vendor/github.com/mholt/caddy/caddyhttp/templates/testdata/images/img.htm
generated
vendored
Normal file
1
vendor/github.com/mholt/caddy/caddyhttp/templates/testdata/images/img.htm
generated
vendored
Normal file
@@ -0,0 +1 @@
|
||||
<!DOCTYPE html><html><head><title>img</title></head><body>{%.Include "header.html"%}</body></html>
|
1
vendor/github.com/mholt/caddy/caddyhttp/templates/testdata/images/img2.htm
generated
vendored
Normal file
1
vendor/github.com/mholt/caddy/caddyhttp/templates/testdata/images/img2.htm
generated
vendored
Normal file
@@ -0,0 +1 @@
|
||||
<!DOCTYPE html><html><head><title>img</title></head><body>{{.Include "header.html"}}</body></html>
|
1
vendor/github.com/mholt/caddy/caddyhttp/templates/testdata/photos/test.html
generated
vendored
Normal file
1
vendor/github.com/mholt/caddy/caddyhttp/templates/testdata/photos/test.html
generated
vendored
Normal file
@@ -0,0 +1 @@
|
||||
<!DOCTYPE html><html><head><title>test page</title></head><body>{{.Include "../header.html"}}</body></html>
|
1
vendor/github.com/mholt/caddy/caddyhttp/templates/testdata/root.html
generated
vendored
Normal file
1
vendor/github.com/mholt/caddy/caddyhttp/templates/testdata/root.html
generated
vendored
Normal file
@@ -0,0 +1 @@
|
||||
<!DOCTYPE html><html><head><title>{{ root }}</title></head><body>{{.Include "header.html"}}</body></html>
|
Reference in New Issue
Block a user