Files
axum/axum/src/response/mod.rs
T

90 lines
2.2 KiB
Rust
Raw Normal View History

2021-11-01 22:13:37 +01:00
#![doc = include_str!("../docs/response.md")]
2021-06-07 16:28:40 +02:00
use axum_core::body::{boxed, BoxBody};
2021-05-30 13:24:03 +02:00
use bytes::Bytes;
use http::{header, HeaderValue, Response};
use http_body::Full;
2021-05-30 13:24:03 +02:00
2021-08-16 19:48:03 +02:00
mod redirect;
pub mod sse;
2021-08-17 17:28:02 +02:00
#[doc(no_inline)]
2021-10-02 15:46:33 +02:00
#[cfg(feature = "json")]
2021-08-17 17:28:02 +02:00
pub use crate::Json;
#[doc(inline)]
pub use axum_core::response::{Headers, IntoResponse};
2021-08-14 16:29:09 +01:00
#[doc(inline)]
pub use self::{redirect::Redirect, sse::Sse};
2021-07-22 21:21:53 +02:00
2021-06-06 23:58:44 +02:00
/// An HTML response.
///
/// Will automatically get `Content-Type: text/html`.
2021-06-07 15:45:19 +02:00
#[derive(Clone, Copy, Debug)]
2021-05-31 10:20:07 +02:00
pub struct Html<T>(pub T);
2021-06-06 22:41:52 +02:00
impl<T> IntoResponse for Html<T>
2021-05-31 10:20:07 +02:00
where
T: Into<Full<Bytes>>,
2021-05-31 10:20:07 +02:00
{
fn into_response(self) -> Response<BoxBody> {
let mut res = Response::new(boxed(self.0.into()));
res.headers_mut().insert(
header::CONTENT_TYPE,
HeaderValue::from_static(mime::TEXT_HTML_UTF_8.as_ref()),
);
2021-05-31 22:54:21 +02:00
res
2021-05-31 10:20:07 +02:00
}
}
impl<T> From<T> for Html<T> {
fn from(inner: T) -> Self {
Self(inner)
}
}
#[cfg(test)]
mod tests {
use super::*;
use http::{
header::{HeaderMap, HeaderName},
StatusCode,
};
use http_body::Empty;
#[test]
fn test_merge_headers() {
struct MyResponse;
impl IntoResponse for MyResponse {
fn into_response(self) -> Response<BoxBody> {
let mut resp = Response::new(boxed(Empty::new()));
resp.headers_mut()
.insert(HeaderName::from_static("a"), HeaderValue::from_static("1"));
resp
}
}
fn check(resp: impl IntoResponse) {
let resp = resp.into_response();
assert_eq!(
resp.headers().get(HeaderName::from_static("a")).unwrap(),
&HeaderValue::from_static("1")
);
assert_eq!(
resp.headers().get(HeaderName::from_static("b")).unwrap(),
&HeaderValue::from_static("2")
);
}
let headers: HeaderMap =
std::iter::once((HeaderName::from_static("b"), HeaderValue::from_static("2")))
.collect();
check((headers.clone(), MyResponse));
check((StatusCode::OK, headers, MyResponse));
}
}