Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Rust initialize class using reqwest and default headers

I am pretty new in Rust and I am trying to biuld a class to instantiate a client to will get info from an API. My class is like this:

use reqwest::Error;
use reqwest::header::{HeaderMap, HeaderValue, CONTENT_TYPE};
use reqwest::blocking::Client;
use reqwest::header;
use std::env;

struct GateClient {
    host: &'static str,
    prefix: &'static str,
    url: &'static str,
    key: String,
    secret: String,
    client: Client,
}

impl GateClient {
    fn new(key: &str, secret: &str) -> Self {
        let mut headers = header::HeaderMap::new();
        headers.insert(CONTENT_TYPE, HeaderValue::from_static("Accept=application/json"));
        headers.insert(CONTENT_TYPE, HeaderValue::from_static("Content-Type=application/json"));
    
        let client = Client::builder().default_headers(headers).build().unwrap();
        
        GateClient {
            host: "https://api.gateio.ws",
            prefix: "/api/v4",
            url: "/spot/currency_pairs/",
            key: key.to_string(),
            secret: secret.to_string(),
            client,
        }
    }

    fn get(&self, arg: &str) -> Result<String, reqwest::Error> {
        let url = format!("{}{}{}{}", self.host, self.prefix, self.url, arg);
        println!("{}", url);
        let response = self.client.get(&url).send()?;
        response.text()
    }
}

#[tokio::main]
async fn main() -> Result<(), Error> {
    env::set_var("RUST_BACKTRACE", "Full");

    let client = GateClient::new("a", "b");
    let response = client.get("ETH_USDT").unwrap();
    println!("{}", response);

    Ok(())
}

Although, it seems that I have an issue cause my program keeps crashing.

thread ‘main’ panicked at
/home/nicolas/.cargo/registry/src/index.crates.io-6f17d22bba15001f/tokio-1.36.0/src/runtime/blocking/shutdown.rs:51:21: Cannot drop a runtime in a context where blocking is not allowed. This
happens when a runtime is dropped from within an asynchronous context.
stack backtrace: 0: rust_begin_unwind

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Could someone tell me what’s my error please?

>Solution :

You are not allowed to use reqwest‘s blocking API (or really, any blocking API) inside asynchronous code. Either use all-blocking:

use reqwest::blocking::Client;
use reqwest::header;
use reqwest::header::{HeaderMap, HeaderValue, CONTENT_TYPE};
use reqwest::Error;
use std::env;

struct GateClient {
    host: &'static str,
    prefix: &'static str,
    url: &'static str,
    key: String,
    secret: String,
    client: Client,
}

impl GateClient {
    fn new(key: &str, secret: &str) -> Self {
        let mut headers = header::HeaderMap::new();
        headers.insert(
            CONTENT_TYPE,
            HeaderValue::from_static("Accept=application/json"),
        );
        headers.insert(
            CONTENT_TYPE,
            HeaderValue::from_static("Content-Type=application/json"),
        );

        let client = Client::builder().default_headers(headers).build().unwrap();

        GateClient {
            host: "https://api.gateio.ws",
            prefix: "/api/v4",
            url: "/spot/currency_pairs/",
            key: key.to_string(),
            secret: secret.to_string(),
            client,
        }
    }

    fn get(&self, arg: &str) -> Result<String, reqwest::Error> {
        let url = format!("{}{}{}{}", self.host, self.prefix, self.url, arg);
        println!("{}", url);
        let response = self.client.get(&url).send()?;
        response.text()
    }
}

fn main() -> Result<(), Error> {
    env::set_var("RUST_BACKTRACE", "Full");

    let client = GateClient::new("a", "b");
    let response = client.get("ETH_USDT").unwrap();
    println!("{}", response);

    Ok(())
}

Or all-async:

use reqwest::Client;
use reqwest::header;
use reqwest::header::{HeaderMap, HeaderValue, CONTENT_TYPE};
use reqwest::Error;
use std::env;

struct GateClient {
    host: &'static str,
    prefix: &'static str,
    url: &'static str,
    key: String,
    secret: String,
    client: Client,
}

impl GateClient {
    fn new(key: &str, secret: &str) -> Self {
        let mut headers = header::HeaderMap::new();
        headers.insert(
            CONTENT_TYPE,
            HeaderValue::from_static("Accept=application/json"),
        );
        headers.insert(
            CONTENT_TYPE,
            HeaderValue::from_static("Content-Type=application/json"),
        );

        let client = Client::builder().default_headers(headers).build().unwrap();

        GateClient {
            host: "https://api.gateio.ws",
            prefix: "/api/v4",
            url: "/spot/currency_pairs/",
            key: key.to_string(),
            secret: secret.to_string(),
            client,
        }
    }

    async fn get(&self, arg: &str) -> Result<String, reqwest::Error> {
        let url = format!("{}{}{}{}", self.host, self.prefix, self.url, arg);
        println!("{}", url);
        let response = self.client.get(&url).send().await?;
        response.text().await
    }
}

#[tokio::main]
async fn main() -> Result<(), Error> {
    env::set_var("RUST_BACKTRACE", "Full");

    let client = GateClient::new("a", "b");
    let response = client.get("ETH_USDT").await.unwrap();
    println!("{}", response);

    Ok(())
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading