Skip to content

Commit e48b758

Browse files
authored
header: match subdirective for response matching (#6765)
1 parent 1f927d6 commit e48b758

File tree

3 files changed

+46
-0
lines changed

3 files changed

+46
-0
lines changed

caddytest/integration/caddyfile_adapt/header.caddyfiletest

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,10 +12,14 @@
1212
@images path /images/*
1313
header @images {
1414
Cache-Control "public, max-age=3600, stale-while-revalidate=86400"
15+
match {
16+
status 200
17+
}
1518
}
1619
header {
1720
+Link "Foo"
1821
+Link "Bar"
22+
match status 200
1923
}
2024
header >Set Defer
2125
header >Replace Deferred Replacement
@@ -42,6 +46,11 @@
4246
{
4347
"handler": "headers",
4448
"response": {
49+
"require": {
50+
"status_code": [
51+
200
52+
]
53+
},
4554
"set": {
4655
"Cache-Control": [
4756
"public, max-age=3600, stale-while-revalidate=86400"
@@ -136,6 +145,11 @@
136145
"Foo",
137146
"Bar"
138147
]
148+
},
149+
"require": {
150+
"status_code": [
151+
200
152+
]
139153
}
140154
}
141155
},

modules/caddyhttp/headers/caddyfile.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,16 @@ func parseCaddyfile(h httpcaddyfile.Helper) ([]httpcaddyfile.ConfigValue, error)
9999
handler.Response.Deferred = true
100100
continue
101101
}
102+
if field == "match" {
103+
responseMatchers := make(map[string]caddyhttp.ResponseMatcher)
104+
err := caddyhttp.ParseNamedResponseMatcher(h.NewFromNextSegment(), responseMatchers)
105+
if err != nil {
106+
return nil, err
107+
}
108+
matcher := responseMatchers["match"]
109+
handler.Response.Require = &matcher
110+
continue
111+
}
102112
if hasArgs {
103113
return nil, h.Err("cannot specify headers in both arguments and block") // because it would be weird
104114
}

modules/caddyhttp/headers/headers_test.go

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,28 @@ func TestHandler(t *testing.T) {
143143
"Cache-Control": []string{"no-cache"},
144144
},
145145
},
146+
{ // same as above, but checks that response headers are left alone when "Require" conditions are unmet
147+
handler: Handler{
148+
Response: &RespHeaderOps{
149+
Require: &caddyhttp.ResponseMatcher{
150+
Headers: http.Header{
151+
"Cache-Control": nil,
152+
},
153+
},
154+
HeaderOps: &HeaderOps{
155+
Add: http.Header{
156+
"Cache-Control": []string{"no-cache"},
157+
},
158+
},
159+
},
160+
},
161+
respHeader: http.Header{
162+
"Cache-Control": []string{"something"},
163+
},
164+
expectedRespHeader: http.Header{
165+
"Cache-Control": []string{"something"},
166+
},
167+
},
146168
{
147169
handler: Handler{
148170
Response: &RespHeaderOps{

0 commit comments

Comments
 (0)