use super::Headers;
use super::request::utf8;
use crate::js::{self, Value};
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Response {
pub status: u16,
pub headers: Headers,
pub body: Vec<u8>,
}
impl Default for Response {
fn default() -> Self {
Response { status: 200, headers: Headers::new(), body: Vec::new() }
}
}
impl Response {
pub fn new(body: impl Into<Vec<u8>>, status: u16, headers: Headers) -> Response {
Response { status, headers, body: body.into() }
}
pub fn json(data: &Value, status: u16) -> Response {
Response::new(js::stringify(data), status, Headers::new().with("content-type", "application/json"))
}
pub fn status(status: u16) -> Response {
Response { status, ..Response::default() }
}
pub fn header(mut self, name: &str, value: impl AsRef<str>) -> Response {
self.headers.set(name, value.as_ref());
self
}
pub fn ok(&self) -> bool {
(200..300).contains(&self.status)
}
pub fn text(&self) -> String {
utf8(&self.body)
}
pub fn json_body(&self) -> Result<Value, js::JsonError> {
js::parse(&self.text())
}
}