Fast and extensible multi-platform HTTP/1-2-3 web server with automatic HTTPS
Mirrored from https://github.com/Slazee/caddy.git
Synced Nov 12, 04:30 UTC
header: `match` subdirective for response matching (#6765)
Arsh committed
Jan 8, 2025 at 11:18 UTC
e48b75843b7eff2948b573391fb41535b5e333ef
3 files changed
+46
caddytest/integration/caddyfile_adapt/header.caddyfiletest
+14
@@ -12,10 +12,14 @@
12
@images path /images/*
13
header @images {
14
Cache-Control "public, max-age=3600, stale-while-revalidate=86400"
15
+ match {
16
+ status 200
17
+ }
18
}
19
header {
20
+Link "Foo"
21
+Link "Bar"
22
+ match status 200
23
}
24
header >Set Defer
25
header >Replace Deferred Replacement
@@ -42,6 +46,11 @@
46
{
47
"handler": "headers",
48
"response": {
49
+ "require": {
50
+ "status_code": [
51
+ 200
52
+ ]
53
+ },
54
"set": {
55
"Cache-Control": [
56
"public, max-age=3600, stale-while-revalidate=86400"
@@ -136,6 +145,11 @@
145
"Foo",
146
"Bar"
147
]
148
+ },
149
+ "require": {
150
+ "status_code": [
151
+ 200
152
+ ]
153
}
154
}
155
},
modules/caddyhttp/headers/caddyfile.go
+10
@@ -99,6 +99,16 @@ func parseCaddyfile(h httpcaddyfile.Helper) ([]httpcaddyfile.ConfigValue, error)
99
handler.Response.Deferred = true
100
continue
101
}
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
+ }
112
if hasArgs {
113
return nil, h.Err("cannot specify headers in both arguments and block") // because it would be weird
114
}
modules/caddyhttp/headers/headers_test.go
+22
@@ -143,6 +143,28 @@ func TestHandler(t *testing.T) {
143
"Cache-Control": []string{"no-cache"},
144
},
145
},
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
+ },
168
{
169
handler: Handler{
170
Response: &RespHeaderOps{