volga 0.8.9

Easy & Fast Web Framework for Rust
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
713
714
715
716
717
718
719
720
721
722
723
//! HTTP response utilities

use crate::error::Error;
use crate::http::{Extensions, StatusCode, Version, body::HttpBody};

use hyper::{
    Response,
    body::{Body, SizeHint},
    header::{HeaderMap, HeaderName, HeaderValue},
    http::response::Parts,
};

use crate::headers::{FromHeaders, Header};

pub use builder::HttpResponseBuilder;

pub mod builder;
pub mod file;
#[cfg(feature = "middleware")]
pub mod filter_result;
pub mod form;
pub mod html;
pub mod into_response;
pub mod macros;
pub mod ok;
pub mod redirect;
pub mod sse;
pub mod status;
pub mod stream;

/// Represents an HTTP response
///
/// See [`Response`]
pub struct HttpResponse {
    inner: Response<HttpBody>,
}

impl std::fmt::Debug for HttpResponse {
    #[inline]
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("HttpResponse(..)")
    }
}

/// Represents a result of HTTP request that could be
/// either [`HttpResponse`] or [`Error`]
pub type HttpResult = Result<HttpResponse, Error>;

impl From<HttpResponse> for Response<HttpBody> {
    #[inline]
    fn from(resp: HttpResponse) -> Self {
        resp.into_inner()
    }
}

impl HttpResponse {
    /// Creates a new [`HttpResponseBuilder`] with default settings.
    ///
    /// By default:
    /// - status is set to `200 OK`
    /// - no headers are set
    #[inline]
    pub fn builder() -> HttpResponseBuilder {
        HttpResponseBuilder::new()
    }

    /// Returns a reference to the associated HTTP header map.
    ///
    /// # Example
    /// ```no_run
    /// use volga::{App, HttpRequest};
    ///
    /// let mut app = App::new();
    ///
    /// app.map_get("/", |req: HttpRequest| async move {
    ///     assert!(req.headers().is_empty());
    /// });
    /// ```
    #[inline]
    pub fn headers(&self) -> &HeaderMap {
        self.inner.headers()
    }

    /// Returns a mutable reference to the associated extensions.
    #[inline]
    #[allow(unused)]
    pub(crate) fn headers_mut(&mut self) -> &mut HeaderMap {
        self.inner.headers_mut()
    }

    /// Returns a reference to the associated HTTP method.
    ///
    /// # Example
    /// ```no_run
    /// use volga::{App, HttpRequest, http::Method};
    ///
    /// let mut app = App::new();
    ///
    /// app.map_get("/", |req: HttpRequest| async move {
    ///     assert_eq!(*req.method(), Method::GET);
    /// });
    /// ```
    #[inline]
    pub fn status(&self) -> StatusCode {
        self.inner.status()
    }

    /// Represents a version of the HTTP spec.
    #[inline]
    pub fn version(&self) -> Version {
        self.inner.version()
    }

    /// Returns a reference to the associated extensions.
    #[inline]
    #[allow(unused)]
    pub(crate) fn extensions(&self) -> &Extensions {
        self.inner.extensions()
    }

    /// Returns a mutable reference to the associated extensions.
    #[inline]
    #[allow(unused)]
    pub(crate) fn extensions_mut(&mut self) -> &mut Extensions {
        self.inner.extensions_mut()
    }

    /// Returns a reference to the associated HTTP body.
    #[inline]
    pub fn body(&self) -> &HttpBody {
        self.inner.body()
    }

    /// Returns the bounds on the remaining length of the stream.
    ///
    /// When the exact remaining length of the stream is known,
    /// the upper bound will be set and will equal the lower bound.
    #[inline]
    pub fn size_hint(&self) -> SizeHint {
        self.inner.size_hint()
    }

    /// Returns a typed HTTP header value
    #[inline]
    pub fn get_header<T: FromHeaders>(&self) -> Option<Header<T>> {
        self.headers().get(T::NAME).map(Header::from_ref)
    }

    /// Returns a view of all values associated with this HTTP header.
    #[inline]
    pub fn get_all_headers<T: FromHeaders>(&self) -> impl Iterator<Item = Header<T>> {
        self.headers().get_all(T::NAME).iter().map(Header::from_ref)
    }

    /// Inserts the header into the response, replacing any existing values
    /// with the same header name.
    ///
    /// This method always overwrites previous values.
    #[inline]
    pub fn insert_header<T>(&mut self, header: Header<T>) -> Header<T>
    where
        T: FromHeaders,
    {
        self.inner
            .headers_mut()
            .insert(header.name(), header.value().clone());
        header
    }

    /// Attempts to insert the header into the response, replacing any existing
    /// values with the same header name.
    ///
    /// Returns an error if the header cannot be constructed.
    #[inline]
    pub fn try_insert_header<T>(
        &mut self,
        header: impl TryInto<Header<T>, Error = Error>,
    ) -> Result<Header<T>, Error>
    where
        T: FromHeaders,
    {
        let header = header.try_into()?;
        Ok(self.insert_header(header))
    }

    /// Inserts the raw header into the response, replacing any existing values
    /// with the same header name.
    #[inline]
    pub fn insert_raw_header(&mut self, name: HeaderName, value: HeaderValue) {
        self.inner.headers_mut().insert(name, value);
    }

    /// Attempts to inserts the raw header into the response, replacing any existing values
    /// with the same header name.
    #[inline]
    pub fn try_insert_raw_header(&mut self, name: &str, value: &str) -> Result<(), Error> {
        let name = HeaderName::from_bytes(name.as_bytes()).map_err(Error::from)?;
        let value = HeaderValue::from_str(value).map_err(Error::from)?;

        self.insert_raw_header(name, value);
        Ok(())
    }

    /// Appends a new value for the given header name.
    ///
    /// Existing values with the same name are preserved.
    /// Multiple values for the same header may be present.
    #[inline]
    pub fn append_header<T>(&mut self, header: Header<T>) -> Result<Header<T>, Error>
    where
        T: FromHeaders,
    {
        self.inner
            .headers_mut()
            .append(header.name(), header.value().clone());
        Ok(header)
    }

    /// Attempts to append a new value for the given header name.
    ///
    /// Returns an error if the header cannot be constructed or appended.
    #[inline]
    pub fn try_append_header<T>(
        &mut self,
        header: impl TryInto<Header<T>, Error = Error>,
    ) -> Result<Header<T>, Error>
    where
        T: FromHeaders,
    {
        let header = header.try_into()?;
        self.append_header(header)
    }

    /// Appends a new raw value for the given raw header name.
    #[inline]
    pub fn append_raw_header(&mut self, name: HeaderName, value: HeaderValue) {
        self.inner.headers_mut().append(name, value);
    }

    /// Attempts to append a new raww value for the given header name.
    #[inline]
    pub fn try_append_raw_header(&mut self, name: &str, value: &str) -> Result<(), Error> {
        let name = HeaderName::from_bytes(name.as_bytes()).map_err(Error::from)?;
        let value = HeaderValue::from_str(value).map_err(Error::from)?;

        self.append_raw_header(name, value);
        Ok(())
    }

    /// Removes all values for the given header name.
    ///
    /// Returns `true` if at least one header value was removed.
    #[inline]
    pub fn remove_header<T>(&mut self) -> bool
    where
        T: FromHeaders,
    {
        self.inner.headers_mut().remove(&T::NAME).is_some()
    }

    /// Attempts to remove all values for the given header name.
    ///
    /// Returns `true` if at least one value was removed.
    #[inline]
    pub fn try_remove_header(&mut self, name: &str) -> Result<bool, Error> {
        let name = HeaderName::from_bytes(name.as_bytes()).map_err(Error::from)?;

        Ok(self.inner.headers_mut().remove(name).is_some())
    }

    /// Returns a mutable reference to the associated HTTP body.
    #[inline]
    pub(crate) fn body_mut(&mut self) -> &mut HttpBody {
        self.inner.body_mut()
    }

    /// Unwraps the inner request
    #[inline]
    pub(crate) fn into_inner(self) -> Response<HttpBody> {
        self.inner
    }

    /// Consumes the response returning the head and body parts.
    #[inline]
    #[allow(unused)]
    pub(crate) fn into_parts(self) -> (Parts, HttpBody) {
        self.inner.into_parts()
    }

    /// Creates a new [`HttpResponse`] with the given head and body
    #[inline]
    #[allow(unused)]
    pub(crate) fn from_parts(parts: Parts, body: HttpBody) -> Self {
        Self {
            inner: Response::from_parts(parts, body),
        }
    }

    /// Creates a new [`HttpResponse`] from [`Response<HttpBody>`]
    #[inline]
    pub(crate) fn from_inner(inner: Response<HttpBody>) -> Self {
        Self { inner }
    }
}

#[cfg(test)]
#[allow(unreachable_pub)]
#[allow(unused)]
mod tests {
    use crate::headers::{Header, HeaderName, HeaderValue, headers};
    use crate::http::body::HttpBody;
    use crate::test::TempFile;
    use crate::test::utils::read_file_bytes;
    use crate::{HttpResponse, response};
    use http_body_util::BodyExt;
    use hyper::StatusCode;
    use serde::Serialize;
    use tokio::fs::File;

    headers! {
        (ApiKey, "x-api-key")
    }

    #[derive(Serialize)]
    struct TestPayload {
        name: String,
    }

    #[tokio::test]
    async fn in_creates_text_response_with_custom_headers() {
        let mut response = HttpResponse::builder()
            .status(400)
            .header_raw("x-api-key", "some api key")
            .header_raw("Content-Type", "text/plain")
            .body(HttpBody::full(String::from("Hello World!")))
            .unwrap();

        let body = &response.body_mut().collect().await.unwrap().to_bytes();

        assert_eq!(response.status(), StatusCode::BAD_REQUEST);
        assert_eq!(String::from_utf8_lossy(body), "Hello World!");
        assert_eq!(
            response.headers().get("Content-Type").unwrap(),
            "text/plain"
        );
        assert_eq!(response.headers().get("x-api-key").unwrap(), "some api key");
    }

    #[tokio::test]
    async fn in_creates_str_text_response_with_custom_headers() {
        let mut response = HttpResponse::builder()
            .status(200)
            .header_raw("x-api-key", "some api key")
            .header_raw("Content-Type", "text/plain")
            .body(HttpBody::full("Hello World!"))
            .unwrap();

        let body = &response.body_mut().collect().await.unwrap().to_bytes();

        assert_eq!(response.status(), StatusCode::OK);
        assert_eq!(String::from_utf8_lossy(body), "Hello World!");
        assert_eq!(
            response.headers().get("Content-Type").unwrap(),
            "text/plain"
        );
        assert_eq!(response.headers().get("x-api-key").unwrap(), "some api key");
    }

    #[tokio::test]
    async fn in_creates_json_response_with_custom_headers() {
        let content = TestPayload {
            name: "test".into(),
        };

        let mut response = HttpResponse::builder()
            .status(200)
            .header_raw("x-api-key", "some api key")
            .header_raw("Content-Type", "application/json")
            .body(HttpBody::json(content).unwrap())
            .unwrap();

        let body = &response.body_mut().collect().await.unwrap().to_bytes();

        assert_eq!(response.status(), StatusCode::OK);
        assert_eq!(String::from_utf8_lossy(body), "{\"name\":\"test\"}");
        assert_eq!(
            response.headers().get("Content-Type").unwrap(),
            "application/json"
        );
        assert_eq!(response.headers().get("x-api-key").unwrap(), "some api key");
    }

    #[tokio::test]
    async fn it_creates_stream_response() {
        let file = TempFile::new("Hello, this is some file content!").await;
        let file = File::open(file.path).await.unwrap();

        let mut response = HttpResponse::builder()
            .status(StatusCode::OK)
            .body(HttpBody::file(file))
            .unwrap();

        let body = read_file_bytes(&mut response).await;

        assert_eq!(response.status(), StatusCode::OK);
        assert_eq!(
            String::from_utf8_lossy(body.as_slice()),
            "Hello, this is some file content!"
        );
    }

    #[tokio::test]
    async fn it_creates_file_response_with_custom_headers() {
        let file = TempFile::new("Hello, this is some file content!").await;
        let file = File::open(file.path).await.unwrap();

        let mut response = response!(
            StatusCode::OK,
            HttpBody::file(file);
            [
                ("x-api-key", "some api key"),
                ("Content-Type", "application/octet-stream")
            ]
        )
        .unwrap();

        let body = read_file_bytes(&mut response).await;

        assert_eq!(response.status(), StatusCode::OK);
        assert_eq!(
            String::from_utf8_lossy(body.as_slice()),
            "Hello, this is some file content!"
        );
        assert_eq!(
            response.headers().get("Content-Type").unwrap(),
            "application/octet-stream"
        );
        assert_eq!(response.headers().get("x-api-key").unwrap(), "some api key");
    }

    #[tokio::test]
    async fn it_creates_empty_not_found_response() {
        let mut response = response!(
            StatusCode::NOT_FOUND,
            HttpBody::empty();
            [
                ("Content-Type", "text/plain")
            ]
        )
        .unwrap();

        let body = &response.body_mut().collect().await.unwrap().to_bytes();

        assert_eq!(response.status(), StatusCode::NOT_FOUND);
        assert_eq!(body.len(), 0);
        assert_eq!(
            response.headers().get("Content-Type").unwrap(),
            "text/plain"
        );
    }

    #[tokio::test]
    async fn it_creates_empty_custom_response() {
        let mut response = response!(
            StatusCode::UNAUTHORIZED,
            HttpBody::empty();
            [
                ("Content-Type", "application/pdf")
            ]
        )
        .unwrap();

        let body = &response.body_mut().collect().await.unwrap().to_bytes();

        assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
        assert_eq!(body.len(), 0);
        assert_eq!(
            response.headers().get("Content-Type").unwrap(),
            "application/pdf"
        );
    }

    #[tokio::test]
    async fn it_creates_custom_response() {
        let mut response = response!(
            StatusCode::FORBIDDEN,
            HttpBody::full("Hello World!");
            [
                ("Content-Type", "text/plain")
            ]
        )
        .unwrap();

        let body = &response.body_mut().collect().await.unwrap().to_bytes();

        assert_eq!(response.status(), StatusCode::FORBIDDEN);
        assert_eq!(String::from_utf8_lossy(body), "Hello World!");
        assert_eq!(
            response.headers().get("Content-Type").unwrap(),
            "text/plain"
        );
    }

    #[test]
    fn it_inserts_header() {
        let mut response = response!(
            StatusCode::OK,
            HttpBody::full("Hello World!");
            [
                ("Content-Type", "text/plain")
            ]
        )
        .unwrap();

        let api_key_header: Header<ApiKey> = Header::from_static("some api key");
        let _ = response.insert_header(api_key_header);

        assert_eq!(response.headers().get("x-api-key").unwrap(), "some api key");
    }

    #[test]
    fn it_tries_insert_header() {
        let mut response = response!(
            StatusCode::OK,
            HttpBody::full("Hello World!");
            [
                ("Content-Type", "text/plain")
            ]
        )
        .unwrap();

        response
            .try_insert_header::<ApiKey>("some api key")
            .unwrap();

        assert_eq!(
            response.get_header::<ApiKey>().unwrap().value(),
            "some api key"
        );
    }

    #[test]
    fn it_inserts_raw_header() {
        let mut response = response!(
            StatusCode::OK,
            HttpBody::full("Hello World!");
            [
                ("Content-Type", "text/plain")
            ]
        )
        .unwrap();

        response.insert_raw_header(
            HeaderName::from_static("x-api-key"),
            HeaderValue::from_static("some api key"),
        );

        assert_eq!(response.headers().get("x-api-key").unwrap(), "some api key");
    }

    #[test]
    fn it_tries_insert_raw_header() {
        let mut response = response!(
            StatusCode::OK,
            HttpBody::full("Hello World!");
            [
                ("Content-Type", "text/plain")
            ]
        )
        .unwrap();

        response
            .try_insert_raw_header("x-api-key", "some api key")
            .unwrap();

        assert_eq!(
            response.get_header::<ApiKey>().unwrap().value(),
            "some api key"
        );
    }

    #[test]
    fn it_appends_header() {
        let mut response = response!(
            StatusCode::OK,
            HttpBody::full("Hello World!");
            [
                ("Content-Type", "text/plain")
            ]
        )
        .unwrap();

        let api_key_header: Header<ApiKey> = Header::from_static("1");
        let _ = response.append_header(api_key_header);

        let api_key_header: Header<ApiKey> = Header::from_static("2");
        let _ = response.append_header(api_key_header);

        assert_eq!(
            response
                .headers()
                .get_all("x-api-key")
                .into_iter()
                .collect::<Vec<_>>(),
            ["1", "2"]
        );
    }

    #[test]
    fn it_tries_append_header() {
        let mut response = response!(
            StatusCode::OK,
            HttpBody::full("Hello World!");
            [
                ("Content-Type", "text/plain")
            ]
        )
        .unwrap();

        response.try_append_header::<ApiKey>("1").unwrap();
        response.try_append_header::<ApiKey>("2").unwrap();

        assert_eq!(
            response
                .get_all_headers::<ApiKey>()
                .map(|h| h.into_inner())
                .collect::<Vec<_>>(),
            ["1", "2"]
        );
    }

    #[test]
    fn it_appends_raw_header() {
        let mut response = response!(
            StatusCode::OK,
            HttpBody::full("Hello World!");
            [
                ("Content-Type", "text/plain")
            ]
        )
        .unwrap();

        response.append_raw_header(
            HeaderName::from_static("x-api-key"),
            HeaderValue::from_static("1"),
        );

        response.append_raw_header(
            HeaderName::from_static("x-api-key"),
            HeaderValue::from_static("2"),
        );

        assert_eq!(
            response
                .get_all_headers::<ApiKey>()
                .map(|h| h.into_inner())
                .collect::<Vec<_>>(),
            ["1", "2"]
        );
    }

    #[test]
    fn it_tries_appends_raw_header() {
        let mut response = response!(
            StatusCode::OK,
            HttpBody::full("Hello World!");
            [
                ("Content-Type", "text/plain")
            ]
        )
        .unwrap();

        response.try_append_raw_header("x-api-key", "1").unwrap();
        response.try_append_raw_header("x-api-key", "2").unwrap();

        assert_eq!(
            response
                .get_all_headers::<ApiKey>()
                .map(|h| h.into_inner())
                .collect::<Vec<_>>(),
            ["1", "2"]
        );
    }

    #[test]
    fn it_removes_header() {
        let mut response = response!(
            StatusCode::OK,
            HttpBody::full("Hello World!");
            [
                ("Content-Type", "text/plain")
            ]
        )
        .unwrap();

        let api_key_header: Header<ApiKey> = Header::from_static("some api key");
        let _ = response.insert_header(api_key_header);

        response.remove_header::<ApiKey>();

        assert!(response.headers().get("x-api-key").is_none());
    }

    #[test]
    fn it_tries_remove_header() {
        let mut response = response!(
            StatusCode::OK,
            HttpBody::full("Hello World!");
            [
                ("Content-Type", "text/plain")
            ]
        )
        .unwrap();

        let api_key_header: Header<ApiKey> = Header::from_static("some api key");
        let _ = response.insert_header(api_key_header);

        let result = response.try_remove_header("x-api-key").unwrap();

        assert!(result);
        assert!(response.headers().get("x-api-key").is_none());
    }
}