maw 0.30.0

A simple and efficient 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
use std::{
    error::Error as StdError,
    fmt,
    pin::Pin,
    sync::Arc,
    task::{Context, Poll},
};

use bytes::Bytes;
use futures_util::{Stream, StreamExt};
use http::{
    self, HeaderMap, HeaderName, HeaderValue, StatusCode,
    header::{self, InvalidHeaderName},
};
use http_body::{Body as HttpBodyTrait, Frame, SizeHint};
use http_body_util::Full;

use crate::{
    any_map::{AnyMap, SerializableAny},
    app::App,
    error::Error,
};

pub type BoxError = Box<dyn StdError + Send + Sync>;

pub enum StreamKind {
    /// Stream produces raw bytes (wrapped into data frames automatically)
    Bytes(Pin<Box<dyn Stream<Item = Result<Bytes, BoxError>> + Send + Sync>>),
    /// Stream produces frames directly (can include trailers)
    Frames(Pin<Box<dyn Stream<Item = Result<Frame<Bytes>, BoxError>> + Send + Sync>>),
}

#[derive(Default)]
pub enum HttpBody {
    #[default]
    Empty,
    Full(Full<Bytes>),
    Stream(StreamKind),
}

impl fmt::Debug for HttpBody {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            HttpBody::Empty => f.debug_struct("HttpBody::Empty").finish(),
            HttpBody::Full(b) => f.debug_struct("HttpBody::Full").field("body", b).finish(),
            HttpBody::Stream(_) => f.debug_struct("HttpBody::Stream").finish(),
        }
    }
}

impl HttpBody {
    pub fn full(bytes: Bytes) -> Self {
        HttpBody::Full(Full::new(bytes))
    }

    /// Create a stream that produces data frames only
    pub fn stream<S>(stream: S) -> Self
    where
        S: Stream<Item = Result<Bytes, BoxError>> + Send + Sync + 'static,
    {
        HttpBody::Stream(StreamKind::Bytes(Box::pin(stream)))
    }

    /// Create a stream that can produce both data and trailer frames
    pub fn stream_frames<S>(stream: S) -> Self
    where
        S: Stream<Item = Result<Frame<Bytes>, BoxError>> + Send + Sync + 'static,
    {
        HttpBody::Stream(StreamKind::Frames(Box::pin(stream)))
    }
}

impl HttpBodyTrait for HttpBody {
    type Data = Bytes;
    type Error = BoxError;

    fn poll_frame(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
    ) -> Poll<Option<Result<Frame<Self::Data>, Self::Error>>> {
        match self.get_mut() {
            HttpBody::Empty => Poll::Ready(None),
            HttpBody::Full(full) => Pin::new(full)
                .poll_frame(cx)
                .map(|opt| opt.map(|res| res.map_err(Into::into))),
            HttpBody::Stream(kind) => match kind {
                // Wrap bytes into data frames
                StreamKind::Bytes(stream) => match stream.as_mut().poll_next(cx) {
                    Poll::Ready(Some(Ok(bytes))) => Poll::Ready(Some(Ok(Frame::data(bytes)))),
                    Poll::Ready(Some(Err(e))) => Poll::Ready(Some(Err(e))),
                    Poll::Ready(None) => Poll::Ready(None),
                    Poll::Pending => Poll::Pending,
                },
                // Pass frames through directly
                StreamKind::Frames(stream) => stream.as_mut().poll_next(cx),
            },
        }
    }

    fn size_hint(&self) -> SizeHint {
        match self {
            HttpBody::Empty => SizeHint::with_exact(0),
            HttpBody::Full(full) => full.size_hint(),
            HttpBody::Stream(_) => SizeHint::new(),
        }
    }
}

pub type HttpResponse<T = HttpBody> = http::Response<T>;

pub struct Response {
    pub(crate) app: Arc<App>,
    pub(crate) inner: http::response::Response<HttpBody>,
    pub locals: AnyMap<dyn SerializableAny>,
    // Indicates if the status code has been modified by the user
    pub(crate) status_modified: bool,
}

impl Response {
    #[inline]
    pub(crate) const fn from_response(app: Arc<App>, res: HttpResponse) -> Self {
        Response {
            app,
            inner: res,
            locals: AnyMap::new(),
            status_modified: false,
        }
    }

    pub fn app(&self) -> &App {
        &self.app
    }

    /// Sets the HTTP status for the response.
    pub fn status(&mut self, status: StatusCode) -> &mut Self {
        if !self.status_modified {
            self.status_modified = true;
        }
        *self.inner.status_mut() = status;
        self
    }

    /// Sets the status code and sends the status text (e.g. "Not Found") as the body.
    ///
    /// **Only** writes the body if it is currently empty.
    pub fn send_status(&mut self, status: StatusCode) -> &mut Self {
        self.status(status);

        if self.inner.body().size_hint().exact() == Some(0) {
            let text = status.canonical_reason().unwrap_or("").to_string();
            *self.inner.body_mut() = HttpBody::full(Bytes::from(text));
        }

        self
    }

    #[inline]
    pub fn headers(&self) -> &http::header::HeaderMap<HeaderValue> {
        self.inner.headers()
    }

    #[inline]
    pub fn headers_mut(&mut self) -> &mut http::header::HeaderMap<HeaderValue> {
        self.inner.headers_mut()
    }

    /// Adds one or more HTTP headers.
    ///
    /// This method is flexible about input types. You can pass:
    /// - a single `(name, value)` tuple:
    ///   `res.header(("Content-Type", "text/plain"))`
    /// - an array of tuples:
    ///   `res.header([("Content-Type", "text/plain"), ("ETag", "123")])`
    /// - a `Vec` of tuples:
    ///   `res.header(vec![("Content-Type", "text/plain")])`
    /// - a `HashMap` of header name/value pairs:
    ///   `res.header(hashmap)`
    ///
    /// If converting the input into headers fails, the error is logged and the
    /// response is returned unchanged.
    #[inline]
    pub fn header<H>(&mut self, headers: H) -> &mut Self
    where
        H: SetIntoHeaders,
    {
        if let Err(e) = headers.into_headers(self.inner.headers_mut()) {
            tracing::error!("failed to set headers: {e}");
        }
        self
    }

    /// Appends a value to the HTTP response header field.
    /// If the header is not already set, it creates the header with the specified value.
    ///
    /// Examples:
    /// ```
    /// res.append("Link", "<http://localhost/>")?;
    /// res.append("Set-Cookie", ["foo=bar; Path=/", "bar=baz; HttpOnly"])?;
    /// res.append("Warning", vec!["199 Miscellaneous warning"])?;
    /// ```
    #[inline]
    pub fn append<K, V>(&mut self, key: K, values: V) -> &mut Self
    where
        K: TryInto<HeaderName, Error = InvalidHeaderName>,
        V: AppendIntoHeaderValues,
        Error: From<K::Error>,
    {
        let key = match key.try_into() {
            Ok(k) => k,
            Err(e) => {
                tracing::error!("failed to convert header name: {e}");
                return self;
            }
        };
        if let Err(e) = values.append_to_header(self.inner.headers_mut(), key) {
            tracing::error!("failed to append header value: {e}");
        }
        self
    }

    /// Send a *non-streaming* body.
    #[inline]
    pub fn send(&mut self, body: impl Into<Bytes>) {
        *self.inner.body_mut() = HttpBody::full(body.into());
    }

    /// Send a *streaming* body.
    #[inline]
    pub fn stream<S, E>(&mut self, stream: S)
    where
        S: Stream<Item = Result<Bytes, E>> + Send + Sync + 'static,
        E: Into<BoxError> + 'static,
    {
        let mapped = stream.map(|result| result.map_err(|e| e.into()));
        *self.inner.body_mut() = HttpBody::stream(mapped);
    }

    /// Send a *streaming* body with frames.
    #[inline]
    pub fn stream_frames<S, E>(&mut self, stream: S)
    where
        S: Stream<Item = Result<Frame<Bytes>, E>> + Send + Sync + 'static,
        E: Into<BoxError> + 'static,
    {
        let mapped = stream.map(|result| result.map_err(|e| e.into()));
        *self.inner.body_mut() = HttpBody::stream_frames(mapped);
    }

    /// Send a server-sent events (SSE) stream.
    ///
    /// Sets standard SSE headers and automatically closes the stream when
    /// application shutdown is triggered.
    pub fn sse<S, E>(&mut self, stream: S)
    where
        S: Stream<Item = Result<Bytes, E>> + Send + Sync + 'static,
        E: Into<BoxError> + 'static,
    {
        self.header([
            ("Content-Type", "text/event-stream"),
            ("Cache-Control", "no-cache"),
            ("X-Accel-Buffering", "no"), // Disable buffering for nginx
        ]);

        let shutdown = self.app.shutdown_token().cancelled_owned();

        let stream = stream
            .map(|result| result.map_err(Into::into))
            .take_until(shutdown);

        *self.inner.body_mut() = HttpBody::stream(stream);
    }

    #[inline]
    pub fn content_type<V>(&mut self, value: V) -> &mut Self
    where
        V: TryInto<HeaderValue>,
        Error: From<V::Error>,
    {
        self.header((header::CONTENT_TYPE, value))
    }

    #[inline]
    pub fn html(&mut self, s: &'static str) {
        self.content_type("text/html; charset=utf-8").send(s);
    }

    #[inline]
    pub fn json(&mut self, value: impl serde::Serialize) {
        match serde_json::to_string(&value) {
            Ok(json_str) => self
                .content_type("application/json; charset=utf-8")
                .send(json_str),
            Err(e) => {
                tracing::error!("failed to serialize JSON response: {e}");
                self.status(StatusCode::INTERNAL_SERVER_ERROR)
                    .send("Internal Server Error")
            }
        }
    }

    #[cfg(feature = "minijinja")]
    #[inline]
    pub fn get_render_ctx(&self) -> minijinja::Value {
        let mut ctx = std::collections::BTreeMap::new();
        self.app.locals(|l| {
            for (key, value) in l {
                ctx.insert(key.to_string(), minijinja::Value::from_serialize(value));
            }
        });
        for (key, value) in &self.locals {
            ctx.insert(key.to_string(), minijinja::Value::from_serialize(value));
        }
        minijinja::Value::from(ctx)
    }

    #[cfg(feature = "minijinja")]
    fn send_rendered(&mut self, result: Result<String, minijinja::Error>, label: &str) {
        match result {
            Ok(rendered) => self
                .status(StatusCode::OK)
                .content_type("text/html; charset=utf-8")
                .send(rendered),
            Err(e) => {
                tracing::warn!("failed to render {label}: {e}");
                self.send_status(StatusCode::INTERNAL_SERVER_ERROR);
            }
        }
    }

    #[cfg(feature = "minijinja")]
    #[inline]
    pub fn render(&mut self, template: &str) {
        let ctx = self.get_render_ctx();
        let result = self.app.jinja.render(template, &ctx);
        self.send_rendered(result, template);
    }

    #[cfg(feature = "minijinja")]
    #[inline]
    pub fn render_with(&mut self, template: &str, value: minijinja::Value) {
        let ctx = minijinja::context! { ..self.get_render_ctx(), ..value };
        let result = self.app.jinja.render(template, &ctx);
        self.send_rendered(result, template);
    }

    #[cfg(feature = "minijinja")]
    #[inline]
    pub fn render_str(&mut self, source: &str) {
        let ctx = self.get_render_ctx();
        let result = self.app.jinja.render_str(source, &ctx);
        self.send_rendered(result, "inline template");
    }

    #[cfg(feature = "minijinja")]
    #[inline]
    pub fn render_str_with(&mut self, source: &str, value: minijinja::Value) {
        let ctx = minijinja::context! { ..self.get_render_ctx(), ..value };
        let result = self.app.jinja.render_str(source, &ctx);
        self.send_rendered(result, "inline template");
    }

    /// Redirects to the specified location with an optional status code.
    /// If no status is provided, defaults to 302 Found.
    pub fn redirect(&mut self, location: impl AsRef<str>, status: Option<StatusCode>) {
        // Set the Location header
        self.header((header::LOCATION, location.as_ref()));

        // Set status code (default to 302 Found)
        let status_code = status.unwrap_or(StatusCode::FOUND);
        self.status(status_code);
    }

    /// Streams a file as the response body, setting `Content-Type` and `Content-Length` automatically.
    pub async fn send_file(
        &mut self,
        path: impl AsRef<std::path::Path>,
    ) -> Result<(), std::io::Error> {
        let path = path.as_ref();
        let file = tokio::fs::File::open(path).await?;
        let meta = file.metadata().await?;

        let mime = mime_guess::from_path(path).first_or_octet_stream();
        self.header(("Content-Type", mime.as_ref()));
        self.header(("Content-Length", meta.len().to_string()));

        self.stream(tokio_util::io::ReaderStream::with_capacity(file, 64 * 1024));

        Ok(())
    }
}

impl fmt::Debug for Response {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Response")
            .field("status_code", &self.inner.status())
            .field("body", &self.inner.body())
            .finish()
    }
}

pub trait SetIntoHeaders {
    fn into_headers(self, map: &mut HeaderMap) -> Result<(), Error>;
}

impl<K, V> SetIntoHeaders for (K, V)
where
    K: TryInto<HeaderName>,
    V: TryInto<HeaderValue>,
    Error: From<K::Error> + From<V::Error>,
{
    fn into_headers(self, map: &mut HeaderMap) -> Result<(), Error> {
        let k = self.0.try_into()?;
        let v = self.1.try_into()?;
        map.insert(k, v);
        Ok(())
    }
}

impl<K, V, const N: usize> SetIntoHeaders for [(K, V); N]
where
    K: TryInto<HeaderName>,
    V: TryInto<HeaderValue>,
    Error: From<K::Error> + From<V::Error>,
{
    fn into_headers(self, map: &mut HeaderMap) -> Result<(), Error> {
        for (key, value) in self {
            let k = key.try_into()?;
            let v = value.try_into()?;
            map.insert(k, v);
        }
        Ok(())
    }
}

impl<K, V> SetIntoHeaders for Vec<(K, V)>
where
    K: TryInto<HeaderName>,
    V: TryInto<HeaderValue>,
    Error: From<K::Error> + From<V::Error>,
{
    fn into_headers(self, map: &mut HeaderMap) -> Result<(), Error> {
        for (key, value) in self {
            let k = key.try_into()?;
            let v = value.try_into()?;
            map.insert(k, v);
        }
        Ok(())
    }
}

pub trait AppendIntoHeaderValues {
    fn append_to_header(self, map: &mut HeaderMap, key: HeaderName) -> Result<(), http::Error>;
}

impl AppendIntoHeaderValues for &str {
    fn append_to_header(self, map: &mut HeaderMap, key: HeaderName) -> Result<(), http::Error> {
        let value = HeaderValue::try_from(self).map_err(|e| http::Error::from(e))?;
        map.append(key, value);
        Ok(())
    }
}

impl AppendIntoHeaderValues for String {
    fn append_to_header(self, map: &mut HeaderMap, key: HeaderName) -> Result<(), http::Error> {
        let value = HeaderValue::try_from(self).map_err(|e| http::Error::from(e))?;
        map.append(key, value);
        Ok(())
    }
}

impl AppendIntoHeaderValues for HeaderValue {
    fn append_to_header(self, map: &mut HeaderMap, key: HeaderName) -> Result<(), http::Error> {
        map.append(key, self);
        Ok(())
    }
}

impl AppendIntoHeaderValues for &[&str] {
    fn append_to_header(self, map: &mut HeaderMap, key: HeaderName) -> Result<(), http::Error> {
        for &value in self {
            let v = HeaderValue::try_from(value).map_err(|e| http::Error::from(e))?;
            map.append(key.clone(), v);
        }
        Ok(())
    }
}

impl AppendIntoHeaderValues for &[String] {
    fn append_to_header(self, map: &mut HeaderMap, key: HeaderName) -> Result<(), http::Error> {
        for value in self {
            let v = HeaderValue::try_from(value.as_str()).map_err(|e| http::Error::from(e))?;
            map.append(key.clone(), v);
        }
        Ok(())
    }
}

impl AppendIntoHeaderValues for Vec<String> {
    fn append_to_header(self, map: &mut HeaderMap, key: HeaderName) -> Result<(), http::Error> {
        for value in self {
            let v = HeaderValue::try_from(value).map_err(|e| http::Error::from(e))?;
            map.append(key.clone(), v);
        }
        Ok(())
    }
}

impl<const N: usize> AppendIntoHeaderValues for [String; N] {
    fn append_to_header(self, map: &mut HeaderMap, key: HeaderName) -> Result<(), http::Error> {
        for value in self {
            let v = HeaderValue::try_from(value).map_err(|e| http::Error::from(e))?;
            map.append(key.clone(), v);
        }
        Ok(())
    }
}

impl<const N: usize> AppendIntoHeaderValues for [&str; N] {
    fn append_to_header(self, map: &mut HeaderMap, key: HeaderName) -> Result<(), http::Error> {
        for value in self {
            let v = HeaderValue::try_from(value).map_err(|e| http::Error::from(e))?;
            map.append(key.clone(), v);
        }
        Ok(())
    }
}

impl<const N: usize> AppendIntoHeaderValues for &[String; N] {
    fn append_to_header(self, map: &mut HeaderMap, key: HeaderName) -> Result<(), http::Error> {
        for value in self {
            let v = HeaderValue::try_from(value).map_err(|e| http::Error::from(e))?;
            map.append(key.clone(), v);
        }
        Ok(())
    }
}

impl<const N: usize> AppendIntoHeaderValues for &[&str; N] {
    fn append_to_header(self, map: &mut HeaderMap, key: HeaderName) -> Result<(), http::Error> {
        for value in self {
            let v = HeaderValue::try_from(*value).map_err(|e| http::Error::from(e))?;
            map.append(key.clone(), v);
        }
        Ok(())
    }
}

impl AppendIntoHeaderValues for Vec<&str> {
    fn append_to_header(self, map: &mut HeaderMap, key: HeaderName) -> Result<(), http::Error> {
        for value in self {
            let v = HeaderValue::try_from(value).map_err(|e| http::Error::from(e))?;
            map.append(key.clone(), v);
        }
        Ok(())
    }
}