topcoat-router 0.9.0

A modular, batteries-included Rust web framework for server-rendered apps.
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
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
mod headers;

use std::{borrow::Cow, convert::Infallible, future::ready};

use bytes::{Bytes, BytesMut};
pub use headers::*;
use http::{
    Extensions, HeaderMap, StatusCode,
    header::{CONTENT_TYPE, HeaderName, HeaderValue},
    response::Parts,
};
use topcoat_core::{
    context::Cx,
    error::{Error, Result},
};

use crate::{Body, BoxError};

pub type Response<T = Body> = http::Response<T>;

const TEXT_PLAIN: HeaderValue = HeaderValue::from_static("text/plain; charset=utf-8");
const APPLICATION_OCTET_STREAM: HeaderValue = HeaderValue::from_static("application/octet-stream");

/// Converts a value into an HTTP [`Response`].
///
/// Return an implementing type from a route handler to build its response.
/// The conversion receives [`Cx`] for access to request context. Every
/// implementation also supports [`AsyncIntoResponse`].
///
/// A response can also be assembled from a tuple. The last element is converted
/// with `IntoResponse` and becomes the body, while the earlier elements modify
/// the response: a leading [`StatusCode`], [`Parts`], or [`Response<()>`] sets
/// the status line, and every other element is applied with
/// [`IntoResponseParts`]. For example `(StatusCode::CREATED, headers, body)`
/// builds a `201` response carrying `headers` and `body`.
///
/// # Examples
///
/// Implement it for a domain type that should control its own status, headers,
/// or body:
///
/// ```rust
/// use topcoat::{
///     Result,
///     context::Cx,
///     router::{
///         Body,
///         response::{IntoResponse, Response},
///         route,
///     },
/// };
///
/// struct Csv(String);
///
/// impl IntoResponse for Csv {
///     fn into_response(self, _cx: &Cx) -> Result<Response> {
///         Ok(Response::builder()
///             .header("Content-Type", "text/csv; charset=utf-8")
///             .body(Body::from(self.0))?)
///     }
/// }
///
/// #[route(GET "/api/report.csv")]
/// async fn report() -> Result<Csv> {
///     Ok(Csv("name,total\nAda,42\n".to_string()))
/// }
/// ```
pub trait IntoResponse {
    /// Converts `self` into an HTTP [`Response`], using the request [`Cx`] for any
    /// request-scoped data.
    ///
    /// # Errors
    ///
    /// Returns an error if the response cannot be assembled (for example, a
    /// header value is invalid).
    fn into_response(self, cx: &Cx) -> Result<Response>;
}

/// Converts a value into an HTTP [`Response`], awaiting whatever the
/// conversion needs.
///
/// Route and layer handlers return any type that implements this trait.
/// Every [`IntoResponse`] type implements it, so a handler only needs it by
/// name when its response cannot be built without awaiting, such as a view
/// that resolves its content first.
pub trait AsyncIntoResponse {
    /// Converts `self` into an HTTP [`Response`], using the request [`Cx`] for any
    /// request-scoped data.
    ///
    /// # Errors
    ///
    /// Returns an error if the response cannot be assembled.
    fn async_into_response(self, cx: &Cx) -> impl Future<Output = Result<Response>> + Send;
}

impl<T: IntoResponse> AsyncIntoResponse for T {
    fn async_into_response(self, cx: &Cx) -> impl Future<Output = Result<Response>> + Send {
        ready(self.into_response(cx))
    }
}

/// Modifies a [`Response`]'s [`Parts`] without supplying a body.
///
/// Place an implementing value before the body in an [`IntoResponse`] tuple
/// to modify its headers or extensions. The conversion receives [`Cx`] for
/// access to request context.
pub trait IntoResponseParts {
    /// Applies `self` to the response `parts`, using the request [`Cx`] for any
    /// request-scoped data.
    ///
    /// # Errors
    ///
    /// Returns an error if a part cannot be applied (for example, a header
    /// value is invalid).
    fn into_response_parts(self, cx: &Cx, parts: &mut Parts) -> Result<()>;
}

/// Builds a response carrying `body` with the given `Content-Type`.
pub(crate) fn content_response(content_type: HeaderValue, body: Body) -> Response {
    let mut response = Response::new(body);
    response.headers_mut().insert(CONTENT_TYPE, content_type);
    response
}

/// Copies the status, version, headers, and extensions of `from` onto `parts`,
/// used when a tuple leads with a [`Parts`] or [`Response<()>`] template.
fn merge_parts(parts: &mut Parts, from: Parts) {
    parts.status = from.status;
    parts.version = from.version;
    parts.headers.extend(from.headers);
    parts.extensions.extend(from.extensions);
}

// -- Leaf IntoResponse impls --

impl IntoResponse for Infallible {
    fn into_response(self, _cx: &Cx) -> Result<Response> {
        match self {}
    }
}

impl IntoResponse for () {
    fn into_response(self, _cx: &Cx) -> Result<Response> {
        Ok(Response::new(Body::empty()))
    }
}

impl IntoResponse for StatusCode {
    fn into_response(self, cx: &Cx) -> Result<Response> {
        (self, ()).into_response(cx)
    }
}

impl IntoResponse for &'static str {
    fn into_response(self, _cx: &Cx) -> Result<Response> {
        Ok(content_response(TEXT_PLAIN, Body::from(self)))
    }
}

impl IntoResponse for String {
    fn into_response(self, _cx: &Cx) -> Result<Response> {
        Ok(content_response(TEXT_PLAIN, Body::from(self)))
    }
}

impl IntoResponse for Box<str> {
    fn into_response(self, cx: &Cx) -> Result<Response> {
        String::from(self).into_response(cx)
    }
}

impl IntoResponse for Cow<'static, str> {
    fn into_response(self, cx: &Cx) -> Result<Response> {
        match self {
            Cow::Borrowed(value) => value.into_response(cx),
            Cow::Owned(value) => value.into_response(cx),
        }
    }
}

impl IntoResponse for &'static [u8] {
    fn into_response(self, _cx: &Cx) -> Result<Response> {
        Ok(content_response(APPLICATION_OCTET_STREAM, Body::from(self)))
    }
}

impl<const N: usize> IntoResponse for &'static [u8; N] {
    fn into_response(self, cx: &Cx) -> Result<Response> {
        let bytes: &'static [u8] = self;
        bytes.into_response(cx)
    }
}

impl<const N: usize> IntoResponse for [u8; N] {
    fn into_response(self, cx: &Cx) -> Result<Response> {
        self.to_vec().into_response(cx)
    }
}

impl IntoResponse for Vec<u8> {
    fn into_response(self, _cx: &Cx) -> Result<Response> {
        Ok(content_response(APPLICATION_OCTET_STREAM, Body::from(self)))
    }
}

impl IntoResponse for Box<[u8]> {
    fn into_response(self, cx: &Cx) -> Result<Response> {
        Vec::from(self).into_response(cx)
    }
}

impl IntoResponse for Cow<'static, [u8]> {
    fn into_response(self, cx: &Cx) -> Result<Response> {
        match self {
            Cow::Borrowed(value) => value.into_response(cx),
            Cow::Owned(value) => value.into_response(cx),
        }
    }
}

impl IntoResponse for Bytes {
    fn into_response(self, _cx: &Cx) -> Result<Response> {
        Ok(content_response(APPLICATION_OCTET_STREAM, Body::from(self)))
    }
}

impl IntoResponse for BytesMut {
    fn into_response(self, cx: &Cx) -> Result<Response> {
        self.freeze().into_response(cx)
    }
}

impl IntoResponse for Body {
    fn into_response(self, _cx: &Cx) -> Result<Response> {
        Ok(Response::new(self))
    }
}

impl IntoResponse for HeaderMap {
    fn into_response(self, cx: &Cx) -> Result<Response> {
        (self, ()).into_response(cx)
    }
}

impl IntoResponse for Extensions {
    fn into_response(self, cx: &Cx) -> Result<Response> {
        (self, ()).into_response(cx)
    }
}

impl IntoResponse for Parts {
    fn into_response(self, cx: &Cx) -> Result<Response> {
        (self, ()).into_response(cx)
    }
}

/// Replies with an empty body carrying each `(name, value)` pair as a header.
impl<K, V, const N: usize> IntoResponse for [(K, V); N]
where
    K: TryInto<HeaderName>,
    K::Error: std::error::Error + Send + Sync + 'static,
    V: TryInto<HeaderValue>,
    V::Error: std::error::Error + Send + Sync + 'static,
{
    fn into_response(self, cx: &Cx) -> Result<Response> {
        (self, ()).into_response(cx)
    }
}

/// Re-bodies any [`http::Response`] whose body is a [`Bytes`] stream into the
/// framework's [`Body`], leaving the parts untouched.
impl<B> IntoResponse for http::Response<B>
where
    B: http_body::Body<Data = Bytes> + Send + 'static,
    B::Error: Into<BoxError>,
{
    fn into_response(self, _cx: &Cx) -> Result<Response> {
        let (parts, body) = self.into_parts();
        Ok(Response::from_parts(parts, Body::new(body)))
    }
}

// -- IntoResponseParts impls --

impl IntoResponseParts for () {
    fn into_response_parts(self, _cx: &Cx, _parts: &mut Parts) -> Result<()> {
        Ok(())
    }
}

impl<T> IntoResponseParts for Option<T>
where
    T: IntoResponseParts,
{
    fn into_response_parts(self, cx: &Cx, parts: &mut Parts) -> Result<()> {
        if let Some(value) = self {
            value.into_response_parts(cx, parts)?;
        }
        Ok(())
    }
}

impl IntoResponseParts for HeaderMap {
    fn into_response_parts(self, _cx: &Cx, parts: &mut Parts) -> Result<()> {
        parts.headers.extend(self);
        Ok(())
    }
}

impl IntoResponseParts for Extensions {
    fn into_response_parts(self, _cx: &Cx, parts: &mut Parts) -> Result<()> {
        parts.extensions.extend(self);
        Ok(())
    }
}

/// Inserts each `(name, value)` pair as a response header, failing if a name or
/// value is not a valid header.
impl<K, V, const N: usize> IntoResponseParts for [(K, V); N]
where
    K: TryInto<HeaderName>,
    K::Error: std::error::Error + Send + Sync + 'static,
    V: TryInto<HeaderValue>,
    V::Error: std::error::Error + Send + Sync + 'static,
{
    fn into_response_parts(self, _cx: &Cx, parts: &mut Parts) -> Result<()> {
        for (name, value) in self {
            let name = name.try_into().map_err(Error::from)?;
            let value = value.try_into().map_err(Error::from)?;
            parts.headers.insert(name, value);
        }
        Ok(())
    }
}

// -- Tuple IntoResponse impls --

/// Generates the four `IntoResponse` tuple families for a fixed number of
/// [`IntoResponseParts`] members `T1..Tn`: a bare tuple, and tuples led by a
/// [`StatusCode`], [`Parts`], or [`Response<()>`] that seeds the response.
///
/// In every family the final element is the body (any [`IntoResponse`]) and the
/// `Ti` are applied to the resulting [`Parts`] in order.
macro_rules! impl_into_response_tuples {
    ( $($ty:ident),* ) => {
        #[allow(non_snake_case, unused_mut, unused_variables)]
        impl<R, $($ty,)*> IntoResponse for ($($ty,)* R,)
        where
            R: IntoResponse,
            $($ty: IntoResponseParts,)*
        {
            fn into_response(self, cx: &Cx) -> Result<Response> {
                let ($($ty,)* r,) = self;
                let (mut parts, body) = r.into_response(cx)?.into_parts();
                $( $ty.into_response_parts(cx, &mut parts)?; )*
                Ok(Response::from_parts(parts, body))
            }
        }

        #[allow(non_snake_case, unused_mut, unused_variables)]
        impl<R, $($ty,)*> IntoResponse for (StatusCode, $($ty,)* R,)
        where
            R: IntoResponse,
            $($ty: IntoResponseParts,)*
        {
            fn into_response(self, cx: &Cx) -> Result<Response> {
                let (status, $($ty,)* r,) = self;
                let (mut parts, body) = r.into_response(cx)?.into_parts();
                parts.status = status;
                $( $ty.into_response_parts(cx, &mut parts)?; )*
                Ok(Response::from_parts(parts, body))
            }
        }

        #[allow(non_snake_case, unused_mut, unused_variables)]
        impl<R, $($ty,)*> IntoResponse for (Parts, $($ty,)* R,)
        where
            R: IntoResponse,
            $($ty: IntoResponseParts,)*
        {
            fn into_response(self, cx: &Cx) -> Result<Response> {
                let (template, $($ty,)* r,) = self;
                let (mut parts, body) = r.into_response(cx)?.into_parts();
                merge_parts(&mut parts, template);
                $( $ty.into_response_parts(cx, &mut parts)?; )*
                Ok(Response::from_parts(parts, body))
            }
        }

        #[allow(non_snake_case, unused_mut, unused_variables)]
        impl<R, $($ty,)*> IntoResponse for (Response<()>, $($ty,)* R,)
        where
            R: IntoResponse,
            $($ty: IntoResponseParts,)*
        {
            fn into_response(self, cx: &Cx) -> Result<Response> {
                let (template, $($ty,)* r,) = self;
                let (template, ()) = template.into_parts();
                let (mut parts, body) = r.into_response(cx)?.into_parts();
                merge_parts(&mut parts, template);
                $( $ty.into_response_parts(cx, &mut parts)?; )*
                Ok(Response::from_parts(parts, body))
            }
        }
    };
}

impl_into_response_tuples!();
impl_into_response_tuples!(T1);
impl_into_response_tuples!(T1, T2);
impl_into_response_tuples!(T1, T2, T3);
impl_into_response_tuples!(T1, T2, T3, T4);
impl_into_response_tuples!(T1, T2, T3, T4, T5);
impl_into_response_tuples!(T1, T2, T3, T4, T5, T6);
impl_into_response_tuples!(T1, T2, T3, T4, T5, T6, T7);
impl_into_response_tuples!(T1, T2, T3, T4, T5, T6, T7, T8);
impl_into_response_tuples!(T1, T2, T3, T4, T5, T6, T7, T8, T9);
impl_into_response_tuples!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10);
impl_into_response_tuples!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11);
impl_into_response_tuples!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12);
impl_into_response_tuples!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13);
impl_into_response_tuples!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14);
impl_into_response_tuples!(
    T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15
);
impl_into_response_tuples!(
    T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16
);

#[cfg(test)]
mod tests {
    use http_body_util::Full;

    use super::*;
    use crate::to_bytes;

    fn block_on<F: Future>(future: F) -> F::Output {
        tokio::runtime::Builder::new_current_thread()
            .build()
            .unwrap()
            .block_on(future)
    }

    /// Renders a value into a response and reads the body fully into memory.
    fn run(value: impl IntoResponse) -> (Parts, Bytes) {
        let cx = Cx::default();
        let (parts, body) = value.into_response(&cx).unwrap().into_parts();
        let bytes = block_on(to_bytes(body, usize::MAX)).unwrap();
        (parts, bytes)
    }

    fn header(parts: &Parts, name: &'static str) -> String {
        parts
            .headers
            .get(name)
            .unwrap()
            .to_str()
            .unwrap()
            .to_owned()
    }

    // -- leaf bodies --

    #[test]
    fn str_is_text_plain() {
        let (parts, body) = run("hi");
        assert_eq!(parts.status, StatusCode::OK);
        assert_eq!(header(&parts, "content-type"), "text/plain; charset=utf-8");
        assert_eq!(&body[..], b"hi");
    }

    #[test]
    fn owned_and_borrowed_text_match() {
        for (parts, body) in [
            run(String::from("hi")),
            run(Box::<str>::from("hi")),
            run(Cow::Borrowed("hi")),
            run(Cow::<str>::Owned("hi".to_owned())),
        ] {
            assert_eq!(header(&parts, "content-type"), "text/plain; charset=utf-8");
            assert_eq!(&body[..], b"hi");
        }
    }

    #[test]
    fn byte_bodies_are_octet_stream() {
        for (parts, body) in [
            run(b"hi".to_vec()),
            run(Bytes::from_static(b"hi")),
            run(BytesMut::from(&b"hi"[..])),
            run(*b"hi"),
            run(b"hi"),
            run(Box::<[u8]>::from(&b"hi"[..])),
        ] {
            assert_eq!(header(&parts, "content-type"), "application/octet-stream");
            assert_eq!(&body[..], b"hi");
        }
    }

    #[test]
    fn unit_is_empty_ok() {
        let (parts, body) = run(());
        assert_eq!(parts.status, StatusCode::OK);
        assert!(body.is_empty());
        assert!(parts.headers.is_empty());
    }

    #[test]
    fn status_code_sets_status_with_empty_body() {
        let (parts, body) = run(StatusCode::NO_CONTENT);
        assert_eq!(parts.status, StatusCode::NO_CONTENT);
        assert!(body.is_empty());
    }

    #[test]
    fn header_map_applies_headers() {
        let mut headers = HeaderMap::new();
        headers.insert(
            HeaderName::from_static("x-test"),
            HeaderValue::from_static("1"),
        );
        let (parts, body) = run(headers);
        assert_eq!(header(&parts, "x-test"), "1");
        assert!(body.is_empty());
    }

    #[test]
    fn extensions_are_applied() {
        #[derive(Clone, Debug, PartialEq)]
        struct Marker(u32);

        let mut extensions = Extensions::new();
        extensions.insert(Marker(7));
        let (parts, _) = run(extensions);
        assert_eq!(parts.extensions.get::<Marker>(), Some(&Marker(7)));
    }

    #[test]
    fn response_passes_through_with_rebodied_stream() {
        let response = http::Response::builder()
            .status(StatusCode::ACCEPTED)
            .header("x-test", "1")
            .body(Full::new(Bytes::from_static(b"yo")))
            .unwrap();
        let (parts, body) = run(response);
        assert_eq!(parts.status, StatusCode::ACCEPTED);
        assert_eq!(header(&parts, "x-test"), "1");
        assert_eq!(&body[..], b"yo");
    }

    // -- header arrays --

    #[test]
    fn header_array_is_into_response() {
        let (parts, body) = run([("x-test", "1"), ("x-other", "2")]);
        assert_eq!(header(&parts, "x-test"), "1");
        assert_eq!(header(&parts, "x-other"), "2");
        assert!(body.is_empty());
    }

    #[test]
    fn invalid_header_name_is_an_error() {
        // A space is not allowed in a header name.
        let cx = Cx::default();
        assert!([("inva lid", "1")].into_response(&cx).is_err());
    }

    // -- tuples --

    #[test]
    fn one_tuple_is_just_the_body() {
        let (parts, body) = run(("hi",));
        assert_eq!(parts.status, StatusCode::OK);
        assert_eq!(&body[..], b"hi");
    }

    #[test]
    fn status_then_body() {
        let (parts, body) = run((StatusCode::CREATED, "hi"));
        assert_eq!(parts.status, StatusCode::CREATED);
        assert_eq!(header(&parts, "content-type"), "text/plain; charset=utf-8");
        assert_eq!(&body[..], b"hi");
    }

    #[test]
    fn headers_then_body() {
        let (parts, body) = run(([("x-test", "1")], "hi"));
        assert_eq!(header(&parts, "x-test"), "1");
        assert_eq!(&body[..], b"hi");
    }

    #[test]
    fn status_headers_and_body() {
        let (parts, body) = run((StatusCode::CREATED, [("x-test", "1")], "hi"));
        assert_eq!(parts.status, StatusCode::CREATED);
        assert_eq!(header(&parts, "x-test"), "1");
        assert_eq!(&body[..], b"hi");
    }

    #[test]
    fn multiple_response_parts_are_all_applied() {
        let (parts, body) = run((
            StatusCode::CREATED,
            [("x-one", "1")],
            [("x-two", "2")],
            "hi",
        ));
        assert_eq!(parts.status, StatusCode::CREATED);
        assert_eq!(header(&parts, "x-one"), "1");
        assert_eq!(header(&parts, "x-two"), "2");
        assert_eq!(&body[..], b"hi");
    }

    #[test]
    fn optional_parts_are_applied_when_present() {
        let (present, _) = run((Some([("x-test", "1")]), "hi"));
        assert_eq!(header(&present, "x-test"), "1");

        let (absent, body) = run((Option::<[(&str, &str); 1]>::None, "hi"));
        assert!(absent.headers.get("x-test").is_none());
        assert_eq!(&body[..], b"hi");
    }

    #[test]
    fn parts_template_seeds_status_and_headers() {
        let (mut template, _) = Response::new(Body::empty()).into_parts();
        template.status = StatusCode::IM_A_TEAPOT;
        template.headers.insert(
            HeaderName::from_static("x-test"),
            HeaderValue::from_static("1"),
        );

        let (parts, body) = run((template, "hi"));
        assert_eq!(parts.status, StatusCode::IM_A_TEAPOT);
        assert_eq!(header(&parts, "x-test"), "1");
        assert_eq!(&body[..], b"hi");
    }

    #[test]
    fn response_unit_template_seeds_status_and_headers() {
        let template = http::Response::builder()
            .status(StatusCode::IM_A_TEAPOT)
            .header("x-test", "1")
            .body(())
            .unwrap();

        let (parts, body) = run((template, "hi"));
        assert_eq!(parts.status, StatusCode::IM_A_TEAPOT);
        assert_eq!(header(&parts, "x-test"), "1");
        assert_eq!(&body[..], b"hi");
    }
}