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
httpcaddyfile: Matchers can now be embedded into a nested scope
This is useful in 'handle' and 'route' directives, for instance, if you want to keep your matcher definitions by the directives that use them.
Matthew Holt committed
Feb 25, 2020 at 21:56 UTC
f6b9cb7122c670ae063a9049455ec99edf0dc8be
1 file changed
+31
-4
caddyconfig/httpcaddyfile/directives.go
+31
-4
@@ -17,6 +17,7 @@ package httpcaddyfile
17
import (
18
"encoding/json"
19
"sort"
20
+ "strings"
21
22
"github.com/caddyserver/caddy/v2"
23
"github.com/caddyserver/caddy/v2/caddyconfig"
@@ -298,17 +299,43 @@ func sortRoutes(routes []ConfigValue) {
299
// and returned.
300
func parseSegmentAsSubroute(h Helper) (caddyhttp.MiddlewareHandler, error) {
301
var allResults []ConfigValue
302
+
303
for h.Next() {
304
+ // slice the linear list of tokens into top-level segments
305
+ var segments []caddyfile.Segment
306
for nesting := h.Nesting(); h.NextBlock(nesting); {
303
- dir := h.Val()
307
+ segments = append(segments, h.NextSegment())
308
+ }
309
310
+ // copy existing matcher definitions so we can augment
311
+ // new ones that are defined only in this scope
312
+ matcherDefs := make(map[string]caddy.ModuleMap, len(h.matcherDefs))
313
+ for key, val := range h.matcherDefs {
314
+ matcherDefs[key] = val
315
+ }
316
+
317
+ // find and extract any embedded matcher definitions in this scope
318
+ for i, seg := range segments {
319
+ if strings.HasPrefix(seg.Directive(), matcherPrefix) {
320
+ err := parseMatcherDefinitions(caddyfile.NewDispenser(seg), matcherDefs)
321
+ if err != nil {
322
+ return nil, err
323
+ }
324
+ segments = append(segments[:i], segments[i+1:]...)
325
+ }
326
+ }
327
+
328
+ // with matchers ready to go, evaluate each directive's segment
329
+ for _, seg := range segments {
330
+ dir := seg.Directive()
331
dirFunc, ok := registeredDirectives[dir]
332
if !ok {
333
return nil, h.Errf("unrecognized directive: %s", dir)
334
}
335
336
subHelper := h
311
- subHelper.Dispenser = h.NewFromNextSegment()
337
+ subHelper.Dispenser = caddyfile.NewDispenser(seg)
338
+ subHelper.matcherDefs = matcherDefs
339
340
results, err := dirFunc(subHelper)
341
if err != nil {
@@ -319,9 +346,9 @@ func parseSegmentAsSubroute(h Helper) (caddyhttp.MiddlewareHandler, error) {
346
allResults = append(allResults, result)
347
}
348
}
322
- return buildSubroute(allResults, h.groupCounter) // TODO: should we move this outside the loop?
349
}
324
- return nil, nil
350
+
351
+ return buildSubroute(allResults, h.groupCounter)
352
}
353
354
// serverBlock pairs a Caddyfile server block