Skip to content

Commit

Permalink
header: match subdirective for response matching (#6765)
Browse files Browse the repository at this point in the history
  • Loading branch information
lilnasy authored Jan 8, 2025
1 parent 1f927d6 commit e48b758
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 0 deletions.
14 changes: 14 additions & 0 deletions caddytest/integration/caddyfile_adapt/header.caddyfiletest
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,14 @@
@images path /images/*
header @images {
Cache-Control "public, max-age=3600, stale-while-revalidate=86400"
match {
status 200
}
}
header {
+Link "Foo"
+Link "Bar"
match status 200
}
header >Set Defer
header >Replace Deferred Replacement
Expand All @@ -42,6 +46,11 @@
{
"handler": "headers",
"response": {
"require": {
"status_code": [
200
]
},
"set": {
"Cache-Control": [
"public, max-age=3600, stale-while-revalidate=86400"
Expand Down Expand Up @@ -136,6 +145,11 @@
"Foo",
"Bar"
]
},
"require": {
"status_code": [
200
]
}
}
},
Expand Down
10 changes: 10 additions & 0 deletions modules/caddyhttp/headers/caddyfile.go
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,16 @@ func parseCaddyfile(h httpcaddyfile.Helper) ([]httpcaddyfile.ConfigValue, error)
handler.Response.Deferred = true
continue
}
if field == "match" {
responseMatchers := make(map[string]caddyhttp.ResponseMatcher)
err := caddyhttp.ParseNamedResponseMatcher(h.NewFromNextSegment(), responseMatchers)
if err != nil {
return nil, err
}
matcher := responseMatchers["match"]
handler.Response.Require = &matcher
continue
}
if hasArgs {
return nil, h.Err("cannot specify headers in both arguments and block") // because it would be weird
}
Expand Down
22 changes: 22 additions & 0 deletions modules/caddyhttp/headers/headers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,28 @@ func TestHandler(t *testing.T) {
"Cache-Control": []string{"no-cache"},
},
},
{ // same as above, but checks that response headers are left alone when "Require" conditions are unmet
handler: Handler{
Response: &RespHeaderOps{
Require: &caddyhttp.ResponseMatcher{
Headers: http.Header{
"Cache-Control": nil,
},
},
HeaderOps: &HeaderOps{
Add: http.Header{
"Cache-Control": []string{"no-cache"},
},
},
},
},
respHeader: http.Header{
"Cache-Control": []string{"something"},
},
expectedRespHeader: http.Header{
"Cache-Control": []string{"something"},
},
},
{
handler: Handler{
Response: &RespHeaderOps{
Expand Down

0 comments on commit e48b758

Please # to comment.