Send HTTP/HTTPS requests.

Crates.io Rust license


cargo add tomcat tokio = { version = "1.21.2", features = ["full"] } tomcat = "0.1.1"

## Examples

non-blocking get

```rust

[tokio::main]

async fn main(){ use tomcat::*; if let Ok(res) = get("https://www.spacex.com").await{ asserteq!(200,res.status); asserteq!(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.textwithcharset); println!("{}",res.url); println!("{}",res.remote_addr); println!("{:?}",res.version); }

}

```

blocking get

```rust fn main(){ use tomcat::*; if let Ok(res) = getblocking("https://www.spacex.com"){ asserteq!(200,res.status); asserteq!(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.textwithcharset); println!("{}",res.url); println!("{}",res.remoteaddr); println!("{:?}",res.version); } }

```

non-blocking post

```rust

[tokio::main]

async fn main() { openai().await.unwrap(); } async fn openai()-> Result<(), Box>{ use std::env::{self, args}; use reqwest::Body; use serdederive::Serialize; use serdederive::Deserialize; use http::header; #[derive(Serialize, Debug)] struct OpenAIRequest { model: String, prompt: String, max_tokens: u32, stop: String, } #[derive(Deserialize, Debug)] struct OpenAIChoices { text: String, }

#[derive(Deserialize, Debug)]
struct OpenAIResponse {
    choices: Vec<OpenAIChoices>,
}

let api_key = match env::var("OPENAI_KEY") {
    Ok(key) => key,
    Err(_) => {
        println!("Error: please create an environment variable OPENAI_KEY");
        std::process::exit(1);
    }
};

let uri = "https://api.openai.com/v1/completions";

let model = String::from("text-davinci-002");
let stop = String::from("Text");

let default_prompt =
    "Given text, return 1 bash command. Text:list contents of a directory. Command:ls";
let mut user_input = String::new();

let mut arguments: Vec<String> = args().collect();
arguments.remove(0);

if arguments.is_empty() {
    println!("Welcome to Rusty! Enter an argument to get started.");
    std::process::exit(1);
}

for x in arguments {
    user_input.push(' ');
    user_input.push_str(&x);
}

let auth_header_val = format!("Bearer {}", api_key);

let openai_request = OpenAIRequest {
    model,
    prompt: format!("{} Text:{}. Command:", default_prompt, user_input),
    max_tokens: 64,
    stop,
};

let body = Body::from(serde_json::to_vec(&openai_request)?);

//
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);
        }
    };

    println!(
        "{}",
        json.choices[0]
            .text
            .split("\n")
            .map(|s| s.trim())
            .filter(|s| s.len() > 0)
            .collect::<Vec<_>>()
            .join("\n")
    );

}

Ok(())

} ```

blocking post

```rust fn main(){ openaiblocking().unwrap(); } fn openaiblocking()-> Result<(), Box>{ use std::env::{self, args}; use reqwest::blocking::Body; use serdederive::Serialize; use serdederive::Deserialize; use http::header; #[derive(Serialize, Debug)] struct OpenAIRequest { model: String, prompt: String, max_tokens: u32, stop: String, } #[derive(Deserialize, Debug)] struct OpenAIChoices { text: String, }

#[derive(Deserialize, Debug)]
struct OpenAIResponse {
    choices: Vec<OpenAIChoices>,
}

let api_key = match env::var("OPENAI_KEY") {
    Ok(key) => key,
    Err(_) => {
        println!("Error: please create an environment variable OPENAI_KEY");
        std::process::exit(1);
    }
};

let uri = "https://api.openai.com/v1/completions";

let model = String::from("text-davinci-002");
let stop = String::from("Text");

let default_prompt =
    "Given text, return 1 bash command. Text:list contents of a directory. Command:ls";
let mut user_input = String::new();

let mut arguments: Vec<String> = args().collect();
arguments.remove(0);

if arguments.is_empty() {
    println!("Welcome to Rusty! Enter an argument to get started.");
    std::process::exit(1);
}

for x in arguments {
    user_input.push(' ');
    user_input.push_str(&x);
}

let auth_header_val = format!("Bearer {}", api_key);

let openai_request = OpenAIRequest {
    model,
    prompt: format!("{} Text:{}. Command:", default_prompt, user_input),
    max_tokens: 64,
    stop,
};

let body = Body::from(serde_json::to_vec(&openai_request)?);

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);
        }
    };

    println!(
        "{}",
        json.choices[0]
            .text
            .split("\n")
            .map(|s| s.trim())
            .filter(|s| s.len() > 0)
            .collect::<Vec<_>>()
            .join("\n")
    );

}

Ok(())

} ```