@marcel91200 / caddy Mirror · read-only / commits / 637fd8f6
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 14, 05:15 UTC

fileserver: Share template logic for both `templates` and `file_server browse` (#4093)

Co-authored-by: Matthew Holt <mholt@users.noreply.github.com>

Jason Du committed Apr 30, 2021 at 19:17 UTC 637fd8f67b7ff6191673ff13e94825a4ec896891
8 files changed +175 -111
modules/caddyhttp/fileserver/browse.go
+63 -10
@@ -17,14 +17,16 @@ package fileserver
17 import (
18 "bytes"
19 "encoding/json"
20 - "html/template"
20 + "fmt"
21 "net/http"
22 "os"
23 "path"
24 "strings"
25 + "text/template"
26
27 "github.com/caddyserver/caddy/v2"
28 "github.com/caddyserver/caddy/v2/modules/caddyhttp"
29 + "github.com/caddyserver/caddy/v2/modules/caddyhttp/templates"
30 "go.uber.org/zap"
31 )
32
@@ -82,7 +84,26 @@ func (fsrv *FileServer) serveBrowse(root, dirPath string, w http.ResponseWriter,
84 }
85 w.Header().Set("Content-Type", "application/json; charset=utf-8")
86 } else {
85 - if buf, err = fsrv.browseWriteHTML(listing); err != nil {
87 + var fs http.FileSystem
88 + if fsrv.Root != "" {
89 + fs = http.Dir(repl.ReplaceAll(fsrv.Root, "."))
90 + }
91 +
92 + var tplCtx = &templateContext{
93 + TemplateContext: templates.TemplateContext{
94 + Root: fs,
95 + Req: r,
96 + RespHeader: templates.WrappedHeader{Header: w.Header()},
97 + },
98 + browseTemplateContext: listing,
99 + }
100 +
101 + err = fsrv.makeBrowseTemplate(tplCtx)
102 + if err != nil {
103 + return fmt.Errorf("parsing browse template: %v", err)
104 + }
105 +
106 + if buf, err = fsrv.browseWriteHTML(tplCtx); err != nil {
107 return caddyhttp.Error(http.StatusInternalServerError, err)
108 }
109 w.Header().Set("Content-Type", "text/html; charset=utf-8")
@@ -93,10 +114,10 @@ func (fsrv *FileServer) serveBrowse(root, dirPath string, w http.ResponseWriter,
114 return nil
115 }
116
96 -func (fsrv *FileServer) loadDirectoryContents(dir *os.File, root, urlPath string, repl *caddy.Replacer) (browseListing, error) {
117 +func (fsrv *FileServer) loadDirectoryContents(dir *os.File, root, urlPath string, repl *caddy.Replacer) (browseTemplateContext, error) {
118 files, err := dir.Readdir(-1)
119 if err != nil {
99 - return browseListing{}, err
120 + return browseTemplateContext{}, err
121 }
122
123 // user can presumably browse "up" to parent folder if path is longer than "/"
@@ -107,7 +128,7 @@ func (fsrv *FileServer) loadDirectoryContents(dir *os.File, root, urlPath string
128
129 // browseApplyQueryParams applies query parameters to the listing.
130 // It mutates the listing and may set cookies.
110 -func (fsrv *FileServer) browseApplyQueryParams(w http.ResponseWriter, r *http.Request, listing *browseListing) {
131 +func (fsrv *FileServer) browseApplyQueryParams(w http.ResponseWriter, r *http.Request, listing *browseTemplateContext) {
132 sortParam := r.URL.Query().Get("sort")
133 orderParam := r.URL.Query().Get("order")
134 limitParam := r.URL.Query().Get("limit")
@@ -139,17 +160,41 @@ func (fsrv *FileServer) browseApplyQueryParams(w http.ResponseWriter, r *http.Re
160 listing.applySortAndLimit(sortParam, orderParam, limitParam, offsetParam)
161 }
162
142 -func (fsrv *FileServer) browseWriteJSON(listing browseListing) (*bytes.Buffer, error) {
163 +// makeBrowseTemplate creates the template to be used for directory listings.
164 +func (fsrv *FileServer) makeBrowseTemplate(tplCtx *templateContext) error {
165 + var tpl *template.Template
166 + var err error
167 +
168 + if fsrv.Browse.TemplateFile != "" {
169 + tpl = tplCtx.NewTemplate(path.Base(fsrv.Browse.TemplateFile))
170 + tpl, err = tpl.ParseFiles(fsrv.Browse.TemplateFile)
171 + if err != nil {
172 + return fmt.Errorf("parsing browse template file: %v", err)
173 + }
174 + } else {
175 + tpl = tplCtx.NewTemplate("default_listing")
176 + tpl, err = tpl.Parse(defaultBrowseTemplate)
177 + if err != nil {
178 + return fmt.Errorf("parsing default browse template: %v", err)
179 + }
180 + }
181 +
182 + fsrv.Browse.template = tpl
183 +
184 + return nil
185 +}
186 +
187 +func (fsrv *FileServer) browseWriteJSON(listing browseTemplateContext) (*bytes.Buffer, error) {
188 buf := bufPool.Get().(*bytes.Buffer)
189 + defer bufPool.Put(buf)
190 err := json.NewEncoder(buf).Encode(listing.Items)
145 - bufPool.Put(buf)
191 return buf, err
192 }
193
149 -func (fsrv *FileServer) browseWriteHTML(listing browseListing) (*bytes.Buffer, error) {
194 +func (fsrv *FileServer) browseWriteHTML(tplCtx *templateContext) (*bytes.Buffer, error) {
195 buf := bufPool.Get().(*bytes.Buffer)
151 - err := fsrv.Browse.template.Execute(buf, listing)
152 - bufPool.Put(buf)
196 + defer bufPool.Put(buf)
197 + err := fsrv.Browse.template.Execute(buf, tplCtx)
198 return buf, err
199 }
200
@@ -171,3 +216,11 @@ func isSymlinkTargetDir(f os.FileInfo, root, urlPath string) bool {
216 }
217 return targetInfo.IsDir()
218 }
219 +
220 +// templateContext powers the context used when evaluating the browse template.
221 +// It combines browse-specific features with the standard templates handler
222 +// features.
223 +type templateContext struct {
224 + templates.TemplateContext
225 + browseTemplateContext
226 +}
modules/caddyhttp/fileserver/browse_test.go
+22 -8
@@ -1,16 +1,27 @@
1 +// Copyright 2015 Matthew Holt and The Caddy Authors
2 +//
3 +// Licensed under the Apache License, Version 2.0 (the "License");
4 +// you may not use this file except in compliance with the License.
5 +// You may obtain a copy of the License at
6 +//
7 +// http://www.apache.org/licenses/LICENSE-2.0
8 +//
9 +// Unless required by applicable law or agreed to in writing, software
10 +// distributed under the License is distributed on an "AS IS" BASIS,
11 +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 +// See the License for the specific language governing permissions and
13 +// limitations under the License.
14 +
15 package fileserver
16
17 import (
4 - "html/template"
18 "testing"
6 -
7 - "github.com/caddyserver/caddy/v2"
19 + "text/template"
20 )
21
22 func BenchmarkBrowseWriteJSON(b *testing.B) {
23 fsrv := new(FileServer)
12 - fsrv.Provision(caddy.Context{})
13 - listing := browseListing{
24 + listing := browseTemplateContext{
25 Name: "test",
26 Path: "test",
27 CanGoUp: false,
@@ -30,12 +41,11 @@ func BenchmarkBrowseWriteJSON(b *testing.B) {
41
42 func BenchmarkBrowseWriteHTML(b *testing.B) {
43 fsrv := new(FileServer)
33 - fsrv.Provision(caddy.Context{})
44 fsrv.Browse = &Browse{
45 TemplateFile: "",
46 template: template.New("test"),
47 }
38 - listing := browseListing{
48 + listing := browseTemplateContext{
49 Name: "test",
50 Path: "test",
51 CanGoUp: false,
@@ -46,9 +56,13 @@ func BenchmarkBrowseWriteHTML(b *testing.B) {
56 Order: "",
57 Limit: 42,
58 }
59 + tplCtx := &templateContext{
60 + browseTemplateContext: listing,
61 + }
62 + fsrv.makeBrowseTemplate(tplCtx)
63 b.ResetTimer()
64
65 for n := 0; n < b.N; n++ {
52 - fsrv.browseWriteHTML(listing)
66 + fsrv.browseWriteHTML(tplCtx)
67 }
68 }
modules/caddyhttp/fileserver/browsetplcontext.go renamed
+12 -9
@@ -27,7 +27,7 @@ import (
27 "github.com/dustin/go-humanize"
28 )
29
30 -func (fsrv *FileServer) directoryListing(files []os.FileInfo, canGoUp bool, root, urlPath string, repl *caddy.Replacer) browseListing {
30 +func (fsrv *FileServer) directoryListing(files []os.FileInfo, canGoUp bool, root, urlPath string, repl *caddy.Replacer) browseTemplateContext {
31 filesToHide := fsrv.transformHidePaths(repl)
32
33 var dirCount, fileCount int
@@ -62,7 +62,7 @@ func (fsrv *FileServer) directoryListing(files []os.FileInfo, canGoUp bool, root
62 })
63 }
64
65 - return browseListing{
65 + return browseTemplateContext{
66 Name: path.Base(urlPath),
67 Path: urlPath,
68 CanGoUp: canGoUp,
@@ -72,7 +72,8 @@ func (fsrv *FileServer) directoryListing(files []os.FileInfo, canGoUp bool, root
72 }
73 }
74
75 -type browseListing struct {
75 +// browseTemplateContext provides the template context for directory listings.
76 +type browseTemplateContext struct {
77 // The name of the directory (the last element of the path).
78 Name string `json:"name"`
79
@@ -106,7 +107,7 @@ type browseListing struct {
107
108 // Breadcrumbs returns l.Path where every element maps
109 // the link to the text to display.
109 -func (l browseListing) Breadcrumbs() []crumb {
110 +func (l browseTemplateContext) Breadcrumbs() []crumb {
111 if len(l.Path) == 0 {
112 return []crumb{}
113 }
@@ -130,7 +131,7 @@ func (l browseListing) Breadcrumbs() []crumb {
131 return result
132 }
133
133 -func (l *browseListing) applySortAndLimit(sortParam, orderParam, limitParam string, offsetParam string) {
134 +func (l *browseTemplateContext) applySortAndLimit(sortParam, orderParam, limitParam string, offsetParam string) {
135 l.Sort = sortParam
136 l.Order = orderParam
137
@@ -207,10 +208,12 @@ func (fi fileInfo) HumanModTime(format string) string {
208 return fi.ModTime.Format(format)
209 }
210
210 -type byName browseListing
211 -type byNameDirFirst browseListing
212 -type bySize browseListing
213 -type byTime browseListing
211 +type (
212 + byName browseTemplateContext
213 + byNameDirFirst browseTemplateContext
214 + bySize browseTemplateContext
215 + byTime browseTemplateContext
216 +)
217
218 func (l byName) Len() int { return len(l.Items) }
219 func (l byName) Swap(i, j int) { l.Items[i], l.Items[j] = l.Items[j], l.Items[i] }
modules/caddyhttp/fileserver/browsetplcontext_test.go renamed
+15 -1
@@ -1,3 +1,17 @@
1 +// Copyright 2015 Matthew Holt and The Caddy Authors
2 +//
3 +// Licensed under the Apache License, Version 2.0 (the "License");
4 +// you may not use this file except in compliance with the License.
5 +// You may obtain a copy of the License at
6 +//
7 +// http://www.apache.org/licenses/LICENSE-2.0
8 +//
9 +// Unless required by applicable law or agreed to in writing, software
10 +// distributed under the License is distributed on an "AS IS" BASIS,
11 +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 +// See the License for the specific language governing permissions and
13 +// limitations under the License.
14 +
15 package fileserver
16
17 import (
@@ -25,7 +39,7 @@ func TestBreadcrumbs(t *testing.T) {
39 }
40
41 for _, d := range testdata {
28 - l := browseListing{Path: d.path}
42 + l := browseTemplateContext{Path: d.path}
43 actual := l.Breadcrumbs()
44 if len(actual) != len(d.expected) {
45 t.Errorf("wrong size output, got %d elements but expected %d", len(actual), len(d.expected))
modules/caddyhttp/fileserver/staticfiles.go
-18
@@ -17,7 +17,6 @@ package fileserver
17 import (
18 "bytes"
19 "fmt"
20 - "html/template"
20 weakrand "math/rand"
21 "mime"
22 "net/http"
@@ -118,23 +117,6 @@ func (fsrv *FileServer) Provision(ctx caddy.Context) error {
117 fsrv.IndexNames = defaultIndexNames
118 }
119
121 - if fsrv.Browse != nil {
122 - var tpl *template.Template
123 - var err error
124 - if fsrv.Browse.TemplateFile != "" {
125 - tpl, err = template.ParseFiles(fsrv.Browse.TemplateFile)
126 - if err != nil {
127 - return fmt.Errorf("parsing browse template file: %v", err)
128 - }
129 - } else {
130 - tpl, err = template.New("default_listing").Parse(defaultBrowseTemplate)
131 - if err != nil {
132 - return fmt.Errorf("parsing default browse template: %v", err)
133 - }
134 - }
135 - fsrv.Browse.template = tpl
136 - }
137 -
120 // for hide paths that are static (i.e. no placeholders), we can transform them into
121 // absolute paths before the server starts for very slight performance improvement
122 for i, h := range fsrv.Hide {
modules/caddyhttp/templates/templates.go
+3 -3
@@ -37,7 +37,7 @@ func init() {
37 //
38 // [All Sprig functions](https://masterminds.github.io/sprig/) are supported.
39 //
40 -// In addition to the standard functions and Sprig functions, Caddy adds
40 +// In addition to the standard functions and the Sprig library, Caddy adds
41 // extra functions and data that are available to a template:
42 //
43 // ##### `.Args`
@@ -303,10 +303,10 @@ func (t *Templates) executeTemplate(rr caddyhttp.ResponseRecorder, r *http.Reque
303 fs = http.Dir(repl.ReplaceAll(t.FileRoot, "."))
304 }
305
306 - ctx := &templateContext{
306 + ctx := &TemplateContext{
307 Root: fs,
308 Req: r,
309 - RespHeader: tplWrappedHeader{rr.Header()},
309 + RespHeader: WrappedHeader{rr.Header()},
310 config: t,
311 }
312
modules/caddyhttp/templates/tplcontext.go
+55 -43
@@ -38,19 +38,49 @@ import (
38 gmhtml "github.com/yuin/goldmark/renderer/html"
39 )
40
41 -// templateContext is the templateContext with which HTTP templates are executed.
42 -type templateContext struct {
41 +// TemplateContext is the TemplateContext with which HTTP templates are executed.
42 +type TemplateContext struct {
43 Root http.FileSystem
44 Req *http.Request
45 Args []interface{} // defined by arguments to funcInclude
46 - RespHeader tplWrappedHeader
46 + RespHeader WrappedHeader
47
48 config *Templates
49 }
50
51 +// NewTemplate returns a new template intended to be evaluated with this
52 +// context, as it is initialized with configuration from this context.
53 +func (c TemplateContext) NewTemplate(tplName string) *template.Template {
54 + tpl := template.New(tplName)
55 +
56 + // customize delimiters, if applicable
57 + if c.config != nil && len(c.config.Delimiters) == 2 {
58 + tpl.Delims(c.config.Delimiters[0], c.config.Delimiters[1])
59 + }
60 +
61 + // add sprig library
62 + tpl.Funcs(sprigFuncMap)
63 +
64 + // add our own library
65 + tpl.Funcs(template.FuncMap{
66 + "include": c.funcInclude,
67 + "httpInclude": c.funcHTTPInclude,
68 + "stripHTML": c.funcStripHTML,
69 + "markdown": c.funcMarkdown,
70 + "splitFrontMatter": c.funcSplitFrontMatter,
71 + "listFiles": c.funcListFiles,
72 + "env": c.funcEnv,
73 + "placeholder": c.funcPlaceholder,
74 + "fileExists": c.funcFileExists,
75 + "httpError": c.funcHTTPError,
76 + })
77 +
78 + return tpl
79 +}
80 +
81 // OriginalReq returns the original, unmodified, un-rewritten request as
82 // it originally came in over the wire.
53 -func (c templateContext) OriginalReq() http.Request {
83 +func (c TemplateContext) OriginalReq() http.Request {
84 or, _ := c.Req.Context().Value(caddyhttp.OriginalRequestCtxKey).(http.Request)
85 return or
86 }
@@ -59,7 +89,7 @@ func (c templateContext) OriginalReq() http.Request {
89 // Note that included files are NOT escaped, so you should only include
90 // trusted files. If it is not trusted, be sure to use escaping functions
91 // in your template.
62 -func (c templateContext) funcInclude(filename string, args ...interface{}) (string, error) {
92 +func (c TemplateContext) funcInclude(filename string, args ...interface{}) (string, error) {
93 if c.Root == nil {
94 return "", fmt.Errorf("root file system not specified")
95 }
@@ -93,7 +123,7 @@ func (c templateContext) funcInclude(filename string, args ...interface{}) (stri
123 // to the given URI on the same server. Note that included bodies
124 // are NOT escaped, so you should only include trusted resources.
125 // If it is not trusted, be sure to use escaping functions yourself.
96 -func (c templateContext) funcHTTPInclude(uri string) (string, error) {
126 +func (c TemplateContext) funcHTTPInclude(uri string) (string, error) {
127 // prevent virtual request loops by counting how many levels
128 // deep we are; and if we get too deep, return an error
129 recursionCount := 1
@@ -137,26 +167,8 @@ func (c templateContext) funcHTTPInclude(uri string) (string, error) {
167 return buf.String(), nil
168 }
169
140 -func (c templateContext) executeTemplateInBuffer(tplName string, buf *bytes.Buffer) error {
141 - tpl := template.New(tplName)
142 - if len(c.config.Delimiters) == 2 {
143 - tpl.Delims(c.config.Delimiters[0], c.config.Delimiters[1])
144 - }
145 -
146 - tpl.Funcs(sprigFuncMap)
147 -
148 - tpl.Funcs(template.FuncMap{
149 - "include": c.funcInclude,
150 - "httpInclude": c.funcHTTPInclude,
151 - "stripHTML": c.funcStripHTML,
152 - "markdown": c.funcMarkdown,
153 - "splitFrontMatter": c.funcSplitFrontMatter,
154 - "listFiles": c.funcListFiles,
155 - "env": c.funcEnv,
156 - "placeholder": c.funcPlaceholder,
157 - "fileExists": c.funcFileExists,
158 - "httpError": c.funcHTTPError,
159 - })
170 +func (c TemplateContext) executeTemplateInBuffer(tplName string, buf *bytes.Buffer) error {
171 + tpl := c.NewTemplate(tplName)
172
173 parsedTpl, err := tpl.Parse(buf.String())
174 if err != nil {
@@ -168,18 +180,18 @@ func (c templateContext) executeTemplateInBuffer(tplName string, buf *bytes.Buff
180 return parsedTpl.Execute(buf, c)
181 }
182
171 -func (c templateContext) funcPlaceholder(name string) string {
183 +func (c TemplateContext) funcPlaceholder(name string) string {
184 repl := c.Req.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer)
185 value, _ := repl.GetString(name)
186 return value
187 }
188
177 -func (templateContext) funcEnv(varName string) string {
189 +func (TemplateContext) funcEnv(varName string) string {
190 return os.Getenv(varName)
191 }
192
193 // Cookie gets the value of a cookie with name name.
182 -func (c templateContext) Cookie(name string) string {
194 +func (c TemplateContext) Cookie(name string) string {
195 cookies := c.Req.Cookies()
196 for _, cookie := range cookies {
197 if cookie.Name == name {
@@ -190,7 +202,7 @@ func (c templateContext) Cookie(name string) string {
202 }
203
204 // RemoteIP gets the IP address of the client making the request.
193 -func (c templateContext) RemoteIP() string {
205 +func (c TemplateContext) RemoteIP() string {
206 ip, _, err := net.SplitHostPort(c.Req.RemoteAddr)
207 if err != nil {
208 return c.Req.RemoteAddr
@@ -200,7 +212,7 @@ func (c templateContext) RemoteIP() string {
212
213 // Host returns the hostname portion of the Host header
214 // from the HTTP request.
203 -func (c templateContext) Host() (string, error) {
215 +func (c TemplateContext) Host() (string, error) {
216 host, _, err := net.SplitHostPort(c.Req.Host)
217 if err != nil {
218 if !strings.Contains(c.Req.Host, ":") {
@@ -214,7 +226,7 @@ func (c templateContext) Host() (string, error) {
226
227 // funcStripHTML returns s without HTML tags. It is fairly naive
228 // but works with most valid HTML inputs.
217 -func (templateContext) funcStripHTML(s string) string {
229 +func (TemplateContext) funcStripHTML(s string) string {
230 var buf bytes.Buffer
231 var inTag, inQuotes bool
232 var tagStart int
@@ -247,7 +259,7 @@ func (templateContext) funcStripHTML(s string) string {
259
260 // funcMarkdown renders the markdown body as HTML. The resulting
261 // HTML is NOT escaped so that it can be rendered as HTML.
250 -func (templateContext) funcMarkdown(input interface{}) (string, error) {
262 +func (TemplateContext) funcMarkdown(input interface{}) (string, error) {
263 inputStr := toString(input)
264
265 md := goldmark.New(
@@ -283,7 +295,7 @@ func (templateContext) funcMarkdown(input interface{}) (string, error) {
295 // splitFrontMatter parses front matter out from the beginning of input,
296 // and returns the separated key-value pairs and the body/content. input
297 // must be a "stringy" value.
286 -func (templateContext) funcSplitFrontMatter(input interface{}) (parsedMarkdownDoc, error) {
298 +func (TemplateContext) funcSplitFrontMatter(input interface{}) (parsedMarkdownDoc, error) {
299 meta, body, err := extractFrontMatter(toString(input))
300 if err != nil {
301 return parsedMarkdownDoc{}, err
@@ -293,7 +305,7 @@ func (templateContext) funcSplitFrontMatter(input interface{}) (parsedMarkdownDo
305
306 // funcListFiles reads and returns a slice of names from the given
307 // directory relative to the root of c.
296 -func (c templateContext) funcListFiles(name string) ([]string, error) {
308 +func (c TemplateContext) funcListFiles(name string) ([]string, error) {
309 if c.Root == nil {
310 return nil, fmt.Errorf("root file system not specified")
311 }
@@ -326,7 +338,7 @@ func (c templateContext) funcListFiles(name string) ([]string, error) {
338 }
339
340 // funcFileExists returns true if filename can be opened successfully.
329 -func (c templateContext) funcFileExists(filename string) (bool, error) {
341 +func (c TemplateContext) funcFileExists(filename string) (bool, error) {
342 if c.Root == nil {
343 return false, fmt.Errorf("root file system not specified")
344 }
@@ -339,21 +351,21 @@ func (c templateContext) funcFileExists(filename string) (bool, error) {
351 }
352
353 // funcHTTPError returns a structured HTTP handler error. EXPERIMENTAL.
342 -// TODO: Requires https://github.com/golang/go/issues/34201 to be fixed.
354 +// TODO: Requires https://github.com/golang/go/issues/34201 to be fixed (Go 1.17).
355 // Example usage might be: `{{if not (fileExists $includeFile)}}{{httpError 404}}{{end}}`
344 -func (c templateContext) funcHTTPError(statusCode int) (bool, error) {
356 +func (c TemplateContext) funcHTTPError(statusCode int) (bool, error) {
357 return false, caddyhttp.Error(statusCode, nil)
358 }
359
348 -// tplWrappedHeader wraps niladic functions so that they
360 +// WrappedHeader wraps niladic functions so that they
361 // can be used in templates. (Template functions must
362 // return a value.)
351 -type tplWrappedHeader struct{ http.Header }
363 +type WrappedHeader struct{ http.Header }
364
365 // Add adds a header field value, appending val to
366 // existing values for that field. It returns an
367 // empty string.
356 -func (h tplWrappedHeader) Add(field, val string) string {
368 +func (h WrappedHeader) Add(field, val string) string {
369 h.Header.Add(field, val)
370 return ""
371 }
@@ -361,13 +373,13 @@ func (h tplWrappedHeader) Add(field, val string) string {
373 // Set sets a header field value, overwriting any
374 // other values for that field. It returns an
375 // empty string.
364 -func (h tplWrappedHeader) Set(field, val string) string {
376 +func (h WrappedHeader) Set(field, val string) string {
377 h.Header.Set(field, val)
378 return ""
379 }
380
381 // Del deletes a header field. It returns an empty string.
370 -func (h tplWrappedHeader) Del(field string) string {
382 +func (h WrappedHeader) Del(field string) string {
383 h.Header.Del(field)
384 return ""
385 }
modules/caddyhttp/templates/tplcontext_test.go
+5 -19
@@ -12,20 +12,6 @@
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 -// Copyright 2015 Light Code Labs, LLC
16 -//
17 -// Licensed under the Apache License, Version 2.0 (the "License");
18 -// you may not use this file except in compliance with the License.
19 -// You may obtain a copy of the License at
20 -//
21 -// http://www.apache.org/licenses/LICENSE-2.0
22 -//
23 -// Unless required by applicable law or agreed to in writing, software
24 -// distributed under the License is distributed on an "AS IS" BASIS,
25 -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
26 -// See the License for the specific language governing permissions and
27 -// limitations under the License.
28 -
15 package templates
16
17 import (
@@ -357,7 +343,7 @@ title = "Welcome"
343
344 }
345
360 -func getContextOrFail(t *testing.T) templateContext {
346 +func getContextOrFail(t *testing.T) TemplateContext {
347 context, err := initTestContext()
348 if err != nil {
349 t.Fatalf("failed to prepare test context: %v", err)
@@ -365,15 +351,15 @@ func getContextOrFail(t *testing.T) templateContext {
351 return context
352 }
353
368 -func initTestContext() (templateContext, error) {
354 +func initTestContext() (TemplateContext, error) {
355 body := bytes.NewBufferString("request body")
356 request, err := http.NewRequest("GET", "https://example.com/foo/bar", body)
357 if err != nil {
372 - return templateContext{}, err
358 + return TemplateContext{}, err
359 }
374 - return templateContext{
360 + return TemplateContext{
361 Root: http.Dir(os.TempDir()),
362 Req: request,
377 - RespHeader: tplWrappedHeader{make(http.Header)},
363 + RespHeader: WrappedHeader{make(http.Header)},
364 }, nil
365 }