Fast and extensible multi-platform HTTP/1-2-3 web server with automatic HTTPS
Mirrored from https://github.com/Slazee/caddy.git
Synced Nov 11, 01:00 UTC
httpcaddyfile: add Helper.IsNamedRoute (#8354)
Kévin Dunglas committed
Nov 4, 2026 at 20:30 UTC
cf1b1121e78da2b27af702e3585f9059af82ecba
2 files changed
+38
caddyconfig/httpcaddyfile/directives.go
+8
@@ -228,6 +228,14 @@ func (h Helper) Option(name string) any {
228
return h.options[name]
229
}
230
231
+// IsNamedRoute returns true if the directive is in a named route.
232
+// Named routes are adapted before the site blocks, with their own
233
+// State, so values a directive keeps in State aren't shared with
234
+// the site blocks.
235
+func (h Helper) IsNamedRoute() bool {
236
+ return h.parentBlock.IsNamedRoute
237
+}
238
+
239
// Caddyfiles returns the list of config files from
240
// which tokens in the current server block were loaded.
241
func (h Helper) Caddyfiles() []string {
caddyconfig/httpcaddyfile/directives_test.go
+30
@@ -111,6 +111,36 @@ func init() {
111
return caddyhttp.StaticError{StatusCode: "500"}, nil
112
})
113
RegisterDirectiveOrder("test_ordered_plugin", Before, "respond")
114
+
115
+ RegisterHandlerDirective("test_named_route", func(h Helper) (caddyhttp.MiddlewareHandler, error) {
116
+ h.Next()
117
+ body := "site"
118
+ if h.IsNamedRoute() {
119
+ body = "named"
120
+ }
121
+ return caddyhttp.StaticResponse{Body: body}, nil
122
+ })
123
+ RegisterDirectiveOrder("test_named_route", Before, "respond")
124
+}
125
+
126
+func TestHelperIsNamedRoute(t *testing.T) {
127
+ adapted := adaptCaddyfile(t, `&(shared) {
128
+ handle /nested {
129
+ test_named_route
130
+ }
131
+}
132
+
133
+:8080 {
134
+ test_named_route
135
+ invoke shared
136
+}
137
+`)
138
+
139
+ for _, body := range []string{`"body":"named"`, `"body":"site"`} {
140
+ if !strings.Contains(adapted, body) {
141
+ t.Errorf("expected %s in the adapted config: %s", body, adapted)
142
+ }
143
+ }
144
}
145
146
// caddyfiles shared by the directive order tests below. the handle block in