ntex 4.9.0

Framework for composable network services
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
//! `Middleware` for compressing response body.
use crate::http::encoding::Encoder;
use crate::http::header::{
    ACCEPT_ENCODING, CONTENT_ENCODING, ContentEncoding, HeaderMap, HeaderValue, VARY,
};
use crate::service::{Ctx, Middleware, Service};
use crate::web::{BodyEncoding, State, WebRequest, WebResponse};

#[derive(Debug, Clone)]
/// `Middleware` for compressing response body.
///
/// Bodies with a known size below 1KiB are sent uncompressed.
/// Use `BodyEncoding` trait for overriding response compression.
/// To disable compression set encoding to `ContentEncoding::Identity` value.
///
/// The encoding is negotiated from the request's `Accept-Encoding` header.
/// `identity` is used instead of compression only if the client gives it a
/// strictly higher weight, explicitly or via `*`. Responses whose encoding is
/// negotiated get `Vary: Accept-Encoding`, so caches keep one copy per
/// encoding. The header is not added if compression is disabled, if the
/// response selects its encoding with `BodyEncoding` or already has a
/// `Content-Encoding` header.
///
/// Each compressed response keeps its encoder until the body ends, up to
/// 1.5MiB for `zstd`, see [`crate::http::encoding`].
///
/// ```rust
/// use ntex::web::{self, middleware, App, HttpResponse};
///
/// fn main() {
///     let app = App::default()
///         .middleware(middleware::Compress::default())
///         .service(
///             web::resource("/test")
///                 .route(web::get().to(async || { HttpResponse::Ok() }))
///                 .route(web::head().to(async || { HttpResponse::MethodNotAllowed() }))
///         );
/// }
/// ```
pub struct Compress {
    enc: ContentEncoding,
}

impl Compress {
    /// Create new `Compress` middleware with the specified encoding.
    ///
    /// Use `Compress::default()` to select the encoding automatically
    /// ([`ContentEncoding::Auto`]).
    pub fn new(encoding: ContentEncoding) -> Self {
        Compress { enc: encoding }
    }
}

impl Default for Compress {
    fn default() -> Self {
        Compress::new(ContentEncoding::Auto)
    }
}

impl<S, St> Middleware<S, St> for Compress {
    type Service = CompressMiddleware<S>;

    fn create(&self, _: &St, service: S) -> Self::Service {
        CompressMiddleware {
            service,
            encoding: self.enc,
        }
    }
}

#[derive(Debug)]
pub struct CompressMiddleware<S> {
    service: S,
    encoding: ContentEncoding,
}

impl<S, St, In> Service<St, WebRequest<In>> for CompressMiddleware<S>
where
    S: Service<St, WebRequest<In>, Res = WebResponse>,
    St: State,
{
    type Res = WebResponse;
    type Error = S::Error;

    crate::forward!(St, service);

    async fn call(
        &self,
        req: WebRequest<In>,
        ctx: Ctx<'_, Self, St>,
    ) -> Result<WebResponse, S::Error> {
        // negotiate content-encoding
        let values = req
            .headers()
            .get_all(&ACCEPT_ENCODING)
            .filter_map(|val| val.to_str().ok());
        let encoding = AcceptEncoding::parse(values, self.encoding);

        let mut resp = ctx.call(&self.service, req).await?;

        let enc = if let Some(enc) = resp.response().get_encoding() {
            enc
        } else {
            if self.encoding != ContentEncoding::Identity
                && !resp.headers().contains_key(CONTENT_ENCODING)
            {
                add_vary(resp.headers_mut());
            }
            encoding
        };

        Ok(resp.map_body(move |head, body| Encoder::response(enc, head, body)))
    }
}

/// Add `accept-encoding` to the `Vary` header unless it is already covered.
fn add_vary(headers: &mut HeaderMap) {
    let covered = headers
        .get_all(VARY)
        .filter_map(|val| val.to_str().ok())
        .flat_map(|val| val.split(','))
        .map(str::trim)
        .any(|name| name == "*" || name.eq_ignore_ascii_case("accept-encoding"));
    if !covered {
        headers.append(VARY, HeaderValue::from_static("accept-encoding"));
    }
}

/// Encodings that can be picked for a `*` entry.
const WILDCARD: [ContentEncoding; 3] = [
    ContentEncoding::Zstd,
    ContentEncoding::Gzip,
    ContentEncoding::Deflate,
];

#[derive(Debug, PartialEq)]
struct AcceptEncoding {
    /// `None` for the `*` entry
    encoding: Option<ContentEncoding>,
    /// Client weight in thousandths, `0..=1000`
    q: u16,
}

impl AcceptEncoding {
    fn new(tag: &str) -> Option<AcceptEncoding> {
        let mut parts = tag.split(';');
        let name = parts.next()?.trim();
        if name.is_empty() {
            return None;
        }
        // unsupported codings cannot be selected, skip them
        let encoding = if name == "*" {
            None
        } else {
            Some(name.parse().ok()?)
        };

        // a malformed weight makes the entry unacceptable
        let q = parts
            .filter_map(|param| param.split_once('='))
            .find(|(name, _)| name.trim().eq_ignore_ascii_case("q"))
            .map_or(1000, |(_, val)| parse_q(val.trim()).unwrap_or(0));
        Some(AcceptEncoding { encoding, q })
    }

    /// Pick a response encoding from the `Accept-Encoding` header values.
    ///
    /// Entries are ranked by the client's `q` value, ties go to the
    /// server's preference. `q=0` means "not acceptable" and `*` covers
    /// every encoding the client did not list. `identity` wins only if its
    /// explicit or `*` weight is strictly higher than the best compression.
    fn parse<'a, I>(values: I, encoding: ContentEncoding) -> ContentEncoding
    where
        I: Iterator<Item = &'a str>,
    {
        let mut listed: Vec<(ContentEncoding, u16)> = Vec::new();
        let mut wildcard = None;
        for item in values.flat_map(|val| val.split(',')) {
            match AcceptEncoding::new(item) {
                Some(AcceptEncoding {
                    encoding: Some(enc),
                    q,
                }) => listed.push((enc, q)),
                Some(AcceptEncoding { encoding: None, q }) => {
                    wildcard.get_or_insert(q);
                }
                None => {}
            }
        }
        let weight = |enc: ContentEncoding| {
            listed
                .iter()
                .find(|(e, _)| *e == enc)
                .map(|(_, q)| *q)
                .or(wildcard)
                .unwrap_or(0)
        };
        let identity = weight(ContentEncoding::Identity);

        if encoding != ContentEncoding::Auto {
            let q = weight(encoding);
            return if q > 0 && q >= identity {
                encoding
            } else {
                ContentEncoding::Identity
            };
        }

        let mut best: Option<(ContentEncoding, u16)> = None;
        let candidates = listed.iter().map(|(enc, _)| *enc).chain(WILDCARD);
        for enc in candidates.filter(|enc| Encoder::can_encode(*enc)) {
            let q = weight(enc);
            let better = match best {
                None => q > 0,
                Some((b, bq)) => q > bq || (q == bq && enc.quality() > b.quality()),
            };
            if better {
                best = Some((enc, q));
            }
        }
        match best {
            Some((enc, q)) if q >= identity => enc,
            _ => ContentEncoding::Identity,
        }
    }
}

/// Parse an RFC 9110 `qvalue` into thousandths.
fn parse_q(val: &str) -> Option<u16> {
    let (int, frac) = match val.split_once('.') {
        Some((int, frac)) => (int, frac),
        None => (val, ""),
    };
    if frac.len() > 3 || !frac.bytes().all(|b| b.is_ascii_digit()) {
        return None;
    }
    let int = match int {
        "0" => 0,
        "1" => 1000,
        _ => return None,
    };
    let frac = frac
        .bytes()
        .zip([100, 10, 1])
        .map(|(b, scale)| u16::from(b - b'0') * scale)
        .sum::<u16>();
    if int + frac > 1000 { None } else { Some(int + frac) }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn parse(raw: &str, encoding: ContentEncoding) -> ContentEncoding {
        AcceptEncoding::parse([raw].into_iter(), encoding)
    }

    /// STATEMENT: Quality parsing accepts HTTP q-values with at most three fractional digits.
    ///
    /// HOW:
    /// - Parse valid zero/one and fractional values and assert their thousandths representation.
    /// - Assert empty, malformed, overprecise, negative, and out-of-range values are rejected.
    #[test]
    fn test_parse_q() {
        for (val, q) in [
            ("0", 0),
            ("0.", 0),
            ("0.5", 500),
            ("0.05", 50),
            ("0.125", 125),
            ("0.999", 999),
            ("1", 1000),
            ("1.", 1000),
            ("1.000", 1000),
        ] {
            assert_eq!(parse_q(val), Some(q), "{val}");
        }
        for val in [
            "", ".5", "0.1234", "1.001", "1.5", "2", "-0", "0.a", "0.00a", "01", "abc",
        ] {
            assert_eq!(parse_q(val), None, "{val}");
        }
    }

    /// STATEMENT: Encoding entries parse tokens, optional quality parameters, and wildcard values.
    ///
    /// HOW:
    /// - Check gzip defaults, whitespace, case-insensitive `q`, extra parameters, and invalid quality.
    /// - Assert wildcard has no specific encoding, `identity` is kept, and empty or
    ///   unsupported coding entries are ignored.
    #[test]
    fn test_accept_encoding_entry() {
        let entry = |tag| AcceptEncoding::new(tag).unwrap();
        assert_eq!(
            entry("gzip"),
            AcceptEncoding {
                encoding: Some(ContentEncoding::Gzip),
                q: 1000
            }
        );
        assert_eq!(entry(" gzip ; q=0.5 ").q, 500);
        assert_eq!(entry("gzip;Q=0.5").q, 500);
        assert_eq!(entry("gzip;level=1;q=0.25").q, 250);
        assert_eq!(entry("gzip;q=abc").q, 0);
        assert_eq!(entry("gzip;0.8").q, 1000);
        assert_eq!(entry("*;q=0.1").encoding, None);
        assert_eq!(
            entry("identity;q=0").encoding,
            Some(ContentEncoding::Identity)
        );
        assert!(AcceptEncoding::new(" ").is_none());
        assert!(AcceptEncoding::new("compress").is_none());
        assert!(AcceptEncoding::new("gizp;q=1").is_none());
    }

    /// STATEMENT: Automatic compression selects supported encodings rather than unsupported preferences.
    ///
    /// HOW:
    /// - Parse combinations of zstd, gzip, deflate, and Brotli with automatic selection.
    /// - Assert supported server preferences, identity fallback, whitespace handling, and explicit Brotli selection.
    #[test]
    fn test_auto_skips_unsupported_encodings() {
        let auto = ContentEncoding::Auto;
        assert_eq!(
            parse("gzip, deflate, br, zstd", auto),
            ContentEncoding::Zstd
        );
        assert_eq!(parse("gzip, deflate, br", auto), ContentEncoding::Gzip);
        assert_eq!(parse("br, deflate", auto), ContentEncoding::Deflate);
        assert_eq!(parse("br", auto), ContentEncoding::Identity);
        assert_eq!(parse("gzip, br", ContentEncoding::Br), ContentEncoding::Br);
        assert_eq!(parse(" br ,  gzip ; q=1.0 ", auto), ContentEncoding::Gzip);
        assert_eq!(parse("", auto), ContentEncoding::Identity);
    }

    /// STATEMENT: Automatic compression honors quality weights, first duplicates, and server tie-breaking.
    ///
    /// HOW:
    /// - Parse unequal, zero, malformed, and duplicate quality entries and assert the selected encoding.
    /// - Check equal weights follow server preference and `x-gzip` resolves to gzip.
    #[test]
    fn test_auto_honours_q() {
        let auto = ContentEncoding::Auto;
        assert_eq!(parse("gzip;q=0.5, zstd;q=0.1", auto), ContentEncoding::Gzip);
        assert_eq!(
            parse("deflate;q=0.9, gzip;q=0.8", auto),
            ContentEncoding::Deflate
        );
        assert_eq!(parse("zstd;q=0, gzip", auto), ContentEncoding::Gzip);
        assert_eq!(parse("gzip;q=0", auto), ContentEncoding::Identity);
        assert_eq!(parse("gzip;q=abc", auto), ContentEncoding::Identity);
        assert_eq!(parse("gzip;q=2, deflate", auto), ContentEncoding::Deflate);
        assert_eq!(parse("gzip, zstd;q=0", auto), ContentEncoding::Gzip);
        // the first entry for an encoding wins
        assert_eq!(parse("gzip;q=0, gzip", auto), ContentEncoding::Identity);
        // equal weights go to the server's preference
        assert_eq!(
            parse("deflate;q=0.5, gzip;q=0.5, zstd;q=0.5", auto),
            ContentEncoding::Zstd
        );
        assert_eq!(parse("deflate, gzip", auto), ContentEncoding::Gzip);
        assert_eq!(parse("x-gzip", auto), ContentEncoding::Gzip);
    }

    /// STATEMENT: Wildcard quality supplies defaults while explicit encoding weights take precedence.
    ///
    /// HOW:
    /// - Combine wildcard entries with explicit exclusions and weighted supported encodings.
    /// - Assert the selected encoding follows explicit weights, first wildcard, and identity fallback.
    #[test]
    fn test_auto_wildcard() {
        let auto = ContentEncoding::Auto;
        assert_eq!(parse("*", auto), ContentEncoding::Zstd);
        assert_eq!(parse("*;q=0", auto), ContentEncoding::Identity);
        assert_eq!(parse("*;q=0.5, zstd;q=0", auto), ContentEncoding::Gzip);
        assert_eq!(
            parse("zstd;q=0, gzip;q=0, *", auto),
            ContentEncoding::Deflate
        );
        assert_eq!(parse("*;q=0.5, deflate", auto), ContentEncoding::Deflate);
        assert_eq!(parse("gzip;q=0.1, *;q=0.5", auto), ContentEncoding::Zstd);
        assert_eq!(parse("*;q=0, gzip;q=0.1", auto), ContentEncoding::Gzip);
        assert_eq!(parse("*;q=0.5, *", auto), ContentEncoding::Zstd);
        assert_eq!(parse("*;q=0, *, zstd;q=0", auto), ContentEncoding::Identity);
    }

    /// STATEMENT: Explicit compression uses only the configured encoding when the client accepts it.
    ///
    /// HOW:
    /// - Configure gzip and parse direct matches, other encodings, zero/positive qualities, and wildcards.
    /// - Assert gzip is selected only when accepted, with explicit gzip weights overriding wildcards.
    #[test]
    fn test_explicit_encoding() {
        let gzip = ContentEncoding::Gzip;
        assert_eq!(parse("gzip", gzip), gzip);
        assert_eq!(parse("zstd", gzip), ContentEncoding::Identity);
        assert_eq!(parse("gzip;q=0", gzip), ContentEncoding::Identity);
        assert_eq!(parse("gzip;q=0.001", gzip), gzip);
        assert_eq!(parse("*", gzip), gzip);
        assert_eq!(parse("*;q=0", gzip), ContentEncoding::Identity);
        assert_eq!(parse("*, gzip;q=0", gzip), ContentEncoding::Identity);
        assert_eq!(parse("*;q=0, gzip", gzip), gzip);
    }

    /// STATEMENT: `identity` is chosen over compression only when the client weights it
    /// strictly higher.
    ///
    /// HOW:
    /// - Parse headers that weight `identity`, explicitly or via `*`, above, equal to and
    ///   below the best compression, for both automatic and fixed gzip encoding.
    /// - Assert `Identity` is selected only for a strictly higher weight, and an
    ///   unlisted `identity` does not compete.
    #[test]
    fn test_identity_preference() {
        let auto = ContentEncoding::Auto;
        let gzip = ContentEncoding::Gzip;
        let id = ContentEncoding::Identity;
        assert_eq!(parse("identity;q=1, gzip;q=0.1", auto), id);
        assert_eq!(parse("identity;q=0.5, gzip;q=0.5", auto), gzip);
        assert_eq!(parse("identity;q=0.4, gzip;q=0.5", auto), gzip);
        assert_eq!(parse("*, gzip;q=0.1", auto), ContentEncoding::Zstd);
        assert_eq!(parse("*, zstd;q=0.1, gzip;q=0.1, deflate;q=0.1", auto), id);
        assert_eq!(parse("gzip;q=0.1", auto), gzip);
        assert_eq!(parse("identity;q=1, gzip;q=0.1", gzip), id);
        assert_eq!(parse("identity;q=0.1, gzip;q=0.1", gzip), gzip);
        assert_eq!(parse("*, gzip;q=0.5", gzip), id);
        assert_eq!(parse("identity;q=0, *;q=0.5, gzip;q=0.1", gzip), gzip);
    }

    /// STATEMENT: Encoding negotiation considers values from repeated request headers together.
    ///
    /// HOW:
    /// - Parse separate header values excluding zstd and weighting gzip above deflate.
    /// - Assert automatic negotiation selects gzip.
    #[test]
    fn test_repeated_headers() {
        let values = ["zstd;q=0", "gzip;q=0.5, deflate;q=0.1"];
        assert_eq!(
            AcceptEncoding::parse(values.into_iter(), ContentEncoding::Auto),
            ContentEncoding::Gzip
        );
    }

    /// STATEMENT: Compression middleware negotiates valid repeated headers and skips invalid or disabled encodings.
    ///
    /// HOW:
    /// - Serve a compressible body and assert gzip requests receive `Content-Encoding: gzip`.
    /// - Assert invalid-only and zero-quality headers produce no encoding.
    /// - Combine repeated valid/invalid values and assert gzip or deflate is selected from valid entries.
    #[crate::rt_test]
    async fn test_compress_accept_encoding() {
        use crate::http::header::{CONTENT_ENCODING, HeaderValue};
        use crate::web::test::{TestRequest, call_service, init_service};
        use crate::web::{self, App, HttpResponse};

        let srv = init_service(App::new().middleware(Compress::default()).route(
            "/",
            web::get().to(async || HttpResponse::Ok().body("a".repeat(1024))),
        ))
        .await;

        let req = TestRequest::default()
            .header(ACCEPT_ENCODING, "gzip")
            .to_request();
        let resp = call_service(&srv, req).await;
        assert_eq!(resp.headers().get(CONTENT_ENCODING).unwrap(), "gzip");

        let req = TestRequest::default()
            .header(
                ACCEPT_ENCODING,
                HeaderValue::from_bytes(b"gzip\xff").unwrap(),
            )
            .to_request();
        let resp = call_service(&srv, req).await;
        assert!(resp.headers().get(CONTENT_ENCODING).is_none());

        let req = TestRequest::default()
            .header(ACCEPT_ENCODING, "zstd;q=0")
            .header(ACCEPT_ENCODING, "gzip;q=0.5")
            .to_request();
        let resp = call_service(&srv, req).await;
        assert_eq!(resp.headers().get(CONTENT_ENCODING).unwrap(), "gzip");

        let req = TestRequest::default()
            .header(
                ACCEPT_ENCODING,
                HeaderValue::from_bytes(b"zstd\xff").unwrap(),
            )
            .header(ACCEPT_ENCODING, "deflate")
            .to_request();
        let resp = call_service(&srv, req).await;
        assert_eq!(resp.headers().get(CONTENT_ENCODING).unwrap(), "deflate");

        let req = TestRequest::default()
            .header(ACCEPT_ENCODING, "gzip;q=0")
            .to_request();
        let resp = call_service(&srv, req).await;
        assert!(resp.headers().get(CONTENT_ENCODING).is_none());
    }

    /// STATEMENT: Negotiated responses get `Vary: Accept-Encoding` exactly once, and
    /// responses whose encoding is not negotiated do not.
    ///
    /// HOW:
    /// - Serve compressed, uncompressed and existing-`Vary` responses through
    ///   `Compress::default()` and assert a single `accept-encoding` entry next to other
    ///   `Vary` values, and none added when `Vary: *` or `Vary: Accept-Encoding` is set.
    /// - Assert no `Vary` is added with `ContentEncoding::Identity`, for a
    ///   `BodyEncoding` override, or when the handler sets `Content-Encoding`.
    #[crate::rt_test]
    async fn test_compress_vary() {
        use crate::http::header::{CONTENT_ENCODING, VARY};
        use crate::web::test::{TestRequest, call_service, init_service};
        use crate::web::{self, App, HttpResponse};

        fn body() -> String {
            "a".repeat(1024)
        }
        let srv = init_service(
            App::new()
                .middleware(Compress::default())
                .route("/", web::get().to(async || HttpResponse::Ok().body(body())))
                .route(
                    "/vary",
                    web::get().to(async || HttpResponse::Ok().header(VARY, "origin").body(body())),
                )
                .route(
                    "/star",
                    web::get().to(async || HttpResponse::Ok().header(VARY, "*").body(body())),
                )
                .route(
                    "/has",
                    web::get().to(async || {
                        HttpResponse::Ok()
                            .header(VARY, "Origin, Accept-Encoding")
                            .body(body())
                    }),
                )
                .route(
                    "/override",
                    web::get().to(async || {
                        HttpResponse::Ok()
                            .encoding(ContentEncoding::Identity)
                            .body("a".repeat(1024))
                    }),
                )
                .route(
                    "/encoded",
                    web::get()
                        .to(async || HttpResponse::Ok().header(CONTENT_ENCODING, "br").body("a")),
                ),
        )
        .await;
        let vary = async |path: &str, accept: &str| {
            let req = TestRequest::with_uri(path)
                .header(ACCEPT_ENCODING, accept)
                .to_request();
            let resp = call_service(&srv, req).await;
            resp.headers()
                .get_all(VARY)
                .map(|v| v.to_str().unwrap().to_string())
                .collect::<Vec<_>>()
        };

        assert_eq!(vary("/", "gzip").await, ["accept-encoding"]);
        assert_eq!(vary("/", "identity").await, ["accept-encoding"]);
        assert_eq!(vary("/vary", "gzip").await, ["origin", "accept-encoding"]);
        assert_eq!(vary("/star", "gzip").await, ["*"]);
        assert_eq!(vary("/has", "gzip").await, ["Origin, Accept-Encoding"]);
        assert_eq!(vary("/override", "gzip").await, Vec::<String>::new());
        assert_eq!(vary("/encoded", "gzip").await, Vec::<String>::new());

        let srv = init_service(
            App::new()
                .middleware(Compress::new(ContentEncoding::Identity))
                .route("/", web::get().to(async || HttpResponse::Ok().body(body()))),
        )
        .await;
        let req = TestRequest::default()
            .header(ACCEPT_ENCODING, "gzip")
            .to_request();
        let resp = call_service(&srv, req).await;
        assert!(resp.headers().get(VARY).is_none());
        assert!(resp.headers().get(CONTENT_ENCODING).is_none());
    }
}