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
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
//! HTTP responses.

pub(crate) mod handle;

pub(crate) use self::handle::handles_to_response;

use self::handle::ResponseHandle;
use super::body::{self, Body, StreamingBody};
use super::Request;
use crate::backend::Backend;
use crate::convert::{Borrowable, ToHeaderName, ToHeaderValue, ToStatusCode};
use crate::error::BufferSizeError;
use crate::handle::BodyHandle;
use crate::limits;
use fastly_shared::FramingHeadersMode;
use http::header::{self, HeaderMap, HeaderName, HeaderValue};
use http::{StatusCode, Version};
use mime::Mime;
use serde::de::DeserializeOwned;
use serde::Serialize;
use std::borrow::Cow;
use std::io::BufRead;

/// An HTTP response, including body, headers, and status code.
///
/// # Sending to the client
///
/// Each execution of a Compute@Edge program may send a single response back to the client:
///
/// - [`Response::send_to_client()`]
/// - [`Response::stream_to_client()`]
///
/// If no response is explicitly sent by the program, a default `200 OK` response is sent.
///
/// # Creation and conversion
///
/// Responses can be created programmatically:
///
/// - [`Response::new()`]
/// - [`Response::from_body()`]
/// - [`Response::from_status()`]
///
/// Responses are also returned from backend requests:
///
/// - [`Request::send()`]
/// - [`Request::send_async()`]
/// - [`Request::send_async_streaming()`]
///
/// For interoperability with other Rust libraries, [`Response`] can be converted to and from the
/// [`http`] crate's [`http::Response`] type using the [`From`][`Response::from()`] and
/// [`Into`][`Response::into()`] traits.
///
/// # Builder-style methods
///
/// [`Response`] can be used as a
/// [builder](https://doc.rust-lang.org/1.0.0/style/ownership/builders.html), allowing responses to
/// be constructed and used through method chaining. Methods with the `with_` name prefix, such as
/// [`with_header()`][`Self::with_header()`], return `Self` to allow chaining. The builder style is
/// typically most useful when constructing and using a response in a single expression. For
/// example:
///
/// ```no_run
/// # use fastly::Response;
/// Response::new()
///     .with_header("my-header", "hello!")
///     .with_header("my-other-header", "Здравствуйте!")
///     .send_to_client();
/// ```
///
/// # Setter methods
///
/// Setter methods, such as [`set_header()`][`Self::set_header()`], are prefixed by `set_`, and can
/// be used interchangeably with the builder-style methods, allowing you to mix and match styles
/// based on what is most convenient for your program. Setter methods tend to work better than
/// builder-style methods when constructing a value involves conditional branches or loops. For
/// example:
///
/// ```no_run
/// # use fastly::Response;
/// # let needs_translation = true;
/// let mut resp = Response::new().with_header("my-header", "hello!");
/// if needs_translation {
///     resp.set_header("my-other-header", "Здравствуйте!");
/// }
/// resp.send_to_client();
/// ```
#[derive(Debug)]
pub struct Response {
    version: Version,
    status: StatusCode,
    headers: HeaderMap,
    body: Option<Body>,
    fastly_metadata: Option<FastlyResponseMetadata>,
    framing_headers_mode: FramingHeadersMode,
}

impl Response {
    /// Create a new [`Response`].
    ///
    /// The new response is created with status code `200 OK`, no headers, and an empty body.
    pub fn new() -> Self {
        Self {
            version: Version::HTTP_11,
            status: StatusCode::OK,
            headers: HeaderMap::new(),
            body: None,
            fastly_metadata: None,
            framing_headers_mode: FramingHeadersMode::Automatic,
        }
    }

    /// Return whether the response is from a backend request.
    pub fn is_from_backend(&self) -> bool {
        self.fastly_metadata.is_some()
    }

    /// Make a new response with the same headers, status, and version of this response, but no
    /// body.
    ///
    /// If you also need to clone the response body, use
    /// [`clone_with_body()`][`Self::clone_with_body()`]
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use fastly::Response;
    /// let original = Response::from_body("hello")
    ///     .with_header("hello", "world!")
    ///     .with_status(418);
    /// let new = original.clone_without_body();
    /// assert_eq!(original.get_header("hello"), new.get_header("hello"));
    /// assert_eq!(original.get_status(), new.get_status());
    /// assert_eq!(original.get_version(), new.get_version());
    /// assert!(original.has_body());
    /// assert!(!new.has_body());
    /// ```
    pub fn clone_without_body(&self) -> Response {
        Self {
            version: self.version,
            status: self.status,
            headers: self.headers.clone(),
            body: None,
            fastly_metadata: self.fastly_metadata.clone(),
            framing_headers_mode: self.framing_headers_mode,
        }
    }

    /// Clone this response by reading in its body, and then writing the same body to the original
    /// and the cloned response.
    ///
    /// This method requires mutable access to this response because reading from and writing to the
    /// body can involve an HTTP connection.
    ///
    #[doc = include_str!("../../docs/snippets/clones-body.md")]
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use fastly::Response;
    /// let mut original = Response::from_body("hello")
    ///     .with_header("hello", "world!")
    ///     .with_status(418);
    /// let mut new = original.clone_with_body();
    /// assert_eq!(original.get_header("hello"), new.get_header("hello"));
    /// assert_eq!(original.get_status(), new.get_status());
    /// assert_eq!(original.get_version(), new.get_version());
    /// assert_eq!(original.take_body_bytes(), new.take_body_bytes());
    /// ```
    pub fn clone_with_body(&mut self) -> Response {
        let mut new_resp = self.clone_without_body();
        if self.has_body() {
            for chunk in self.take_body().read_chunks(4096) {
                let chunk = chunk.expect("can read body chunk");
                new_resp.get_body_mut().write_bytes(&chunk);
                self.get_body_mut().write_bytes(&chunk);
            }
        }
        new_resp
    }

    /// Create a new [`Response`] with the given value as the body.
    ///
    #[doc = include_str!("../../docs/snippets/body-argument.md")]
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use fastly::Response;
    /// let resp = Response::from_body("hello");
    /// assert_eq!(&resp.into_body_str(), "hello");
    /// ```
    ///
    /// ```no_run
    /// # use fastly::Response;
    /// let body_bytes: &[u8] = &[1, 2, 3];
    /// let resp = Response::from_body(body_bytes);
    /// assert_eq!(resp.into_body_bytes().as_slice(), body_bytes);
    /// ```
    pub fn from_body(body: impl Into<Body>) -> Self {
        Self::new().with_body(body)
    }

    /// Create a new response with the given status code.
    ///
    #[doc = include_str!("../../docs/snippets/body-argument.md")]
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use fastly::Response;
    /// use fastly::http::StatusCode;
    /// let resp = Response::from_status(StatusCode::NOT_FOUND);
    /// assert_eq!(resp.get_status().as_u16(), 404);
    /// ```
    ///
    /// ```no_run
    /// # use fastly::Response;
    /// use fastly::http::StatusCode;
    /// let resp = Response::from_status(404);
    /// assert_eq!(resp.get_status(), StatusCode::NOT_FOUND);
    /// ```
    pub fn from_status(status: impl ToStatusCode) -> Self {
        Self::new().with_status(status)
    }

    /// Create a 303 See Other response with the given value as the `Location` header.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use fastly::Response;
    /// # use http::{header, StatusCode};
    /// let resp = Response::see_other("https://www.fastly.com");
    /// assert_eq!(resp.get_status(), StatusCode::SEE_OTHER);
    /// assert_eq!(resp.get_header_str(header::LOCATION).unwrap(), "https://www.fastly.com");
    /// ```
    pub fn see_other(destination: impl ToHeaderValue) -> Self {
        Self::new()
            .with_status(StatusCode::SEE_OTHER)
            .with_header(header::LOCATION, destination)
    }

    /// Create a 308 Permanent Redirect response with the given value as the `Location` header.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use fastly::Response;
    /// # use http::{header, StatusCode};
    /// let resp = Response::redirect("https://www.fastly.com");
    /// assert_eq!(resp.get_status(), StatusCode::PERMANENT_REDIRECT);
    /// assert_eq!(resp.get_header_str(header::LOCATION).unwrap(), "https://www.fastly.com");
    /// ```
    pub fn redirect(destination: impl ToHeaderValue) -> Self {
        Self::new()
            .with_status(StatusCode::PERMANENT_REDIRECT)
            .with_header(header::LOCATION, destination)
    }

    /// Create a 307 Temporary Redirect response with the given value as the `Location` header.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use fastly::Response;
    /// # use http::{header, StatusCode};
    /// let resp = Response::temporary_redirect("https://www.fastly.com");
    /// assert_eq!(resp.get_status(), StatusCode::TEMPORARY_REDIRECT);
    /// assert_eq!(resp.get_header_str(header::LOCATION).unwrap(), "https://www.fastly.com");
    /// ```
    pub fn temporary_redirect(destination: impl ToHeaderValue) -> Self {
        Self::new()
            .with_status(StatusCode::TEMPORARY_REDIRECT)
            .with_header(header::LOCATION, destination)
    }

    /// Builder-style equivalent of [`set_body()`][`Self::set_body()`].
    pub fn with_body(mut self, body: impl Into<Body>) -> Self {
        self.set_body(body);
        self
    }

    /// Returns `true` if this response has a body.
    pub fn has_body(&self) -> bool {
        self.body.is_some()
    }

    /// Get a mutable reference to the body of this response.
    ///
    #[doc = include_str!("../../docs/snippets/creates-empty-body.md")]
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use fastly::Response;
    /// use std::io::Write;
    ///
    /// let mut resp = Response::from_body("hello,");
    /// write!(resp.get_body_mut(), " world!").unwrap();
    /// assert_eq!(&resp.into_body_str(), "hello, world!");
    /// ```
    pub fn get_body_mut(&mut self) -> &mut Body {
        self.body.get_or_insert_with(|| Body::new())
    }

    /// Get a shared reference to the body of this response if it has one, otherwise return `None`.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use fastly::Response;
    /// use std::io::Write;
    ///
    /// let mut resp = Response::new();
    /// assert!(resp.try_get_body_mut().is_none());
    ///
    /// resp.set_body("hello,");
    /// write!(resp.try_get_body_mut().expect("body now exists"), " world!").unwrap();
    /// assert_eq!(&resp.into_body_str(), "hello, world!");
    /// ```
    pub fn try_get_body_mut(&mut self) -> Option<&mut Body> {
        self.body.as_mut()
    }

    /// Get a prefix of this response's body containing up to the given number of bytes.
    ///
    /// See [`Body::get_prefix_mut()`] for details.
    pub fn get_body_prefix_mut(&mut self, length: usize) -> body::Prefix {
        self.get_body_mut().get_prefix_mut(length)
    }

    /// Get a prefix of this response's body as a string containing up to the given number of bytes.
    ///
    /// See [`Body::get_prefix_str_mut()`] for details.
    ///
    /// # Panics
    ///
    /// If the prefix contains invalid UTF-8 bytes, this function will panic. The exception to this
    /// is if the bytes are invalid because a multi-byte codepoint is cut off by the requested
    /// prefix length. In this case, the invalid bytes are left off the end of the prefix.
    ///
    /// To explicitly handle the possibility of invalid UTF-8 bytes, use
    /// [`try_get_body_prefix_str_mut()`][`Self::try_get_body_prefix_str_mut()`], which returns an
    /// error on failure rather than panicking.
    pub fn get_body_prefix_str_mut(&mut self, length: usize) -> body::PrefixString {
        self.get_body_mut().get_prefix_str_mut(length)
    }

    /// Try to get a prefix of the body as a string containing up to the given number of bytes.
    ///
    /// See [`Body::try_get_prefix_str_mut()`] for details.
    pub fn try_get_body_prefix_str_mut(
        &mut self,
        length: usize,
    ) -> Result<body::PrefixString, std::str::Utf8Error> {
        self.get_body_mut().try_get_prefix_str_mut(length)
    }

    /// Set the given value as the response's body.
    #[doc = include_str!("../../docs/snippets/body-argument.md")]
    #[doc = include_str!("../../docs/snippets/discards-body.md")]
    pub fn set_body(&mut self, body: impl Into<Body>) {
        self.body = Some(body.into());
    }

    /// Take and return the body from this response.
    ///
    /// After calling this method, this response will no longer have a body.
    ///
    #[doc = include_str!("../../docs/snippets/creates-empty-body.md")]
    pub fn take_body(&mut self) -> Body {
        self.body.take().unwrap_or_else(|| Body::new())
    }

    /// Take and return the body from this response if it has one, otherwise return `None`.
    ///
    /// After calling this method, this response will no longer have a body.
    pub fn try_take_body(&mut self) -> Option<Body> {
        self.body.take()
    }

    /// Append another [`Body`] to the body of this response without reading or writing any body
    /// contents.
    ///
    /// If this response does not have a body, the appended body is set as the response's body.
    ///
    #[doc = include_str!("../../docs/snippets/body-append-constant-time.md")]
    ///
    /// This method should be used when combining bodies that have not necessarily been read yet,
    /// such as a body returned from a backend response. To append contents that are already in
    /// memory as strings or bytes, use [`get_body_mut()`][`Self::get_body_mut()`] to write the
    /// contents to the end of the body.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use fastly::{Request, Response};
    /// let mut resp = Response::from_body("hello! backend says: ");
    /// let backend_resp = Request::get("https://example.com/").send("example_backend").unwrap();
    /// resp.append_body(backend_resp.into_body());
    /// resp.send_to_client();
    /// ```
    pub fn append_body(&mut self, other: Body) {
        if let Some(ref mut body) = &mut self.body {
            body.append(other);
        } else {
            self.body = Some(other);
        }
    }

    /// Consume the response and return its body as a byte vector.
    ///
    #[doc = include_str!("../../docs/snippets/buffers-body-reqresp.md")]
    /// # Examples
    ///
    /// ```no_run
    /// # use fastly::Response;
    /// let resp = Response::from_body(b"hello, world!".to_vec());
    /// let bytes = resp.into_body_bytes();
    /// assert_eq!(&bytes, b"hello, world!");
    pub fn into_body_bytes(mut self) -> Vec<u8> {
        self.take_body_bytes()
    }

    /// Consume the response and return its body as a string.
    ///
    #[doc = include_str!("../../docs/snippets/buffers-body-reqresp.md")]
    ///
    /// # Panics
    ///
    #[doc = include_str!("../../docs/snippets/panics-reqresp-intobody-utf8.md")]
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use fastly::Response;
    /// let resp = Response::from_body("hello, world!");
    /// let string = resp.into_body_str();
    /// assert_eq!(&string, "hello, world!");
    /// ```
    pub fn into_body_str(mut self) -> String {
        self.take_body_str()
    }

    /// Consume the response and return its body as a string, including invalid characters.
    ///
    #[doc = include_str!("../../docs/snippets/utf8-replacement.md")]
    ///
    #[doc = include_str!("../../docs/snippets/buffers-body-reqresp.md")]
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use fastly::Response;
    /// let mut resp = Response::new();
    /// resp.set_body_octet_stream(b"\xF0\x90\x80 hello, world!");
    /// let string = resp.into_body_str_lossy();
    /// assert_eq!(&string, "� hello, world!");
    /// ```
    pub fn into_body_str_lossy(mut self) -> String {
        self.take_body_str_lossy()
    }

    /// Consume the response and return its body.
    ///
    #[doc = include_str!("../../docs/snippets/creates-empty-body.md")]
    pub fn into_body(self) -> Body {
        self.body.unwrap_or_else(|| Body::new())
    }

    /// Consume the response and return its body if it has one, otherwise return `None`.
    pub fn try_into_body(self) -> Option<Body> {
        self.body
    }

    /// Deprecated alias of [`with_body_text_plain()`][`Self::with_body_text_plain()`]
    #[deprecated(
        since = "0.7.0",
        note = "renamed to `Response::with_body_text_plain()`"
    )]
    pub fn with_body_str(self, body: &str) -> Self {
        self.with_body_text_plain(body)
    }

    /// Builder-style equivalent of [`set_body_text_plain()`][`Self::set_body_text_plain()`].
    pub fn with_body_text_plain(mut self, body: &str) -> Self {
        self.set_body_text_plain(body);
        self
    }

    /// Deprecated alias of [`set_body_text_plain()`][`Self::set_body_text_plain()`]
    #[deprecated(since = "0.7.0", note = "renamed to `Response::set_body_text_plain()`")]
    pub fn set_body_str(&mut self, body: &str) {
        self.set_body_text_plain(body);
    }

    /// Set the given string as the response's body with content type `text/plain; charset=UTF-8`.
    ///
    #[doc = include_str!("../../docs/snippets/discards-body.md")]
    #[doc = include_str!("../../docs/snippets/sets-text-plain.md")]
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use fastly::Response;
    /// let mut resp = Response::new();
    /// resp.set_body_text_plain("hello, world!");
    /// assert_eq!(resp.get_content_type(), Some(fastly::mime::TEXT_PLAIN_UTF_8));
    /// assert_eq!(&resp.into_body_str(), "hello, world!");
    /// ```
    pub fn set_body_text_plain(&mut self, body: &str) {
        self.body = Some(Body::from(body));
        self.set_content_type(mime::TEXT_PLAIN_UTF_8);
    }

    /// Builder-style equivalent of [`set_body_text_html()`][`Self::set_body_text_html()`].
    pub fn with_body_text_html(mut self, body: &str) -> Self {
        self.set_body_text_html(body);
        self
    }

    /// Set the given string as the request's body with content type `text/html; charset=UTF-8`.
    ///
    #[doc = include_str!("../../docs/snippets/discards-body.md")]
    #[doc = include_str!("../../docs/snippets/sets-text-html.md")]
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use fastly::Response;
    /// let mut resp = Response::new();
    /// resp.set_body_text_html("<p>hello, world!</p>");
    /// assert_eq!(resp.get_content_type(), Some(fastly::mime::TEXT_HTML_UTF_8));
    /// assert_eq!(&resp.into_body_str(), "<p>hello, world!</p>");
    /// ```
    pub fn set_body_text_html(&mut self, body: &str) {
        self.body = Some(Body::from(body));
        self.set_content_type(mime::TEXT_HTML_UTF_8);
    }

    /// Take and return the body from this response as a string.
    ///
    /// After calling this method, this response will no longer have a body.
    ///
    #[doc = include_str!("../../docs/snippets/buffers-body-reqresp.md")]
    ///
    /// # Panics
    ///
    #[doc = include_str!("../../docs/snippets/panics-reqresp-takebody-utf8.md")]
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use fastly::Response;
    /// let mut resp = Response::from_body("hello, world!");
    /// let string = resp.take_body_str();
    /// assert!(resp.try_take_body().is_none());
    /// assert_eq!(&string, "hello, world!");
    /// ```
    pub fn take_body_str(&mut self) -> String {
        if let Some(body) = self.try_take_body() {
            body.into_string()
        } else {
            String::new()
        }
    }

    /// Take and return the body from this response as a string, including invalid characters.
    ///
    #[doc = include_str!("../../docs/snippets/utf8-replacement.md")]
    ///
    /// After calling this method, this response will no longer have a body.
    ///
    #[doc = include_str!("../../docs/snippets/buffers-body-reqresp.md")]
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use fastly::Response;
    /// let mut resp = Response::new();
    /// resp.set_body_octet_stream(b"\xF0\x90\x80 hello, world!");
    /// let string = resp.take_body_str_lossy();
    /// assert!(resp.try_take_body().is_none());
    /// assert_eq!(&string, "� hello, world!");
    /// ```
    pub fn take_body_str_lossy(&mut self) -> String {
        if let Some(body) = self.try_take_body() {
            String::from_utf8_lossy(&body.into_bytes()).to_string()
        } else {
            String::new()
        }
    }

    /// Return a [`Lines`][`std::io::Lines`] iterator that reads the response body a line at a time.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use fastly::{Body, Response};
    /// use std::io::Write;
    ///
    /// fn remove_es(resp: &mut Response) {
    ///     let mut no_es = Body::new();
    ///     for line in resp.read_body_lines() {
    ///         writeln!(no_es, "{}", line.unwrap().replace("e", "")).unwrap();
    ///     }
    ///     resp.set_body(no_es);
    /// }
    /// ```
    pub fn read_body_lines(&mut self) -> std::io::Lines<&mut Body> {
        self.get_body_mut().lines()
    }

    /// Deprecated alias of [`with_body_octet_stream()`][`Self::with_body_octet_stream()`]
    #[deprecated(
        since = "0.8.1",
        note = "renamed to `Response::with_body_octet_stream()`"
    )]
    pub fn with_body_bytes(self, body: &[u8]) -> Self {
        self.with_body_octet_stream(body)
    }

    /// Deprecated alias of [`set_body_octet_stream()`][`Self::set_body_octet_stream()`]
    #[deprecated(
        since = "0.8.1",
        note = "renamed to `Response::set_body_octet_stream()`"
    )]
    pub fn set_body_bytes(&mut self, body: &[u8]) {
        self.set_body_octet_stream(body);
    }

    /// Builder-style equivalent of [`set_body_octet_stream()`][`Self::set_body_octet_stream()`].
    pub fn with_body_octet_stream(mut self, body: &[u8]) -> Self {
        self.set_body_octet_stream(body);
        self
    }

    /// Set the given bytes as the response's body.
    ///
    #[doc = include_str!("../../docs/snippets/discards-body.md")]
    #[doc = include_str!("../../docs/snippets/sets-app-octet-stream.md")]
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use fastly::Response;
    /// let mut resp = Response::new();
    /// resp.set_body_octet_stream(b"hello, world!");
    /// assert_eq!(resp.get_content_type(), Some(fastly::mime::APPLICATION_OCTET_STREAM));
    /// assert_eq!(&resp.into_body_bytes(), b"hello, world!");
    /// ```
    pub fn set_body_octet_stream(&mut self, body: &[u8]) {
        self.body = Some(Body::from(body));
        self.set_content_type(mime::APPLICATION_OCTET_STREAM);
    }

    /// Take and return the body from this response as a string.
    ///
    /// After calling this method, this response will no longer have a body.
    ///
    #[doc = include_str!("../../docs/snippets/buffers-body-reqresp.md")]
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use fastly::Response;
    /// let mut resp = Response::from_body(b"hello, world!".to_vec());
    /// let bytes = resp.take_body_bytes();
    /// assert!(resp.try_take_body().is_none());
    /// assert_eq!(&bytes, b"hello, world!");
    /// ```
    pub fn take_body_bytes(&mut self) -> Vec<u8> {
        if let Some(body) = self.try_take_body() {
            body.into_bytes()
        } else {
            Vec::new()
        }
    }

    /// Return an iterator that reads the response body in chunks of at most the given number of
    /// bytes.
    ///
    /// If `chunk_size` does not evenly divide the length of the body, then the last chunk will not
    /// have length `chunk_size`.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use fastly::{Body, Response};
    /// fn remove_0s(resp: &mut Response) {
    ///     let mut no_0s = Body::new();
    ///     for chunk in resp.read_body_chunks(4096) {
    ///         let mut chunk = chunk.unwrap();
    ///         chunk.retain(|b| *b != 0);
    ///         no_0s.write_bytes(&chunk);
    ///     }
    ///     resp.set_body(no_0s);
    /// }
    /// ```
    pub fn read_body_chunks<'a>(
        &'a mut self,
        chunk_size: usize,
    ) -> impl Iterator<Item = Result<Vec<u8>, std::io::Error>> + 'a {
        self.get_body_mut().read_chunks(chunk_size)
    }

    /// Builder-style equivalent of [`set_body_json()`][Self::set_body_json()`].
    pub fn with_body_json(mut self, value: &impl Serialize) -> Result<Self, serde_json::Error> {
        self.set_body_json(value)?;
        Ok(self)
    }

    /// Convert the given value to JSON and set that JSON as the response's body.
    ///
    /// The given value must implement [`serde::Serialize`]. You can either implement that trait for
    /// your own custom type, or use [`serde_json::Value`] to create untyped JSON values. See
    /// [`serde_json`] for details.
    ///
    #[doc = include_str!("../../docs/snippets/discards-body.md")]
    #[doc = include_str!("../../docs/snippets/sets-app-json.md")]
    ///
    /// # Errors
    ///
    /// This method returns [`serde_json::Error`] if serialization fails.
    ///
    /// # Examples
    ///
    /// Using a type that derives [`serde::Serialize`]:
    ///
    /// ```no_run
    /// # use fastly::Response;
    /// #[derive(serde::Serialize)]
    /// struct MyData {
    ///     name: String,
    ///     count: u64,
    /// }
    /// let my_data = MyData { name: "Computers".to_string(), count: 1024 };
    /// let mut resp = Response::new();
    /// resp.set_body_json(&my_data).unwrap();
    /// assert_eq!(resp.get_content_type(), Some(fastly::mime::APPLICATION_JSON));
    /// assert_eq!(&resp.into_body_str(), r#"{"name":"Computers","count":1024}"#);
    /// ```
    ///
    /// Using untyped JSON and the [`serde_json::json`] macro:
    ///
    /// ```no_run
    /// # use fastly::Response;
    /// let my_data = serde_json::json!({
    ///     "name": "Computers",
    ///     "count": 1024,
    /// });
    /// let mut resp = Response::new();
    /// resp.set_body_json(&my_data).unwrap();
    /// assert_eq!(resp.get_content_type(), Some(fastly::mime::APPLICATION_JSON));
    /// assert_eq!(&resp.into_body_str(), r#"{"count":1024,"name":"Computers"}"#);
    /// ```
    pub fn set_body_json(&mut self, value: &impl Serialize) -> Result<(), serde_json::Error> {
        self.body = Some(Body::new());
        serde_json::to_writer(self.get_body_mut(), value)?;
        self.set_content_type(mime::APPLICATION_JSON);
        Ok(())
    }

    /// Take the response body and attempt to parse it as a JSON value.
    ///
    /// The return type must implement [`serde::Deserialize`] without any non-static lifetimes. You
    /// can either implement that trait for your own custom type, or use [`serde_json::Value`] to
    /// deserialize untyped JSON values. See [`serde_json`] for details.
    ///
    /// After calling this method, this response will no longer have a body.
    ///
    /// # Errors
    ///
    /// This method returns [`serde_json::Error`] if deserialization fails.
    ///
    /// # Examples
    ///
    /// Using a type that derives [`serde::de::DeserializeOwned`]:
    ///
    /// ```no_run
    /// # use fastly::Response;
    /// #[derive(serde::Deserialize)]
    /// struct MyData {
    ///     name: String,
    ///     count: u64,
    /// }
    /// let mut resp = Response::from_body(r#"{"name":"Computers","count":1024}"#);
    /// let my_data = resp.take_body_json::<MyData>().unwrap();
    /// assert_eq!(&my_data.name, "Computers");
    /// assert_eq!(my_data.count, 1024);
    /// ```
    ///
    /// Using untyped JSON with [`serde_json::Value`]:
    ///
    /// ```no_run
    /// # use fastly::Response;
    /// let my_data = serde_json::json!({
    ///     "name": "Computers",
    ///     "count": 1024,
    /// });
    /// let mut resp = Response::from_body(r#"{"name":"Computers","count":1024}"#);
    /// let my_data = resp.take_body_json::<serde_json::Value>().unwrap();
    /// assert_eq!(my_data["name"].as_str(), Some("Computers"));
    /// assert_eq!(my_data["count"].as_u64(), Some(1024));
    /// ```
    pub fn take_body_json<T: DeserializeOwned>(&mut self) -> Result<T, serde_json::Error> {
        if let Some(body) = self.try_take_body() {
            serde_json::from_reader(body)
        } else {
            serde_json::from_reader(std::io::empty())
        }
    }

    /// Builder-style equivalent of [`set_body_form()`][`Self::set_body_form()`].
    pub fn with_body_form(
        mut self,
        value: &impl Serialize,
    ) -> Result<Self, serde_urlencoded::ser::Error> {
        self.set_body_form(value)?;
        Ok(self)
    }

    /// Convert the given value to `application/x-www-form-urlencoded` format and set that data as
    /// the response's body.
    ///
    /// The given value must implement [`serde::Serialize`]; see the trait documentation for
    /// details.
    ///
    #[doc = include_str!("../../docs/snippets/discards-body.md")]
    ///
    /// # Content type
    ///
    /// This method sets the content type to `application/x-www-form-urlencoded`.
    ///
    /// # Errors
    ///
    /// This method returns [`serde_urlencoded::ser::Error`] if serialization fails.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use fastly::Response;
    /// #[derive(serde::Serialize)]
    /// struct MyData {
    ///     name: String,
    ///     count: u64,
    /// }
    /// let my_data = MyData { name: "Computers".to_string(), count: 1024 };
    /// let mut resp = Response::new();
    /// resp.set_body_form(&my_data).unwrap();
    /// assert_eq!(resp.get_content_type(), Some(fastly::mime::APPLICATION_WWW_FORM_URLENCODED));
    /// assert_eq!(&resp.into_body_str(), "name=Computers&count=1024");
    /// ```
    pub fn set_body_form(
        &mut self,
        value: &impl Serialize,
    ) -> Result<(), serde_urlencoded::ser::Error> {
        self.body = Some(Body::new());
        let s = serde_urlencoded::to_string(value)?;
        self.set_body(s);
        self.set_content_type(mime::APPLICATION_WWW_FORM_URLENCODED);
        Ok(())
    }

    /// Take the response body and attempt to parse it as a `application/x-www-form-urlencoded`
    /// formatted string.
    ///
    #[doc = include_str!("../../docs/snippets/returns-deserializeowned.md")]
    ///
    /// After calling this method, this response will no longer have a body.
    ///
    /// # Errors
    ///
    /// This method returns [`serde_urlencoded::de::Error`] if deserialization fails.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use fastly::Response;
    /// #[derive(serde::Deserialize)]
    /// struct MyData {
    ///     name: String,
    ///     count: u64,
    /// }
    /// let mut resp = Response::from_body("name=Computers&count=1024");
    /// let my_data = resp.take_body_form::<MyData>().unwrap();
    /// assert_eq!(&my_data.name, "Computers");
    /// assert_eq!(my_data.count, 1024);
    /// ```
    pub fn take_body_form<T: DeserializeOwned>(
        &mut self,
    ) -> Result<T, serde_urlencoded::de::Error> {
        if let Some(body) = self.try_take_body() {
            serde_urlencoded::from_reader(body)
        } else {
            serde_urlencoded::from_reader(std::io::empty())
        }
    }

    /// Get the MIME type described by the response's
    /// [`Content-Type`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type)
    /// header, or `None` if that header is absent or contains an invalid MIME type.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use fastly::Response;
    /// let resp = Response::new().with_body_text_plain("hello, world!");
    /// assert_eq!(resp.get_content_type(), Some(fastly::mime::TEXT_PLAIN_UTF_8));
    /// ```
    pub fn get_content_type(&self) -> Option<Mime> {
        self.get_header_str(http::header::CONTENT_TYPE)
            .and_then(|v| v.parse().ok())
    }

    /// Builder-style equivalent of [`set_content_type()`][`Self::set_content_type()`].
    pub fn with_content_type(mut self, mime: Mime) -> Self {
        self.set_content_type(mime);
        self
    }

    /// Set the MIME type described by the response's
    /// [`Content-Type`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type)
    /// header.
    ///
    /// Any existing `Content-Type` header values will be overwritten.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use fastly::Response;
    /// let mut resp = Response::new().with_body("hello,world!");
    /// resp.set_content_type(fastly::mime::TEXT_CSV_UTF_8);
    /// ```
    pub fn set_content_type(&mut self, mime: Mime) {
        self.set_header(http::header::CONTENT_TYPE, mime.as_ref())
    }

    /// Get the value of the response's
    /// [`Content-Length`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Length)
    /// header, if it exists.
    pub fn get_content_length(&self) -> Option<usize> {
        self.get_header(http::header::CONTENT_LENGTH)
            .and_then(|v| v.to_str().ok())
            .and_then(|v| v.parse().ok())
    }

    /// Returns whether the given header name is present in the response.
    ///
    #[doc = include_str!("../../docs/snippets/header-name-argument.md")]
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use fastly::Response;
    /// let resp = Response::new().with_header("hello", "world!");
    /// assert!(resp.contains_header("hello"));
    /// assert!(!resp.contains_header("not-present"));
    /// ```
    pub fn contains_header(&self, name: impl ToHeaderName) -> bool {
        self.headers.contains_key(name.into_borrowable().as_ref())
    }

    /// Builder-style equivalent of [`set_header()`][`Self::set_header()`].
    pub fn with_header(mut self, name: impl ToHeaderName, value: impl ToHeaderValue) -> Self {
        self.set_header(name, value);
        self
    }

    /// Get the value of a header as a string, or `None` if the header is not present.
    ///
    /// If there are multiple values for the header, only one is returned, which may be any of the
    /// values. See [`get_header_all_str()`][`Self::get_header_all_str()`] if you need to get all of
    /// the values.
    ///
    #[doc = include_str!("../../docs/snippets/header-name-argument.md")]
    ///
    /// # Panics
    ///
    #[doc = include_str!("../../docs/snippets/panics-reqresp-header-utf8.md")]
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use fastly::Response;
    /// let resp = Response::new().with_header("hello", "world!");
    /// assert_eq!(resp.get_header_str("hello"), Some("world"));
    /// ```
    pub fn get_header_str<'a>(&self, name: impl ToHeaderName) -> Option<&str> {
        let name = name.into_borrowable();
        if let Some(hdr) = self.get_header(name.as_ref()) {
            Some(
                hdr.to_str().unwrap_or_else(|_| {
                    panic!("invalid UTF-8 HTTP header value for header: {}", name)
                }),
            )
        } else {
            None
        }
    }

    /// Get the value of a header as a string, including invalid characters, or `None` if the header
    /// is not present.
    ///
    #[doc = include_str!("../../docs/snippets/utf8-replacement.md")]
    ///
    /// If there are multiple values for the header, only one is returned, which may be any of the
    /// values. See [`get_header_all_str_lossy()`][`Self::get_header_all_str_lossy()`] if you need
    /// to get all of the values.
    ///
    #[doc = include_str!("../../docs/snippets/header-name-argument.md")]
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use fastly::Response;
    /// # use http::header::HeaderValue;
    /// # use std::borrow::Cow;
    /// let header_value = HeaderValue::from_bytes(b"\xF0\x90\x80 world!").unwrap();
    /// let resp = Response::new().with_header("hello", header_value);
    /// assert_eq!(resp.get_header_str_lossy("hello"), Some(Cow::from("� world")));
    /// ```
    pub fn get_header_str_lossy(&self, name: impl ToHeaderName) -> Option<Cow<'_, str>> {
        self.get_header(name)
            .map(|hdr| String::from_utf8_lossy(hdr.as_bytes()))
    }

    /// Get the value of a header, or `None` if the header is not present.
    ///
    /// If there are multiple values for the header, only one is returned, which may be any of the
    /// values. See [`get_header_all()`][`Self::get_header_all()`] if you need to get all of the
    /// values.
    ///
    #[doc = include_str!("../../docs/snippets/header-name-argument.md")]
    ///
    /// # Examples
    ///
    /// Handling UTF-8 values explicitly:
    ///
    /// ```no_run
    /// # use fastly::Response;
    /// # use fastly::http::HeaderValue;
    /// let resp = Response::new().with_header("hello", "world!");
    /// assert_eq!(resp.get_header("hello"), Some(&HeaderValue::from_static("world")));
    /// ```
    ///
    /// Safely handling invalid UTF-8 values:
    ///
    /// ```no_run
    /// # use fastly::Response;
    /// let invalid_utf8 = &"🐈".as_bytes()[0..3];
    /// let resp = Response::new().with_header("hello", invalid_utf8);
    /// assert_eq!(resp.get_header("hello").unwrap().as_bytes(), invalid_utf8);
    /// ```
    pub fn get_header<'a>(&self, name: impl ToHeaderName) -> Option<&HeaderValue> {
        self.headers.get(name.into_borrowable().as_ref())
    }

    /// Get all values of a header as strings, or an empty vector if the header is not present.
    ///
    #[doc = include_str!("../../docs/snippets/header-name-argument.md")]
    ///
    /// # Panics
    ///
    #[doc = include_str!("../../docs/snippets/panics-reqresp-headers-utf8.md")]
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use fastly::Response;
    /// let resp = Response::new()
    ///     .with_header("hello", "world!")
    ///     .with_header("hello", "universe!");
    /// let values = resp.get_header_all_str("hello");
    /// assert_eq!(values.len(), 2);
    /// assert!(values.contains(&"world!"));
    /// assert!(values.contains(&"universe!"));
    /// ```
    pub fn get_header_all_str<'a>(&self, name: impl ToHeaderName) -> Vec<&str> {
        let name = name.into_borrowable();
        self.get_header_all(name.as_ref())
            .map(|v| {
                v.to_str()
                    .unwrap_or_else(|_| panic!("non-UTF-8 HTTP header value for header: {}", name))
            })
            .collect()
    }

    /// Get an iterator of all the response's header names and values.
    ///
    /// # Examples
    ///
    /// You can turn the iterator into a collection, like [`Vec`]:
    ///
    /// ```no_run
    /// # use fastly::Response;
    /// # use fastly::http::header::{HeaderName, HeaderValue};
    /// let resp = Response::new()
    ///     .with_header("hello", "world!")
    ///     .with_header("hello", "universe!");
    ///
    /// let headers: Vec<(&HeaderName, &HeaderValue)> = resp.get_headers().collect();
    /// assert_eq!(headers.len(), 2);
    /// assert!(headers.contains(&(&HeaderName::from_static("hello"), &HeaderValue::from_static("world!"))));
    /// assert!(headers.contains(&(&HeaderName::from_static("hello"), &HeaderValue::from_static("universe!"))));
    /// ```
    ///
    /// You can use the iterator in a loop:
    ///
    /// ```no_run
    /// # use fastly::Response;
    /// let resp = Response::new()
    ///     .with_header("hello", "world!")
    ///     .with_header("hello", "universe!");
    ///
    /// for (n, v) in resp.get_headers() {
    ///     println!("Header -  {}: {:?}", n, v);
    /// }
    /// ```
    pub fn get_headers(&self) -> impl Iterator<Item = (&HeaderName, &HeaderValue)> {
        self.headers.iter()
    }

    /// Get all values of a header as strings, including invalid characters, or an empty vector if the header is not present.
    ///
    #[doc = include_str!("../../docs/snippets/utf8-replacement.md")]
    ///
    #[doc = include_str!("../../docs/snippets/header-name-argument.md")]
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use std::borrow::Cow;
    /// # use http::header::HeaderValue;
    /// # use fastly::Response;
    /// let world_value = HeaderValue::from_bytes(b"\xF0\x90\x80 world!").unwrap();
    /// let universe_value = HeaderValue::from_bytes(b"\xF0\x90\x80 universe!").unwrap();
    /// let resp = Response::new()
    ///     .with_header("hello", world_value)
    ///     .with_header("hello", universe_value);
    /// let values = resp.get_header_all_str_lossy("hello");
    /// assert_eq!(values.len(), 2);
    /// assert!(values.contains(&Cow::from("� world!")));
    /// assert!(values.contains(&Cow::from("� universe!")));
    /// ```
    pub fn get_header_all_str_lossy(&self, name: impl ToHeaderName) -> Vec<Cow<'_, str>> {
        self.get_header_all(name)
            .map(|hdr| String::from_utf8_lossy(hdr.as_bytes()))
            .collect()
    }

    /// Get an iterator of all the values of a header.
    ///
    #[doc = include_str!("../../docs/snippets/header-name-argument.md")]
    ///
    /// # Examples
    ///
    /// You can turn the iterator into collection, like [`Vec`]:
    ///
    /// ```no_run
    /// # use fastly::Response;
    /// # use fastly::http::HeaderValue;
    /// let invalid_utf8 = &"🐈".as_bytes()[0..3];
    /// let resp = Response::new()
    ///     .with_header("hello", "world!")
    ///     .with_header("hello", invalid_utf8);
    ///
    /// let values: Vec<&HeaderValue> = resp.get_header_all("hello").collect();
    /// assert_eq!(values.len(), 2);
    /// assert!(values.contains(&&HeaderValue::from_static("world!")));
    /// assert!(values.contains(&&HeaderValue::from_bytes(invalid_utf8).unwrap()));
    /// ```
    ///
    /// You can use the iterator in a loop:
    ///
    /// ```no_run
    /// # use fastly::Response;
    /// let invalid_utf8 = &"🐈".as_bytes()[0..3];
    /// let resp = Response::new()
    ///     .with_header("hello", "world!")
    ///     .with_header("hello", invalid_utf8);
    ///
    /// for value in resp.get_header_all("hello") {
    ///     if let Ok(s) = value.to_str() {
    ///         println!("hello, {}", s);
    ///     } else {
    ///         println!("hello, invalid UTF-8!");
    ///     }
    /// }
    /// ```
    pub fn get_header_all<'a>(
        &'a self,
        name: impl ToHeaderName,
    ) -> impl Iterator<Item = &'a HeaderValue> {
        self.headers.get_all(name.into_borrowable().as_ref()).iter()
    }

    /// Get all of the response's header names as strings, or an empty vector if no headers are
    /// present.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use fastly::Response;
    /// let resp = Response::new()
    ///     .with_header("hello", "world!")
    ///     .with_header("goodbye", "latency!");
    /// let names = resp.get_header_names_str();
    /// assert_eq!(names.len(), 2);
    /// assert!(names.contains(&"hello"));
    /// assert!(names.contains(&"goodbye"));
    /// ```
    pub fn get_header_names_str(&self) -> Vec<&str> {
        self.get_header_names().map(|n| n.as_str()).collect()
    }

    /// Get an iterator of all the response's header names.
    ///
    /// # Examples
    ///
    /// You can turn the iterator into a collection, like [`Vec`]:
    ///
    /// ```no_run
    /// # use fastly::Response;
    /// # use fastly::http::header::HeaderName;
    /// let resp = Response::new()
    ///     .with_header("hello", "world!")
    ///     .with_header("goodbye", "latency!");
    ///
    /// let values: Vec<&HeaderName> = resp.get_header_names().collect();
    /// assert_eq!(values.len(), 2);
    /// assert!(values.contains(&&HeaderName::from_static("hello")));
    /// assert!(values.contains(&&HeaderName::from_static("goodbye")));
    /// ```
    ///
    /// You can use the iterator in a loop:
    ///
    /// ```no_run
    /// # use fastly::Response;
    /// let resp = Response::new()
    ///     .with_header("hello", "world!")
    ///     .with_header("goodbye", "latency!");
    ///
    /// for name in resp.get_header_names() {
    ///     println!("saw header: {:?}", name);
    /// }
    /// ```
    pub fn get_header_names(&self) -> impl Iterator<Item = &HeaderName> {
        self.headers.keys()
    }

    /// Set a response header to the given value, discarding any previous values for the given
    /// header name.
    ///
    #[doc = include_str!("../../docs/snippets/header-name-value-argument.md")]
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use fastly::Response;
    /// let mut resp = Response::new();
    ///
    /// resp.set_header("hello", "world!");
    /// assert_eq!(resp.get_header_str("hello"), Some("world!"));
    ///
    /// resp.set_header("hello", "universe!");
    ///
    /// let values = resp.get_header_all_str("hello");
    /// assert_eq!(values.len(), 1);
    /// assert!(!values.contains(&"world!"));
    /// assert!(values.contains(&"universe!"));
    /// ```
    pub fn set_header(&mut self, name: impl ToHeaderName, value: impl ToHeaderValue) {
        self.headers.insert(name.into_owned(), value.into_owned());
    }

    /// Add a response header with given value.
    ///
    /// Unlike [`set_header()`][`Self::set_header()`], this does not discard existing values for the
    /// same header name.
    ///
    #[doc = include_str!("../../docs/snippets/header-name-value-argument.md")]
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use fastly::Response;
    /// let mut resp = Response::new();
    ///
    /// resp.set_header("hello", "world!");
    /// assert_eq!(resp.get_header_str("hello"), Some("world!"));
    ///
    /// resp.append_header("hello", "universe!");
    ///
    /// let values = resp.get_header_all_str("hello");
    /// assert_eq!(values.len(), 2);
    /// assert!(values.contains(&"world!"));
    /// assert!(values.contains(&"universe!"));
    /// ```
    pub fn append_header(&mut self, name: impl ToHeaderName, value: impl ToHeaderValue) {
        self.headers
            .append(name.into_borrowable().as_ref(), value.into_owned());
    }

    /// Remove all response headers of the given name, and return one of the removed header values
    /// if any were present.
    ///
    /// If the header has multiple values, one is returned arbitrarily. To get all of the removed
    /// header values, or to get a specific value, use
    /// [`get_header_all()`][`Self::get_header_all()`].
    ///
    #[doc = include_str!("../../docs/snippets/header-name-argument.md")]
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use fastly::Response;
    /// # use fastly::http::HeaderValue;
    /// let mut resp = Response::new().with_header("hello", "world!");
    /// assert_eq!(resp.get_header_str("hello"), Some("world!"));
    /// assert_eq!(resp.remove_header("hello"), Some(HeaderValue::from_static("world!")));
    /// assert!(resp.remove_header("not-present").is_none());
    /// ```
    pub fn remove_header(&mut self, name: impl ToHeaderName) -> Option<HeaderValue> {
        self.headers.remove(name.into_borrowable().as_ref())
    }

    /// Remove all response headers of the given name, and return one of the removed header values
    /// as a string if any were present.
    ///
    #[doc = include_str!("../../docs/snippets/removes-one-header.md")]
    ///
    #[doc = include_str!("../../docs/snippets/header-name-argument.md")]
    ///
    /// # Panics
    ///
    #[doc = include_str!("../../docs/snippets/panics-reqresp-remove-header-utf8.md")]
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use fastly::Response;
    /// let mut resp = Response::new().with_header("hello", "world!");
    /// assert_eq!(resp.get_header_str("hello"), Some("world!"));
    /// assert_eq!(resp.remove_header_str("hello"), Some("world!".to_string()));
    /// assert!(resp.remove_header_str("not-present").is_none());
    /// ```
    pub fn remove_header_str(&mut self, name: impl ToHeaderName) -> Option<String> {
        let name = name.into_borrowable();
        if let Some(hdr) = self.remove_header(name.as_ref()) {
            Some(
                hdr.to_str()
                    .map(|s| s.to_owned())
                    .unwrap_or_else(|_| panic!("non-UTF-8 HTTP header value for header: {}", name)),
            )
        } else {
            None
        }
    }

    /// Remove all response headers of the given name, and return one of the removed header values
    /// as a string, including invalid characters, if any were present.
    ///
    #[doc = include_str!("../../docs/snippets/utf8-replacement.md")]
    ///
    #[doc = include_str!("../../docs/snippets/removes-one-header.md")]
    ///
    #[doc = include_str!("../../docs/snippets/header-name-argument.md")]
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use fastly::Response;
    /// # use http::header::HeaderValue;
    /// # use std::borrow::Cow;
    /// let header_value = HeaderValue::from_bytes(b"\xF0\x90\x80 world!").unwrap();
    /// let mut resp = Response::new().with_header("hello", header_value);
    /// assert_eq!(resp.get_header_str_lossy("hello"), Some(Cow::from("� world")));
    /// assert_eq!(resp.remove_header_str_lossy("hello"), Some(String::from("� world")));
    /// assert!(resp.remove_header_str_lossy("not-present").is_none());
    /// ```
    pub fn remove_header_str_lossy(&mut self, name: impl ToHeaderName) -> Option<String> {
        self.remove_header(name)
            .map(|hdr| String::from_utf8_lossy(hdr.as_bytes()).into_owned())
    }

    /// Builder-style equivalent of [`set_status()`][`Self::set_status()`].
    pub fn with_status(mut self, status: impl ToStatusCode) -> Self {
        self.set_status(status);
        self
    }

    /// Get the HTTP status code of the response.
    pub fn get_status(&self) -> StatusCode {
        self.status
    }

    /// Set the HTTP status code of the response.
    ///
    #[doc = include_str!("../../docs/snippets/statuscode-argument.md")]
    ///
    /// # Examples
    ///
    /// Using the constants from [`StatusCode`]:
    ///
    /// ```no_run
    /// # use fastly::Response;
    /// use fastly::http::StatusCode;
    ///
    /// let mut resp = Response::from_body("not found!");
    /// resp.set_status(StatusCode::NOT_FOUND);
    /// resp.send_to_client();
    /// ```
    ///
    /// Using a `u16`:
    ///
    /// ```no_run
    /// # use fastly::Response;
    /// let mut resp = Response::from_body("not found!");
    /// resp.set_status(404);
    /// resp.send_to_client();
    /// ```
    pub fn set_status(&mut self, status: impl ToStatusCode) {
        self.status = status.to_status_code();
    }

    /// Builder-style equivalent of [`set_version()`][`Self::set_version()`].
    pub fn with_version(mut self, version: Version) -> Self {
        self.set_version(version);
        self
    }

    /// Get the HTTP version of this response.
    pub fn get_version(&self) -> Version {
        self.version
    }

    /// Set the HTTP version of this response.
    pub fn set_version(&mut self, version: Version) {
        self.version = version;
    }

    /// Sets how `Content-Length` and `Transfer-Encoding` will be determined when sending this
    /// request.
    ///
    /// See [`FramingHeadersMode`] for details on the options.
    pub fn set_framing_headers_mode(&mut self, mode: FramingHeadersMode) {
        self.framing_headers_mode = mode;
    }

    /// Builder-style equivalent of
    /// [`set_framing_headers_mode()`][`Self::set_framing_headers_mode()`].
    pub fn with_framing_headers_mode(mut self, mode: FramingHeadersMode) -> Self {
        self.set_framing_headers_mode(mode);
        self
    }

    /// Get the name of the [`Backend`] this response came from, or `None` if the response is
    /// synthetic.
    ///
    /// # Examples
    ///
    /// From a backend response:
    ///
    /// ```no_run
    /// # use fastly::Request;
    /// let backend_resp = Request::get("https://example.com/").send("example_backend").unwrap();
    /// assert_eq!(backend_resp.get_backend_name(), Some("example_backend"));
    /// ```
    ///
    /// From a synthetic response:
    ///
    /// ```no_run
    /// # use fastly::Response;
    /// let synthetic_resp = Response::new();
    /// assert!(synthetic_resp.get_backend_name().is_none());
    /// ```
    pub fn get_backend_name(&self) -> Option<&str> {
        self.get_backend().map(|be| be.name())
    }

    /// Get the backend this response came from, or `None` if the response is synthetic.
    ///
    /// # Examples
    ///
    /// From a backend response:
    ///
    /// ```no_run
    /// # use fastly::{Backend, Request};
    /// let backend_resp = Request::get("https://example.com/").send("example_backend").unwrap();
    /// assert_eq!(backend_resp.get_backend(), Some(&Backend::from_name("example_backend").unwrap()));
    /// ```
    ///
    /// From a synthetic response:
    ///
    /// ```no_run
    /// # use fastly::Response;
    /// let synthetic_resp = Response::new();
    /// assert!(synthetic_resp.get_backend().is_none());
    /// ```
    pub fn get_backend(&self) -> Option<&Backend> {
        self.fastly_metadata.as_ref().and_then(|md| md.backend())
    }

    /// Get the request this response came from, or `None` if the response is synthetic.
    ///
    /// Note that the returned request will only have the headers and metadata of the original
    /// request, as the body is consumed when sending the request.
    ///
    /// This method only returns a reference to the backend request. To instead take and return the
    /// owned request (for example, to subsequently send the request again), use
    /// [`take_backend_request()`][`Self::take_backend_request()`].
    ///
    /// # Examples
    ///
    /// From a backend response:
    ///
    /// ```no_run
    /// # use fastly::Request;
    /// let backend_resp = Request::post("https://example.com/")
    ///     .with_body("hello")
    ///     .send("example_backend")
    ///     .unwrap();
    /// let backend_req = backend_resp.get_backend_request().expect("response is not synthetic");
    /// assert_eq!(backend_req.get_url_str(), "https://example.com/");
    /// assert!(!backend_req.has_body());
    /// ```
    ///
    /// From a synthetic response:
    ///
    /// ```no_run
    /// # use fastly::Response;
    /// let synthetic_resp = Response::new();
    /// assert!(synthetic_resp.get_backend_request().is_none());
    /// ```
    pub fn get_backend_request(&self) -> Option<&Request> {
        self.fastly_metadata.as_ref().and_then(|md| md.sent_req())
    }

    /// Take and return the request this response came from, or `None` if the response is synthetic.
    ///
    /// Note that the returned request will only have the headers and metadata of the original
    /// request, as the body is consumed when sending the request.
    ///
    /// # Examples
    ///
    /// From a backend response:
    ///
    /// ```no_run
    /// # use fastly::Request;
    /// let mut backend_resp = Request::post("https://example.com/")
    ///     .with_body("hello")
    ///     .send("example_backend")
    ///     .unwrap();
    /// let backend_req = backend_resp.take_backend_request().expect("response is not synthetic");
    /// assert_eq!(backend_req.get_url_str(), "https://example.com/");
    /// assert!(!backend_req.has_body());
    /// backend_req.with_body("goodbye").send("example_backend").unwrap();
    /// ```
    ///
    /// From a synthetic response:
    ///
    /// ```no_run
    /// # use fastly::Response;
    /// let mut synthetic_resp = Response::new();
    /// assert!(synthetic_resp.take_backend_request().is_none());
    /// ```
    pub fn take_backend_request(&mut self) -> Option<Request> {
        self.fastly_metadata
            .as_mut()
            .and_then(|md| md.take_sent_req())
    }

    pub(crate) fn set_fastly_metadata(&mut self, md: FastlyResponseMetadata) {
        self.fastly_metadata = Some(md);
    }

    /// Begin sending the response to the client.
    ///
    /// This method returns as soon as the response header begins sending to the client, and
    /// transmission of the response will continue in the background.
    ///
    /// Once this method is called, nothing else may be added to the response body. To stream
    /// additional data to a response body after it begins to send, use
    /// [`stream_to_client`][`Self::stream_to_client()`].
    ///
    /// # Panics
    ///
    /// This method panics if another response has already been sent to the client by this method,
    /// by [`stream_to_client()`][`Self::stream_to_client()`], or by the equivalent methods of
    /// [`ResponseHandle`].
    ///
    /// # Examples
    ///
    /// Sending a backend response without modification:
    ///
    /// ```no_run
    /// # use fastly::Request;
    /// Request::get("https://example.com/").send("example_backend").unwrap().send_to_client();
    /// ```
    ///
    /// Removing a header from a backend response before sending to the client:
    ///
    /// ```no_run
    /// # use fastly::Request;
    /// let mut backend_resp = Request::get("https://example.com/").send("example_backend").unwrap();
    /// backend_resp.remove_header("bad-header");
    /// backend_resp.send_to_client();
    /// ```
    ///
    /// Sending a synthetic response:
    ///
    /// ```no_run
    /// # use fastly::Response;
    /// Response::from_body("hello, world!").send_to_client();
    /// ```
    pub fn send_to_client(self) {
        let res = self.send_to_client_impl(false, true);
        debug_assert!(res.is_none());
    }

    /// Deprecated alias of [`Response::send_to_client()`]
    #[deprecated(since = "0.6.0", note = "renamed to `Response::send_to_client()`")]
    pub fn send_downstream(self) {
        self.send_to_client()
    }

    /// Begin sending the response to the client, and return a [`StreamingBody`] that can accept
    /// further data to send.
    ///
    /// This method is most useful for programs that do some sort of processing or inspection of a
    /// potentially-large backend response body. Streaming allows the program to operate on small
    /// parts of the body rather than having to read it all into memory at once.
    ///
    /// This method returns as soon as the response header begins sending to the client, and
    /// transmission of the response will continue in the background.
    ///
    /// Note that the client connection is only closed once the [`StreamingBody`] is dropped. You
    /// can explicitly drop the body once finished to avoid holding the connection open longer than
    /// necessary.
    ///
    /// # Panics
    ///
    /// This method panics if another response has already been sent to the client by this method,
    /// by [`send_to_client()`][`Self::send_to_client()`], or by the equivalent methods of
    /// [`ResponseHandle`].
    ///
    /// # Examples
    ///
    /// Count the number of lines in a UTF-8 backend response body while sending it to the client:
    ///
    /// ```no_run
    /// # use fastly::Request;
    /// use std::io::BufRead;
    ///
    /// let mut backend_resp = Request::get("https://example.com/").send("example_backend").unwrap();
    /// // Take the body so we can iterate through its lines later
    /// let backend_resp_body = backend_resp.take_body();
    /// // Start sending the backend response to the client with a now-empty body
    /// let mut client_body = backend_resp.stream_to_client();
    ///
    /// let mut num_lines = 0;
    /// for line in backend_resp_body.lines() {
    ///     let line = line.unwrap();
    ///     num_lines += 1;
    ///     // Write the line to the streaming client body
    ///     client_body.write_str(&line);
    /// }
    /// // Drop the streaming body to allow the client connection to close
    /// drop(client_body);
    ///
    /// println!("backend response body contained {} lines", num_lines);
    /// ```
    pub fn stream_to_client(self) -> StreamingBody {
        let res = self.send_to_client_impl(true, true);
        // streaming = true means we always get back a `Some`
        res.expect("streaming body is present")
    }

    /// Deprecated alias of [`Response::stream_to_client()`]
    #[deprecated(since = "0.6.0", note = "renamed to `Response::stream_to_client()`")]
    pub fn send_downstream_streaming(self) -> StreamingBody {
        self.stream_to_client()
    }

    /// Send a response to the client.
    ///
    /// This will return a [`StreamingBody`] if and only if `streaming` is true. If a response has
    /// already been sent to the client, and `panic_on_multiple_send` is `true`, this function will
    /// panic.
    ///
    /// This method is public, but hidden from generated documentation in order to support the
    /// implementation of [`panic_with_status()`].
    #[doc(hidden)]
    pub fn send_to_client_impl(
        self,
        streaming: bool,
        panic_on_multiple_send: bool,
    ) -> Option<StreamingBody> {
        assert_single_downstream_response_is_sent(panic_on_multiple_send);

        let (resp_handle, body_handle) = self.into_handles();

        // Send the response to the client using the appropriate method based on the `streaming` flag.
        if streaming {
            Some(resp_handle.stream_to_client(body_handle).into())
        } else {
            resp_handle.send_to_client(body_handle);
            None
        }
    }

    /// Create a [`Response`] from the a [`ResponseHandle`] and a [`BodyHandle`], returning an error
    /// if any [`ResponseLimits`][`crate::limits::ResponseLimits`] are exceeded.
    ///
    /// The extra metadata associated with a backend response is not tracked by the low-level handle
    /// APIs. As a result, methods like [`get_backend()`][`Self::get_backend()`] and
    /// [`get_backend_request()`][`Self::get_backend_request()`] will always return `None` for a
    /// request created from handles.
    pub fn from_handles(
        resp_handle: ResponseHandle,
        body_handle: BodyHandle,
    ) -> Result<Self, BufferSizeError> {
        let mut resp = Response::new()
            .with_status(resp_handle.get_status())
            .with_version(resp_handle.get_version());
        let resp_limits = limits::RESPONSE_LIMITS.read().unwrap();

        for name in resp_handle.get_header_names_impl(
            limits::DEFAULT_MAX_HEADER_NAME_BYTES,
            resp_limits.max_header_name_bytes,
        ) {
            let name = name?;
            for value in resp_handle.get_header_values_impl(
                &name,
                limits::DEFAULT_MAX_HEADER_VALUE_BYTES,
                resp_limits.max_header_value_bytes,
            ) {
                let value = value?;
                resp.append_header(&name, value);
            }
        }

        Ok(resp.with_body(body_handle))
    }

    /// Create a [`ResponseHandle`]/[`BodyHandle`] pair from a [`Response`].
    ///
    /// The extra metadata associated with a backend response is not tracked by the low-level handle
    /// APIs. As a result, converting to handles will cause the backend and request associated with
    /// a backend response to be lost.
    pub fn into_handles(mut self) -> (ResponseHandle, BodyHandle) {
        // Convert to a body handle, or create an empty body handle if none is set.
        let body_handle = if let Some(body) = self.try_take_body() {
            body.into_handle()
        } else {
            BodyHandle::new()
        };

        // Mint a response handle, and set the HTTP status code, version, and headers.
        let mut resp_handle = ResponseHandle::new();
        resp_handle.set_status(self.status);
        resp_handle.set_version(self.version);
        for name in self.headers.keys() {
            resp_handle.set_header_values(name, self.headers.get_all(name));
        }
        resp_handle.set_framing_headers_mode(self.framing_headers_mode);

        (resp_handle, body_handle)
    }
}

/// Anything that we need to make a full roundtrip through the `http` types that doesn't have a more
/// concrete corresponding type.
#[derive(Debug, Default)]
struct FastlyExts {
    fastly_metadata: Option<FastlyResponseMetadata>,
    framing_headers_mode: FramingHeadersMode,
}

impl Into<http::Response<Body>> for Response {
    fn into(self) -> http::Response<Body> {
        let mut resp = http::Response::new(self.body.unwrap_or_else(|| Body::new()));
        resp.extensions_mut().insert(FastlyExts {
            fastly_metadata: self.fastly_metadata,
            framing_headers_mode: self.framing_headers_mode,
        });
        *resp.headers_mut() = self.headers;
        *resp.status_mut() = self.status;
        *resp.version_mut() = self.version;
        resp
    }
}

impl From<http::Response<Body>> for Response {
    fn from(from: http::Response<Body>) -> Self {
        let (mut parts, body) = from.into_parts();
        let fastly_exts: FastlyExts = parts.extensions.remove().unwrap_or_default();
        Response {
            version: parts.version,
            status: parts.status,
            headers: parts.headers,
            body: Some(body),
            fastly_metadata: fastly_exts.fastly_metadata,
            framing_headers_mode: fastly_exts.framing_headers_mode,
        }
    }
}

/// Additional Fastly-specific metadata for responses.
#[derive(Debug)]
pub(crate) struct FastlyResponseMetadata {
    backend: Backend,
    sent_req: Option<Request>,
}

impl Clone for FastlyResponseMetadata {
    fn clone(&self) -> Self {
        Self {
            backend: self.backend.clone(),
            // sent_req never has a body, so it is fine to clone without it
            sent_req: self.sent_req.as_ref().map(Request::clone_without_body),
        }
    }
}

impl FastlyResponseMetadata {
    /// Create a response metadata object, given the request and the backend name.
    pub fn new(backend: Backend, sent_req: Request) -> Self {
        Self {
            backend,
            sent_req: Some(sent_req),
        }
    }

    /// Get a reference to the backend that this response came from.
    pub fn backend(&self) -> Option<&Backend> {
        // ACF 2020-06-17: this is wrapped in an option for future compatibility when we might have
        // `FastlyResponseMetadata`s on responses that didn't come from a backend
        Some(&self.backend)
    }

    /// Get a reference to the original request associated with this response.
    ///
    /// Note that the request's original body has already been sent, so the returned request does
    /// not have a body.
    pub fn sent_req(&self) -> Option<&Request> {
        self.sent_req.as_ref()
    }

    pub(crate) fn take_sent_req(&mut self) -> Option<Request> {
        self.sent_req.take()
    }
}

/// Send a response to the client with the given HTTP status code, and then panic.
///
/// By default, Rust panics will cause a generic `500 Internal Server Error` response to be sent to
/// the client, if a response has not already been sent. This macro allows you to customize the
/// status code, although the response is still generic.
///
/// The syntax is similar to [`panic!()`], but takes an optional first argument that must implement
/// [`ToStatusCode`], such as [`StatusCode`] or [`u16`]. The optional message and format arguments
/// are passed to [`panic!()`] unchanged, and so will be printed to the logging endpoint specified
/// by [`set_panic_endpoint()`][`crate::log::set_panic_endpoint()`].
///
/// # Examples
///
/// ```no_run
/// # use fastly::{Request, panic_with_status};
/// let req = Request::get("https://example.com/bad_path");
/// if req.get_path().starts_with("bad") {
///     panic_with_status!(403, "forbade request to a bad path: {}", req.get_url_str());
/// }
/// ```
#[macro_export]
macro_rules! panic_with_status {
    () => {
        $crate::panic_with_status!($crate::http::StatusCode::INTERNAL_SERVER_ERROR)
    };
    ($status:expr) => {{
        $crate::Response::new().with_status($status).send_to_client_impl(false, false);
        panic!();
    }};
    ($status:expr, $($arg:tt)*) => {{
        $crate::Response::new().with_status($status).send_to_client_impl(false, false);
        panic!($($arg)*);
    }};
}

/// Make sure a single response is sent to the downstream request
#[doc(hidden)]
pub(crate) fn assert_single_downstream_response_is_sent(panic_on_multiple_send: bool) {
    use std::sync::atomic::{AtomicBool, Ordering};

    /// A flag representing whether or not we have sent a response to the client.
    static SENT: AtomicBool = AtomicBool::new(false);

    // Set our sent flag, and panic if we have already sent a response.
    if SENT.swap(true, Ordering::SeqCst) && panic_on_multiple_send {
        panic!("cannot send more than one client response per execution");
    }
}