use std::fmt;
use std::pin::Pin;
use std::task::{Context, Poll};
use bytes::Bytes;
use http::{HeaderMap, HeaderValue, StatusCode, header};
use http_body::{Frame, SizeHint};
use http_body_util::{BodyExt, Full};
use serde::Serialize;
use serde_json::json;
use crate::authorization::Authorization;
use crate::errors::BoxError;
use crate::http::RequestContext;
pub type Body = Full<Bytes>;
pub type Response = http::Response<Body>;
pub struct BoxedBody(Pin<Box<dyn http_body::Body<Data = Bytes, Error = BoxError> + Send>>);
impl BoxedBody {
pub fn new<B>(body: B) -> Self
where
B: http_body::Body<Data = Bytes> + Send + 'static,
B::Error: Into<BoxError>,
{
Self(Box::pin(body.map_err(Into::into)))
}
}
impl fmt::Debug for BoxedBody {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("BoxedBody").finish_non_exhaustive()
}
}
impl http_body::Body for BoxedBody {
type Data = Bytes;
type Error = BoxError;
fn poll_frame(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<std::result::Result<Frame<Bytes>, BoxError>>> {
self.0.as_mut().poll_frame(cx)
}
fn is_end_stream(&self) -> bool {
self.0.is_end_stream()
}
fn size_hint(&self) -> SizeHint {
self.0.size_hint()
}
}
pub type BoxedResponse = http::Response<BoxedBody>;
pub type Map = serde_json::Map<String, serde_json::Value>;
pub fn into_boxed<B>(response: http::Response<B>) -> BoxedResponse
where
B: http_body::Body<Data = Bytes> + Send + 'static,
B::Error: Into<BoxError>,
{
response.map(BoxedBody::new)
}
#[derive(Debug, Default)]
pub struct ResponseWriter {
headers: HeaderMap,
}
impl ResponseWriter {
pub fn new() -> Self {
Self::default()
}
pub fn headers(&self) -> &HeaderMap {
&self.headers
}
pub fn headers_mut(&mut self) -> &mut HeaderMap {
&mut self.headers
}
pub fn append(&mut self, name: header::HeaderName, value: HeaderValue) {
self.headers.append(name, value);
}
pub fn apply<B>(&self, response: &mut http::Response<B>) {
for (name, value) in self.headers.iter() {
response.headers_mut().append(name.clone(), value.clone());
}
}
pub fn finish<B>(&self, mut response: http::Response<B>) -> http::Response<B> {
self.apply(&mut response);
response
}
}
pub fn write_json<T: Serialize>(status: StatusCode, v: T) -> Response {
let body = match serde_json::to_vec(&v) {
Ok(body) => body,
Err(err) => {
return http::Response::builder()
.status(StatusCode::INTERNAL_SERVER_ERROR)
.header(header::CONTENT_TYPE, "application/json; charset=utf-8")
.body(Full::new(Bytes::from(
json!({ "error": err.to_string(), "code": "SERVER_ERROR" }).to_string(),
)))
.expect("static response is valid");
}
};
http::Response::builder()
.status(status)
.header(header::CONTENT_TYPE, "application/json; charset=utf-8")
.body(Full::new(Bytes::from(body)))
.expect("json response is valid")
}
pub fn redirect(status: StatusCode, target: &str) -> Response {
let location = HeaderValue::from_str(target).unwrap_or_else(|_| HeaderValue::from_static("/"));
http::Response::builder()
.status(status)
.header(header::LOCATION, location)
.body(Full::new(Bytes::new()))
.expect("redirect response is valid")
}
pub fn wants_json(r: &RequestContext<'_>) -> bool {
if r.header("accept") == "application/json" {
return true;
}
r.header("x-auth-return-redirect") == "1" || r.query_get("json") == "true"
}
impl Authorization {
pub fn redirect_or_json(&self, r: &RequestContext<'_>, target: &str) -> Response {
if wants_json(r) {
return write_json(StatusCode::OK, json!({ "url": target }));
}
redirect(StatusCode::FOUND, target)
}
}