use super::{Headers, SearchParams, Url};
use crate::js::{self, Value};
#[derive(Clone, Debug, Default)]
pub struct Request {
pub url: String,
pub method: String,
pub headers: Headers,
pub body: Vec<u8>,
pub remote_address: String,
}
impl Request {
pub fn new(method: &str, url: impl Into<String>) -> Request {
Request { url: url.into(), method: method.to_ascii_uppercase(), ..Request::default() }
}
pub fn get(url: impl Into<String>) -> Request {
Request::new("GET", url)
}
pub fn header(mut self, name: &str, value: impl AsRef<str>) -> Request {
self.headers.set(name, value.as_ref());
self
}
pub fn body(mut self, body: impl Into<Vec<u8>>) -> Request {
self.body = body.into();
self
}
pub fn remote(mut self, address: impl Into<String>) -> Request {
self.remote_address = address.into();
self
}
pub fn text(&self) -> String {
utf8(&self.body)
}
pub fn json(&self) -> Result<Value, js::JsonError> {
js::parse(&self.text())
}
pub fn form(&self) -> SearchParams {
SearchParams::parse_bytes(&self.body)
}
pub fn parsed_url(&self) -> Url {
Url::parse(&self.url).unwrap_or_else(|| Url::parse("http://localhost/").expect("a URL"))
}
}
pub fn utf8(bytes: &[u8]) -> String {
let bytes = bytes.strip_prefix(b"\xEF\xBB\xBF").unwrap_or(bytes);
String::from_utf8_lossy(bytes).into_owned()
}