tii 0.0.6

A Low-Latency Web Server.
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
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
//! Provides functionality for handling HTTP responses.

use crate::http::cookie::SetCookie;
use crate::http::headers::{Headers, HttpHeader, HttpHeaderName};
use crate::http::status::StatusCode;

use crate::http::method::HttpMethod;
use crate::http::request::HttpVersion;
use crate::http::response_body::ResponseBody;
use crate::stream::ConnectionStreamWrite;
use crate::tii_error::{TiiResult, UserError};
use crate::{EntitySerializer, MimeTypeWithCharset};
use std::fmt::Debug;
use std::io::{Read, Seek};
use std::{io, mem};

/// Represents a response from the server.
/// Implements `Into<Vec<u8>>` so can be serialised into bytes to transmit.
///
/// ## Simple Creation
/// ```
/// use tii::MimeType;
/// use tii::StatusCode;
/// tii::Response::ok("Success", MimeType::TextPlain);
/// tii::Response::new(StatusCode::NotFound);
/// ```
///
/// ## Advanced Creation
/// ```
/// tii::Response::new(tii::StatusCode::OK)
///     .with_body_slice(b"Success")
///     .with_header(tii::HttpHeaderName::ContentType, "text/plain");
/// ```
#[derive(Debug)]
pub struct Response {
  /// The status code of the response, for example 200 OK.
  pub status_code: StatusCode,
  /// A list of the headers included in the response.
  pub(crate) headers: Headers,
  /// The body of the response.
  pub body: Option<ResponseBody>,

  /// If this field is set to true then tii will not send the body over the wire.
  /// The response headers that would describe the omitted body will still be sent.
  /// This should only be set to true as a response to HTTP HEAD requests.
  ///
  /// IMPLEMENTATION DETAIL: Setting this value to true forces 'Connection: Close'.
  /// In case of HTTP 0.9 this value is completely ignored and the body is still sent.
  ///
  /// Use this field only if absolutely necessary!
  ///
  /// How HTTP clients will expect HEAD requests in regard to response body and Content-Lengths field values is highly dependent on the client
  /// Every client seems to expect something else. Some clients prefer a response that simply has `Response::without_body`,
  /// this however will also remove the Content-Length header! Other clients want the Content-Length header but
  /// no actual body. The forcing of 'Connection: Close' is a safety measure because otherwise clients that do
  /// actually want to read the body will just hang until timeout waiting for the body which
  /// we will never send.
  pub omit_body: bool,
}

impl Response {
  /// Creates a new response object with the given status code.
  /// Automatically sets the HTTP version to "HTTP/1.1", sets no headers, and creates an empty body.
  pub fn new(status_code: impl Into<StatusCode>) -> Self {
    let status_code = status_code.into();
    Self { status_code, headers: Headers::new(), body: None, omit_body: false }
  }

  /// HTTP 200 OK with body.
  pub fn ok(bytes: impl Into<ResponseBody>, mime: impl Into<MimeTypeWithCharset>) -> Response {
    Self::new(StatusCode::OK)
      .with_body(bytes.into())
      .with_header_unchecked("Content-Type", mime.into())
  }

  /// HTTP 200 OK with entity body.
  pub fn ok_entity<T: Debug + Send + 'static>(
    entity: T,
    serializer: impl EntitySerializer<T>,
    mime: impl Into<MimeTypeWithCharset>,
  ) -> Response {
    Self::ok(ResponseBody::from_entity(entity, serializer), mime)
  }

  /// HTTP 200 OK with body.
  ///
  /// # Errors
  /// Propagated from try_into call of bytes argument.
  pub fn try_ok<E>(
    bytes: impl TryInto<ResponseBody, Error = E>,
    mime: impl Into<MimeTypeWithCharset>,
  ) -> Result<Response, E> {
    Ok(Self::ok(bytes.try_into()?, mime))
  }

  /// HTTP 201 Created with body.
  pub fn created(bytes: impl Into<ResponseBody>, mime: impl Into<MimeTypeWithCharset>) -> Response {
    Self::new(StatusCode::Created)
      .with_body(bytes.into())
      .with_header_unchecked("Content-Type", mime.into())
  }

  /// HTTP 201 Created with entity body.
  pub fn created_entity<T: Debug + Send + 'static>(
    entity: T,
    serializer: impl EntitySerializer<T>,
    mime: impl Into<MimeTypeWithCharset>,
  ) -> Response {
    Self::created(ResponseBody::from_entity(entity, serializer), mime)
  }

  /// HTTP 202 Accepted with body.
  pub fn accepted(
    bytes: impl Into<ResponseBody>,
    mime: impl Into<MimeTypeWithCharset>,
  ) -> Response {
    Self::new(StatusCode::Created)
      .with_body(bytes.into())
      .with_header_unchecked("Content-Type", mime.into())
  }

  /// HTTP 203 Non-Authoritative Information with body
  pub fn non_authoritative(
    bytes: impl Into<ResponseBody>,
    mime: impl Into<MimeTypeWithCharset>,
  ) -> Response {
    Self::new(StatusCode::NonAuthoritative)
      .with_body(bytes.into())
      .with_header_unchecked("Content-Type", mime.into())
  }

  /// HTTP 204 No Content
  pub fn no_content() -> Response {
    Self::new(StatusCode::NoContent)
  }

  /// HTTP 205 Reset Content
  pub fn reset_content() -> Response {
    Self::new(StatusCode::ResetContent)
  }

  /// HTTP 206 Partial Content
  /// Note: Content-Range header must still be set by the caller. TODO
  pub fn partial_content(
    body: impl Into<ResponseBody>,
    mime: impl Into<MimeTypeWithCharset>,
  ) -> Response {
    Self::new(StatusCode::PartialContent)
      .with_body(body.into())
      .with_header_unchecked(HttpHeaderName::ContentType, mime.into())
  }

  /// HTTP 300 Multiple Choices
  pub fn multiple_choices(
    body: impl Into<ResponseBody>,
    mime: impl Into<MimeTypeWithCharset>,
  ) -> Response {
    Self::new(StatusCode::MultipleChoices)
      .with_body(body.into())
      .with_header_unchecked(HttpHeaderName::ContentType, mime.into())
  }

  /// HTTP 300 Multiple Choices without body
  pub fn multiple_choices_no_body() -> Response {
    Self::new(StatusCode::MultipleChoices)
  }

  /// HTTP 301 Moved Permanently
  pub fn moved_permanently(
    location: impl ToString,
    body: impl Into<ResponseBody>,
    mime: impl Into<MimeTypeWithCharset>,
  ) -> Response {
    Self::new(StatusCode::MovedPermanently)
      .with_header_unchecked(HttpHeaderName::Location, location)
      .with_header_unchecked(HttpHeaderName::ContentType, mime.into())
      .with_body(body.into())
  }

  /// HTTP 301 Moved Permanently without body
  pub fn moved_permanently_no_body(location: impl ToString) -> Response {
    Self::new(StatusCode::MovedPermanently)
      .with_header_unchecked(HttpHeaderName::Location, location)
  }

  /// HTTP 302 Found
  pub fn found(
    location: impl ToString,
    body: impl Into<ResponseBody>,
    mime: impl Into<MimeTypeWithCharset>,
  ) -> Response {
    Self::new(StatusCode::Found)
      .with_header_unchecked(HttpHeaderName::Location, location)
      .with_header_unchecked(HttpHeaderName::ContentType, mime.into())
      .with_body(body.into())
  }

  /// HTTP 302 Found without body
  pub fn found_no_body(location: impl ToString) -> Response {
    Self::new(StatusCode::Found).with_header_unchecked(HttpHeaderName::Location, location)
  }

  /// HTTP 303 See Other
  pub fn see_other(
    location: impl ToString,
    body: impl Into<ResponseBody>,
    mime: impl Into<MimeTypeWithCharset>,
  ) -> Response {
    Self::new(StatusCode::SeeOther)
      .with_header_unchecked(HttpHeaderName::Location, location)
      .with_header_unchecked(HttpHeaderName::ContentType, mime.into())
      .with_body(body.into())
  }

  /// HTTP 303 See Other without body
  pub fn see_other_no_body(location: impl ToString) -> Response {
    Self::new(StatusCode::SeeOther).with_header_unchecked(HttpHeaderName::Location, location)
  }

  /// HTTP 304 Not modified.
  pub fn not_modified() -> Response {
    Self::new(StatusCode::NotModified)
  }

  /// HTTP 307 Temporary Redirect
  pub fn temporary_redirect(
    location: impl ToString,
    body: impl Into<ResponseBody>,
    mime: impl Into<MimeTypeWithCharset>,
  ) -> Response {
    Self::new(StatusCode::TemporaryRedirect)
      .with_header_unchecked(HttpHeaderName::Location, location)
      .with_header_unchecked(HttpHeaderName::ContentType, mime.into())
      .with_body(body.into())
  }

  /// HTTP 307 Temporary Redirect without body
  pub fn temporary_redirect_no_body(location: impl ToString) -> Response {
    Self::new(StatusCode::TemporaryRedirect)
      .with_header_unchecked(HttpHeaderName::Location, location)
  }

  /// HTTP 308 Permanent Redirect
  pub fn permanent_redirect(
    location: impl ToString,
    body: impl Into<ResponseBody>,
    mime: impl Into<MimeTypeWithCharset>,
  ) -> Response {
    Self::new(StatusCode::PermanentRedirect)
      .with_body(body.into())
      .with_header_unchecked(HttpHeaderName::Location, location)
      .with_header_unchecked(HttpHeaderName::ContentType, mime.into())
  }

  /// HTTP 308 Permanent Redirect without body
  pub fn permanent_redirect_no_body(location: impl ToString) -> Response {
    Self::new(StatusCode::PermanentRedirect)
      .with_header_unchecked(HttpHeaderName::Location, location)
  }

  /// HTTP 400 Bad Request
  pub fn bad_request(
    body: impl Into<ResponseBody>,
    mime: impl Into<MimeTypeWithCharset>,
  ) -> Response {
    Self::new(StatusCode::BadRequest)
      .with_body(body.into())
      .with_header_unchecked(HttpHeaderName::ContentType, mime.into())
  }

  /// HTTP 400 Bad Request without body
  pub fn bad_request_no_body() -> Response {
    Self::new(StatusCode::BadRequest)
  }

  /// HTTP 401 Unauthorized
  pub fn unauthorized() -> Response {
    Self::new(StatusCode::Unauthorized)
  }

  /// HTTP 402 Payment Required with body
  pub fn payment_required(
    body: impl Into<ResponseBody>,
    mime: impl Into<MimeTypeWithCharset>,
  ) -> Response {
    Self::new(StatusCode::PaymentRequired)
      .with_body(body.into())
      .with_header_unchecked(HttpHeaderName::ContentType, mime.into())
  }

  /// HTTP 402 Payment Required without body
  pub fn payment_required_no_body() -> Response {
    Self::new(StatusCode::PaymentRequired)
  }

  /// HTTP 403 Forbidden
  pub fn forbidden(
    body: impl Into<ResponseBody>,
    mime: impl Into<MimeTypeWithCharset>,
  ) -> Response {
    Self::new(StatusCode::Forbidden)
      .with_body(body.into())
      .with_header_unchecked(HttpHeaderName::ContentType, mime.into())
  }

  /// HTTP 403 Forbidden
  pub fn forbidden_no_body() -> Response {
    Self::new(StatusCode::Forbidden)
  }

  /// HTTP 404 Not Found with body
  pub fn not_found(body: impl Into<ResponseBody>, mime: impl Into<MimeTypeWithCharset>) -> Self {
    Self::new(StatusCode::NotFound)
      .with_body(body.into())
      .with_header_unchecked(HttpHeaderName::ContentType, mime.into())
  }

  /// HTTP 404 Not Found without body
  pub fn not_found_no_body() -> Self {
    Self::new(StatusCode::NotFound)
  }

  /// HTTP 405 Method Not Allowed
  pub fn method_not_allowed(allowed_methods: &[HttpMethod]) -> Self {
    if allowed_methods.is_empty() {
      return Self::new(StatusCode::MethodNotAllowed);
    }

    let mut buf = String::new();
    for method in allowed_methods {
      if !buf.is_empty() {
        buf += ", ";
      }
      buf += method.as_str();
    }

    Self::new(StatusCode::MethodNotAllowed)
      .with_header_unchecked(HttpHeaderName::Allow, buf.as_str())
  }

  /// HTTP 406 Not Acceptable
  pub fn not_acceptable(
    body: impl Into<ResponseBody>,
    mime: impl Into<MimeTypeWithCharset>,
  ) -> Self {
    Self::new(StatusCode::NotAcceptable)
      .with_body(body.into())
      .with_header_unchecked(HttpHeaderName::ContentType, mime.into())
  }

  /// HTTP 406 Not Acceptable without body
  pub fn not_acceptable_no_body() -> Self {
    Self::new(StatusCode::NotAcceptable)
  }

  /// HTTP 407 Proxy Authentication Required
  pub fn proxy_authentication_required(authenticate: impl ToString) -> Self {
    Self::new(StatusCode::ProxyAuthenticationRequired)
      .with_header_unchecked(HttpHeaderName::ProxyAuthenticate, authenticate)
  }

  /// HTTP 408 Request Timeout
  pub fn request_timeout() -> Self {
    Self::new(StatusCode::RequestTimeout)
  }

  /// HTTP 409 Conflict
  pub fn conflict(body: impl Into<ResponseBody>, mime: impl Into<MimeTypeWithCharset>) -> Self {
    Self::new(StatusCode::Conflict)
      .with_body(body.into())
      .with_header_unchecked(HttpHeaderName::ContentType, mime.into())
  }

  /// HTTP 409 Conflict without body
  pub fn conflict_no_body() -> Self {
    Self::new(StatusCode::Conflict)
  }

  /// HTTP 410 Gone
  pub fn gone(body: impl Into<ResponseBody>, mime: impl Into<MimeTypeWithCharset>) -> Self {
    Self::new(StatusCode::Gone)
      .with_body(body.into())
      .with_header_unchecked(HttpHeaderName::ContentType, mime.into())
  }

  /// HTTP 410 Gone
  pub fn gone_no_body() -> Self {
    Self::new(StatusCode::Gone)
  }

  /// HTTP 411 Length Required
  pub fn length_required(
    body: impl Into<ResponseBody>,
    mime: impl Into<MimeTypeWithCharset>,
  ) -> Self {
    Self::new(StatusCode::LengthRequired)
      .with_body(body.into())
      .with_header_unchecked(HttpHeaderName::ContentType, mime.into())
  }

  /// HTTP 411 Length Required without body
  pub fn length_required_no_body() -> Self {
    Self::new(StatusCode::LengthRequired)
  }

  /// HTTP 412 Precondition Failed
  pub fn precondition_failed() -> Self {
    Self::new(StatusCode::PreconditionFailed)
  }

  /// HTTP 413 Content Too Large
  pub fn content_too_large(
    body: impl Into<ResponseBody>,
    mime: impl Into<MimeTypeWithCharset>,
  ) -> Self {
    Self::new(StatusCode::ContentTooLarge)
      .with_body(body.into())
      .with_header_unchecked(HttpHeaderName::ContentType, mime.into())
  }

  /// HTTP 413 Content Too Large without body
  pub fn content_too_large_no_body() -> Self {
    Self::new(StatusCode::ContentTooLarge)
  }

  /// HTTP 415 Unsupported Media Type with body
  pub fn unsupported_media_type(
    body: impl Into<ResponseBody>,
    mime: impl Into<MimeTypeWithCharset>,
  ) -> Response {
    Self::new(StatusCode::UnsupportedMediaType)
      .with_body(body.into())
      .with_header_unchecked(HttpHeaderName::ContentType, mime.into())
  }

  /// HTTP 415 Unsupported Media Type without body
  pub fn unsupported_media_type_no_body() -> Response {
    Self::new(StatusCode::UnsupportedMediaType)
  }

  /// HTTP 500 Internal Server Error with a body
  ///
  /// INFO: IT IS USUALLY A BAD IDEA TO HAND OUT A RESPONSE BODY TO A 500 RESPONSE
  /// ESPECIALLY IF YOUR APPLICATION UNDERGOES ANY SORT OF PEN TESTING.
  /// PEN TESTERS WILL ALWAYS MARK IT IN THEIR "FINDINGS",
  /// EVEN WHEN IT MAKES NO SENSE TO DO SO.
  /// USE THIS METHOD WITH CARE.
  ///
  pub fn internal_server_error(
    body: impl Into<ResponseBody>,
    mime: impl Into<MimeTypeWithCharset>,
  ) -> Response {
    Self::new(StatusCode::InternalServerError)
      .with_body(body.into())
      .with_header_unchecked(HttpHeaderName::ContentType, mime.into())
  }

  /// HTTP 500 Internal Server Error without body
  pub fn internal_server_error_no_body() -> Response {
    Self::new(StatusCode::InternalServerError)
  }

  ///Removes the body from the response
  pub fn without_body(mut self) -> Self {
    self.body = None;
    self
  }

  ///Set the body to use with the response
  pub fn with_body(mut self, body: impl Into<ResponseBody>) -> Self {
    self.body = Some(body.into());
    self
  }

  /// Use the string body as request body
  pub fn with_body_string<T: AsRef<str>>(mut self, body: T) -> Self {
    self.body = Some(ResponseBody::from_string(body.as_ref().to_string()));
    self
  }

  /// Use the binary body as request body
  pub fn with_body_vec(mut self, body: Vec<u8>) -> Self {
    self.body = Some(ResponseBody::from_data(body));
    self
  }

  /// Use the binary body as request body
  pub fn with_body_slice<T: AsRef<[u8]>>(mut self, body: T) -> Self {
    self.body = Some(ResponseBody::from_slice(&body));
    self
  }

  /// Use the file (or something file like) as request body
  /// Note: this call fetches the file size which must not change afterward.
  /// This call uses seek to move the file pointer. Any seeking done prior to this call is ignored.
  /// The actual body will always contain the entire "file"
  pub fn with_body_file<T: Read + Seek + Send + 'static>(mut self, body: T) -> io::Result<Self> {
    self.body = Some(ResponseBody::from_file(body)?);
    Ok(self)
  }

  /// Adds the given header to the response.
  /// Returns itself for use in a builder pattern.
  pub fn with_header(mut self, header: impl AsRef<str>, value: impl ToString) -> TiiResult<Self> {
    self.add_header(header, value)?;
    Ok(self)
  }

  /// Internal add header where the entire state of the request obj is known.
  fn with_header_unchecked(mut self, header: impl AsRef<str>, value: impl ToString) -> Self {
    self.headers.push(HttpHeader::new(header, value.to_string()));
    self
  }

  /// Returns the status code and reason phrase of this request.
  pub fn get_status_code(&self) -> &StatusCode {
    &self.status_code
  }

  /// Returns the number value of the status code
  pub fn get_status_code_number(&self) -> u16 {
    self.status_code.code()
  }

  /// Sets the status code and reason phrase of this request.
  pub fn set_status_code(&mut self, status_code: StatusCode) {
    self.status_code = status_code;
  }

  /// Adds the header to the Response.
  pub fn add_header(&mut self, hdr: impl AsRef<str>, value: impl ToString) -> TiiResult<()> {
    match &hdr.as_ref().into() {
      HttpHeaderName::ContentLength => {
        UserError::ImmutableResponseHeaderModified(HttpHeaderName::ContentLength).into()
      }
      HttpHeaderName::TransferEncoding => {
        UserError::ImmutableResponseHeaderModified(HttpHeaderName::TransferEncoding).into()
      }
      HttpHeaderName::Trailer => {
        UserError::ImmutableResponseHeaderModified(HttpHeaderName::Trailer).into()
      }
      hdr => {
        self.headers.add(hdr, value);
        Ok(())
      }
    }
  }

  /// Replace all header values in the Response
  pub fn set_header(&mut self, header: impl AsRef<str>, value: impl ToString) -> TiiResult<()> {
    match &header.as_ref().into() {
      HttpHeaderName::ContentLength => {
        UserError::ImmutableResponseHeaderModified(HttpHeaderName::ContentLength).into()
      }
      HttpHeaderName::TransferEncoding => {
        UserError::ImmutableResponseHeaderModified(HttpHeaderName::TransferEncoding).into()
      }
      HttpHeaderName::Trailer => {
        UserError::ImmutableResponseHeaderModified(HttpHeaderName::Trailer).into()
      }
      hdr => {
        self.headers.set(hdr, value);
        Ok(())
      }
    }
  }

  /// remove all values for a given header.
  pub fn remove_header(&mut self, header: impl AsRef<str>) {
    self.headers.remove(header);
  }

  /// Returns an iterator over all headers.
  pub fn get_all_headers(&self) -> impl Iterator<Item = &HttpHeader> {
    self.headers.iter()
  }

  /// Returns the first header or None
  pub fn get_header(&self, name: impl AsRef<str>) -> Option<&str> {
    self.headers.get(name)
  }

  /// Returns the all header values of empty Vec.
  pub fn get_headers(&self, name: impl AsRef<str>) -> Vec<&str> {
    self.headers.get_all(name)
  }

  /// Adds the given cookie to the response in the `Set-Cookie` header.
  /// Returns itself for use in a builder pattern.
  pub fn with_cookie(mut self, cookie: SetCookie) -> Self {
    self.headers.push(cookie.into());
    self
  }

  /// Sets the body and returns the previous body.
  pub fn set_body(&mut self, body: Option<ResponseBody>) -> Option<ResponseBody> {
    mem::replace(&mut self.body, body)
  }

  /// Returns a reference that can be used to inspect the body.
  /// To actually consume the body call `set_body(None)`.
  pub fn get_body(&self) -> Option<&ResponseBody> {
    self.body.as_ref()
  }

  /// Returns a mutable reference that can be used to inspect the body.
  /// To actually consume the body call `set_body(None)`.
  pub fn get_body_mut(&mut self) -> Option<&mut ResponseBody> {
    self.body.as_mut()
  }

  ///
  /// Write the response to a streaming output. This consumes the response object.
  /// # Parameters
  /// `request_id` for logging purposes only
  /// `version` http version of the response
  /// `destination` the stream to write to.
  ///
  pub fn write_to<T: ConnectionStreamWrite + ?Sized>(
    mut self,
    request_id: u128,
    version: HttpVersion,
    destination: &T,
  ) -> TiiResult<()> {
    if let Some(body) = self.set_body(None) {
      let mime = if let Some(mime) = self.get_header(HttpHeaderName::ContentType) {
        MimeTypeWithCharset::parse_from_content_type_header(mime)
          .unwrap_or(MimeTypeWithCharset::APPLICATION_OCTET_STREAM)
      } else {
        MimeTypeWithCharset::APPLICATION_OCTET_STREAM
      };

      self.set_body(Some(body.serialize_entity(&mime)?));
    }

    if version == HttpVersion::Http09 {
      if let Some(body) = self.body {
        body.write_to_http(request_id, destination)?;
        destination.flush()?;
      }

      return Ok(());
    }

    destination.write_all(version.as_net_str().as_bytes())?;
    destination.write_all(b" ")?;
    destination.write_all(self.status_code.code_as_utf())?;
    destination.write_all(b" ")?;
    destination.write_all(self.status_code.status_line().as_bytes())?;

    for header in self.headers.iter() {
      // These headers shouldn't be addable to the response.
      if header.name == HttpHeaderName::ContentLength {
        crate::util::unreachable();
      }

      if header.name == HttpHeaderName::TransferEncoding {
        crate::util::unreachable();
      }

      destination.write_all(b"\r\n")?;
      destination.write_all(header.name.to_str().as_bytes())?;
      destination.write_all(b": ")?;
      destination.write_all(header.value.as_bytes())?;
    }

    if let Some(body) = self.body {
      if body.is_chunked() {
        destination.write_all(b"\r\nTransfer-Encoding: chunked\r\n")?;
        if let Some(enc) = body.get_content_encoding() {
          if self.headers.get(HttpHeaderName::ContentEncoding).is_none() {
            destination.write_all(b"Content-Encoding: ")?;
            destination.write_all(enc.as_bytes())?;
            destination.write_all(b"\r\n")?;
          }
        }
        destination.write_all(b"\r\n")?;
        if !self.omit_body {
          body.write_to_http(request_id, destination)?;
        }
        destination.flush()?;
        return Ok(());
      }

      destination.write_all(b"\r\n")?;

      if let Some(len) = body.content_length() {
        destination.write(format!("Content-Length: {len}\r\n").as_bytes())?;
      }

      if let Some(enc) = body.get_content_encoding() {
        if self.headers.get(HttpHeaderName::ContentEncoding).is_none() {
          destination.write_all(b"Content-Encoding: ")?;
          destination.write_all(enc.as_bytes())?;
          destination.write_all(b"\r\n")?;
        }
      }

      destination.write_all(b"\r\n")?;

      if !self.omit_body {
        body.write_to_http(request_id, destination)?;
      }
      destination.flush()?;
      return Ok(());
    }

    destination.write_all(b"\r\nContent-Length: 0\r\n\r\n")?;
    destination.flush()?;
    Ok(())
  }
}