tomcat 0.1.12

Crate for Send HTTP/HTTPS requests
Documentation

#![feature(async_closure)]
pub use reqwest::IntoUrl;
pub use reqwest::RequestBuilder;
pub use http::Extensions;
pub use http::HeaderMap;
pub use http::Version;
pub use std::net::SocketAddr;
#[derive(Debug,Clone)]
pub struct Response {
    pub status: u16,
    pub bytes: Vec<u8>,
    pub content_length: Option<u64>,
    pub headers: HeaderMap,
    pub remote_addr: SocketAddr,
    pub text: String,
    pub text_with_charset: String,
    pub url: String,
    pub version: Version,
}
impl Response {
    pub fn new(
        status: u16,
        bytes: Vec<u8>,
        content_length: Option<u64>,
        headers: HeaderMap,
        remote_addr: SocketAddr,
        text: String,
        text_with_charset: String,
        url: String,
        version: Version,
    ) -> Self {
        Response {
            status,
            bytes,
            content_length,
            headers,
            remote_addr,
            text,
            text_with_charset,
            url,
            version,
        }
    }
}



///# non-blocking get
///```rust
///#[tokio::main]
///async fn main(){
///    use tomcat::*;
///    if let Ok(res) = get("https://www.spacex.com").await{
///        assert_eq!(200,res.status);
///        assert_eq!(r#"{"content-type": "text/html; charset=utf-8", "vary": "Accept-Encoding", "date": "Sun, 09 Oct 2022 18:49:44 GMT", "connection": "keep-alive", "keep-alive": "timeout=5", "transfer-encoding": "chunked"}"#,format!("{:?}",res.headers));
///        println!("{}",res.text);
///        println!("{}",res.text_with_charset);
///        println!("{}",res.url);
///        println!("{}",res.remote_addr);
///        println!("{:?}",res.version);
///    }
///}
/// ```
pub async fn get(url: impl ToString + IntoUrl) -> Result<Response, Box<dyn std::error::Error>> {
    let status = reqwest::get(url.as_str().to_string())
        .await?
        .status()
        .as_u16();

    let bytes = reqwest::get(url.as_str().to_string())
        .await?
        .bytes()
        .await
        .unwrap()
        .to_vec();

    let content_length = reqwest::get(url.as_str().to_string())
        .await?
        .content_length();

    let headers = reqwest::get(url.as_str().to_string())
        .await?
        .headers()
        .to_owned();
    let remote_addr = reqwest::get(url.as_str().to_string())
        .await?
        .remote_addr()
        .unwrap();

    let text = reqwest::get(url.as_str().to_string())
        .await?
        .text()
        .await
        .unwrap();

    let text_with_charset = reqwest::get(url.as_str().to_string())
        .await?
        .text_with_charset("utf-8")
        .await
        .unwrap();

    let url = reqwest::get(url.as_str().to_string())
        .await?
        .url()
        .as_str()
        .to_string();

    let version = reqwest::get(url.as_str().to_string()).await?.version();

    Ok(Response::new(
        status,
        bytes,
        content_length,
        headers,
        remote_addr,
        text,
        text_with_charset,
        url,
        version,
    ))
}
///# blocking get
///```rust
///fn main(){
///    use tomcat::*;
///    if let Ok(res) = get_blocking("https://www.spacex.com"){
///        assert_eq!(200,res.status);
///        assert_eq!(r#"{"content-type": "text/html; charset=utf-8", "vary": "Accept-Encoding", "date": "Sun, 09 Oct 2022 18:49:44 GMT", "connection": "keep-alive", "keep-alive": "timeout=5", "transfer-encoding": "chunked"}"#,format!("{:?}",res.headers));
///        println!("{}",res.text);
///        println!("{}",res.text_with_charset);
///        println!("{}",res.url);
///        println!("{}",res.remote_addr);
///        println!("{:?}",res.version);
///    }
///}
///
///```

pub fn get_blocking(url: impl ToString + IntoUrl) -> Result<Response, Box<dyn std::error::Error>> {
    let status = reqwest::blocking::get(url.as_str().to_string())?
        .status()
        .as_u16();

    let bytes = reqwest::blocking::get(url.as_str().to_string())?
        .bytes()
        .unwrap()
        .to_vec();

    let content_length = reqwest::blocking::get(url.as_str().to_string())?.content_length();

    let headers = reqwest::blocking::get(url.as_str().to_string())?
        .headers()
        .to_owned();
    let remote_addr = reqwest::blocking::get(url.as_str().to_string())?
        .remote_addr()
        .unwrap();

    let text = reqwest::blocking::get(url.as_str().to_string())?
        .text()
        .unwrap();

    let text_with_charset = reqwest::blocking::get(url.as_str().to_string())?
        .text_with_charset("utf-8")
        .unwrap();

    let url = reqwest::blocking::get(url.as_str().to_string())?
        .url()
        .as_str()
        .to_string();

    let version = reqwest::blocking::get(url.as_str().to_string())?.version();

    Ok(Response::new(
        status,
        bytes,
        content_length,
        headers,
        remote_addr,
        text,
        text_with_charset,
        url,
        version,
    ))
}


///# non-blocking post
/// ```rust
/// if let Ok(req) = tomcat::post("https://api.openai.com/v1/completions").await {
///    let res = req
///    .header(header::CONTENT_TYPE, "application/json")
///    .header("Authorization", &auth_header_val)
///    .body(body).send().await.unwrap();
///    let text = res.text().await.unwrap();
///
///    let json: OpenAIResponse = match serde_json::from_str(&text){
///        Ok(response) => response,
///        Err(_) => {
///            println!("Error calling OpenAI. Check environment variable OPENAI_KEY");
///            std::process::exit(1);
///        }
///    };
/// ```
pub async fn post(
    url: impl ToString + IntoUrl,
) -> Result<RequestBuilder, Box<dyn std::error::Error>> {
    let client = reqwest::Client::new();
    let requestbuilder = client.post(url.as_str().to_string());
    Ok(requestbuilder)
}
///# blocking post
/// ```rust
///if let Ok(req) = tomcat::post_blocking("https://api.openai.com/v1/completions"){
///    let res = req
///    .header(header::CONTENT_TYPE, "application/json")
///    .header("Authorization", &auth_header_val)
///    .body(body).send().unwrap();
///    let text = res.text().unwrap();
///
///    let json: OpenAIResponse = match serde_json::from_str(&text){
///        Ok(response) => response,
///        Err(_) => {
///            println!("Error calling OpenAI. Check environment variable OPENAI_KEY");
///            std::process::exit(1);
///        }
///    };
/// ```
pub fn post_blocking(
    url: impl ToString + IntoUrl,
) -> Result<reqwest::blocking::RequestBuilder, Box<dyn std::error::Error>> {
    let client = reqwest::blocking::Client::new();
    let requestbuilder = client.post(url.as_str().to_string());
    Ok(requestbuilder)
}