From e51e56a4944622c0a2c7d19da4bb6b9bb07c1973 Mon Sep 17 00:00:00 2001 From: Matthew Holt Date: Thu, 16 Jan 2020 17:08:52 -0700 Subject: httpcaddyfile: Fix nested blocks; add handle directive; refactor The fix that was initially put forth in #2971 was good, but only for up to one layer of nesting. The real problem was that we forgot to increment nesting when already inside a block if we saw another open curly brace that opens another block (dispenser.go L157-158). The new 'handle' directive allows HTTP Caddyfiles to be designed more like nginx location blocks if the user prefers. Inside a handle block, directives are still ordered just like they are outside of them, but handler blocks at a given level of nesting are mutually exclusive. This work benefitted from some refactoring and cleanup. --- caddyconfig/caddyfile/dispenser.go | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) (limited to 'caddyconfig/caddyfile/dispenser.go') diff --git a/caddyconfig/caddyfile/dispenser.go b/caddyconfig/caddyfile/dispenser.go index 5b90b73..4ed9325 100755 --- a/caddyconfig/caddyfile/dispenser.go +++ b/caddyconfig/caddyfile/dispenser.go @@ -152,8 +152,10 @@ func (d *Dispenser) NextBlock(initialNestingLevel int) bool { if !d.Next() { return false // should be EOF error } - if d.Val() == "}" { + if d.Val() == "}" && !d.nextOnSameLine() { d.nesting-- + } else if d.Val() == "{" && !d.nextOnSameLine() { + d.nesting++ } return d.nesting > initialNestingLevel } @@ -262,9 +264,9 @@ func (d *Dispenser) NewFromNextTokens() *Dispenser { if !openedBlock { // because NextBlock() consumes the initial open // curly brace, we rewind here to append it, since - // our case is special in that we want to include - // all the tokens including surrounding curly braces - // for a new dispenser to have + // our case is special in that we want the new + // dispenser to have all the tokens including + // surrounding curly braces d.Prev() tkns = append(tkns, d.Token()) d.Next() @@ -273,12 +275,12 @@ func (d *Dispenser) NewFromNextTokens() *Dispenser { tkns = append(tkns, d.Token()) } if openedBlock { - // include closing brace accordingly + // include closing brace tkns = append(tkns, d.Token()) - // since NewFromNextTokens is intended to consume the entire - // directive, we must call Next() here and consume the closing - // curly brace - d.Next() + + // do not consume the closing curly brace; the + // next iteration of the enclosing loop will + // call Next() and consume it } return NewDispenser(tkns) } -- cgit v1.2.3