/*
 * @Author: 
 * @Date: 2023-03-12 10:30:23
 * @LastEditors: 
 * @LastEditTime: 2023-03-22 21:48:39
 * @FilePath: \chatgpt\src\main.rs
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
extern crate lazy_static;
use std::{io, collections::HashMap};
use std::io::Write;
// use lazy_static::lazy_static;
// use std::fmt::format;
// use std::io::BufRead;
use reqwest::header::HeaderMap;
use std::sync::Mutex;
// use serde::{Deserialize, Deserializer};
// use serde_derive::Deserialize;
// use std::error::Error;
// use serde::de::Visitor;
// use serde_json::{Map, Value};
#[macro_use]
lazy_static::lazy_static! {
    static ref HISTORY_STR: Mutex<String> = Mutex::new(String::new());
}
#[tokio::main]
async fn main() {
    loop {
        match send_post().await {
            Ok(mut res) => {
                res=res.replace("\\n","").replace("\\\"","");
                let completions: Vec<&str> = res
                    //分割字符串切片向量 其中每个元素都包含了completion值的json 对象 字符串
                    .split("{\"type\":\"success\",\"completion\":\"")
                    .skip(1)
                    //提取completion 值
                    .map(|s| s.split("\"}").next().expect("map error on loop."))
                    .collect();
                //join 合并字符串
                let merged = completions.join("");
                println!("AI-> {}", merged);
            }

            Err(e) => { eprintln!("{:?}", e) }
        }
    }
}

//获取用户键盘输入
async fn get_user_input() -> (){
    let mut input_buf = String::new();
    print_to_terminal().await;
    let _input = io::stdin().read_line(&mut input_buf).expect("fail to get user input.");
    HISTORY_STR.lock().unwrap().push_str(&input_buf);
}

async fn send_post() -> Result<String, reqwest::Error> {
    let client = reqwest::Client::new();
    //post 请求头
    let mut header = HeaderMap::new();
    header.insert("User-Agent",
                  "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) \
                  Chrome/110.0.0.0 Safari/537.36".parse().expect("unsolve the userAgent header value."),
    );
    header.insert("referer", "https//www.covery".parse().expect("unsolve the referer value."));
    header.insert("sec-ch-ua", "sec-ch-ua".parse().expect("sec-ch-ua header parse fale"));

    // post 请求体
    let mut data = HashMap::new();
    //用户输入
    get_user_input().await;

    data.insert("prompt", HISTORY_STR.lock().expect("fail getting lock to send message").to_string());

    Ok(client.post("https://free-api.cveoy/v3/completions")
        .headers(header)
        .json(&data)
        .send()
        .await?
        .text()
        .await?
    )
}

async fn print_to_terminal(){
    print!("Please enter your input:");
    let _=io::stdout().flush();
}

更多推荐

rust发送post请求