use bytes::Bytes;
use http::{Extensions, HeaderMap, HeaderName, HeaderValue, StatusCode, header};
use http_body_util::Full;
use serde::Serialize;
use crate::error::Error;
#[derive(Debug, Clone, Copy)]
struct Head;
#[derive(Debug, Clone)]
pub struct Response {
status: StatusCode,
headers: HeaderMap,
body: Bytes,
extensions: Extensions,
}
impl Default for Response {
fn default() -> Self {
Self::new(StatusCode::OK)
}
}
impl Response {
pub fn new(status: StatusCode) -> Self {
Self {
status,
headers: HeaderMap::new(),
body: Bytes::new(),
extensions: Extensions::new(),
}
}
pub fn text(body: impl Into<String>) -> Self {
Self::with_body(body.into(), "text/plain; charset=utf-8")
}
pub fn html(body: impl Into<String>) -> Self {
Self::with_body(body.into(), "text/html; charset=utf-8")
}
pub fn json<T: Serialize + ?Sized>(value: &T) -> Self {
match serde_json::to_vec(value) {
Ok(body) if ESCAPE_HTML.load(std::sync::atomic::Ordering::Relaxed) => {
Self::with_body(escape_html(&body), "application/json; charset=utf-8")
}
Ok(body) => Self::with_body(body, "application/json; charset=utf-8"),
Err(err) => Error::from(err).into_response(),
}
}
pub fn redirect(location: &str) -> Self {
Self::new(StatusCode::SEE_OTHER).with_header(header::LOCATION, location)
}
pub fn head(status: StatusCode) -> Self {
let mut response = Self::new(status);
response.extensions.insert(Head);
response
}
pub fn no_content() -> Self {
Self::new(StatusCode::NO_CONTENT)
}
fn with_body(body: impl Into<Bytes>, content_type: &'static str) -> Self {
let mut res = Self::new(StatusCode::OK);
res.body = body.into();
res.headers
.insert(header::CONTENT_TYPE, HeaderValue::from_static(content_type));
res
}
pub fn with_body_bytes(mut self, body: impl Into<Bytes>) -> Self {
self.body = body.into();
self
}
pub fn with_status(mut self, status: StatusCode) -> Self {
self.status = status;
self
}
pub fn with_header<K, V>(mut self, name: K, value: V) -> Self
where
K: TryInto<HeaderName>,
V: TryInto<HeaderValue>,
{
match (name.try_into(), value.try_into()) {
(Ok(name), Ok(value)) => {
self.headers.insert(name, value);
}
_ => tracing::warn!("ignoring invalid response header"),
}
self
}
pub fn status(&self) -> StatusCode {
self.status
}
pub fn headers(&self) -> &HeaderMap {
&self.headers
}
pub fn headers_mut(&mut self) -> &mut HeaderMap {
&mut self.headers
}
pub fn header(&self, name: impl http::header::AsHeaderName) -> Option<&str> {
self.headers.get(name).and_then(|v| v.to_str().ok())
}
pub fn extensions(&self) -> &Extensions {
&self.extensions
}
pub fn extensions_mut(&mut self) -> &mut Extensions {
&mut self.extensions
}
pub fn body(&self) -> &Bytes {
&self.body
}
pub fn fresh_when(
mut self,
ctx: &crate::Context,
last_modified: chrono::DateTime<chrono::Utc>,
) -> Self {
use sha2::Digest;
let modified = last_modified
.format("%a, %d %b %Y %H:%M:%S GMT")
.to_string();
let digest = sha2::Sha256::digest(&self.body);
let etag = format!(
"W/\"{}\"",
digest[..16]
.iter()
.map(|b| format!("{b:02x}"))
.collect::<String>()
);
let fresh = match ctx.header(header::IF_NONE_MATCH) {
Some(tags) => tags
.split(',')
.any(|tag| tag.trim() == etag || tag.trim() == "*"),
None => ctx
.header(header::IF_MODIFIED_SINCE)
.and_then(crate::time::parse_http_date)
.is_some_and(|since| since.timestamp() >= last_modified.timestamp()),
};
if let Ok(value) = HeaderValue::from_str(&modified) {
self.headers.insert(header::LAST_MODIFIED, value);
}
if let Ok(value) = HeaderValue::from_str(&etag) {
self.headers.insert(header::ETAG, value);
}
if fresh && self.status == StatusCode::OK {
self.status = StatusCode::NOT_MODIFIED;
self.body = Bytes::new();
self.headers.remove(header::CONTENT_TYPE);
}
self
}
pub fn is_head(&self) -> bool {
self.extensions.get::<Head>().is_some()
}
pub fn body_text(&self) -> String {
String::from_utf8_lossy(&self.body).into_owned()
}
pub fn body_json(&self) -> serde_json::Value {
serde_json::from_slice(&self.body).unwrap_or_default()
}
pub(crate) fn into_http(self) -> http::Response<Full<Bytes>> {
let mut res = http::Response::new(Full::new(self.body));
*res.status_mut() = self.status;
*res.headers_mut() = self.headers;
res
}
}
pub trait IntoResponse {
fn into_response(self) -> Response;
}
static ESCAPE_HTML: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
pub fn escape_html_entities_in_json(on: bool) {
ESCAPE_HTML.store(on, std::sync::atomic::Ordering::Relaxed);
}
fn escape_html(json: &[u8]) -> Vec<u8> {
let text = String::from_utf8_lossy(json);
let mut out = String::with_capacity(text.len());
for c in text.chars() {
match c {
'<' => out.push_str("\\u003c"),
'>' => out.push_str("\\u003e"),
'&' => out.push_str("\\u0026"),
'\u{2028}' => out.push_str("\\u2028"),
'\u{2029}' => out.push_str("\\u2029"),
c => out.push(c),
}
}
out.into_bytes()
}
#[cfg(test)]
mod escape_tests {
#[test]
fn escapes_as_rails_does() {
let json = br#"{"url":"/a?b=1&c=<x>"}"#;
assert_eq!(
String::from_utf8(super::escape_html(json)).unwrap(),
r#"{"url":"/a?b=1\u0026c=\u003cx\u003e"}"#
);
}
}
impl IntoResponse for Response {
fn into_response(self) -> Response {
self
}
}
impl IntoResponse for &'static str {
fn into_response(self) -> Response {
Response::text(self)
}
}
impl IntoResponse for String {
fn into_response(self) -> Response {
Response::text(self)
}
}
impl IntoResponse for StatusCode {
fn into_response(self) -> Response {
Response::new(self)
}
}
impl<R: IntoResponse> IntoResponse for (StatusCode, R) {
fn into_response(self) -> Response {
self.1.into_response().with_status(self.0)
}
}
impl<R: IntoResponse, E: IntoResponse> IntoResponse for Result<R, E> {
fn into_response(self) -> Response {
match self {
Ok(r) => r.into_response(),
Err(e) => e.into_response(),
}
}
}
#[derive(Debug, Clone)]
pub struct Html<T>(pub T);
impl<T: Into<String>> IntoResponse for Html<T> {
fn into_response(self) -> Response {
Response::html(self.0)
}
}
#[derive(Debug, Clone)]
pub struct Json<T>(pub T);
impl<T: Serialize> IntoResponse for Json<T> {
fn into_response(self) -> Response {
Response::json(&self.0)
}
}
pub trait IntoStatus {
fn into_status(self) -> StatusCode;
}
impl IntoStatus for StatusCode {
fn into_status(self) -> StatusCode {
self
}
}
impl IntoStatus for u16 {
#[track_caller]
fn into_status(self) -> StatusCode {
StatusCode::from_u16(self).unwrap_or_else(|_| panic!("{self} isn't an HTTP status"))
}
}
impl IntoStatus for i32 {
#[track_caller]
fn into_status(self) -> StatusCode {
u16::try_from(self)
.ok()
.and_then(|code| StatusCode::from_u16(code).ok())
.unwrap_or_else(|| panic!("{self} isn't an HTTP status"))
}
}
impl IntoStatus for &str {
#[track_caller]
fn into_status(self) -> StatusCode {
status_named(self).unwrap_or_else(|| panic!("no HTTP status is called `:{self}`"))
}
}
pub fn status_name(status: StatusCode) -> String {
let reason = status.canonical_reason().unwrap_or(status.as_str());
reason
.to_ascii_lowercase()
.replace(['-', '\''], "")
.split(|c: char| !c.is_ascii_alphanumeric())
.filter(|word| !word.is_empty())
.collect::<Vec<_>>()
.join("_")
}
pub fn status_named(name: &str) -> Option<StatusCode> {
(100..600)
.filter_map(|code| StatusCode::from_u16(code).ok())
.find(|status| status_name(*status) == name)
}