Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use actix_web::client::Client in Actix-web 4.0

I use crate scylla that use tokio 1, so i must use crate actix-web 4.0 beta. Now i have problem that use actix_web::client::Client show error :

3 | use actix_web::client::Client;
  |                ^^^^^^ could not find `client` in `actix_web`

i want to hit API inside actix handler with this code :

pub(crate) async fn proses_mapmatching(data: web::Data<AppState>) -> impl Responder {

    let client = Client::default();

    let res = client.post("http://localhost:8002/trace_route")
        .send()
        .await
        .unwrap()
        .body()
        .await;

    println!("Response: {:?}", res);

    HttpResponse::Ok().body(format!("Hello {:?}", res))
}

Any idea to still use actix-web 4 with reqest post insede handler function ? Thanks

ANSWER CODE with AWC - Thanks to Mr. @kmdreko

pub(crate) async fn proses_mapmatching(data: web::Data<AppState>) -> impl Responder {

    let mut client = awc::Client::default();
    let response = client.post("http://localhost:8002/trace_route")
        .send_body("Raw body contents")
        .await;

    println!("Response: {:?}", response.unwrap().body().await);

    HttpResponse::Ok().body(format!("Hello {}!", rows.len()))
}

like image 250
Pamungkas Jayuda Avatar asked Oct 18 '25 06:10

Pamungkas Jayuda


2 Answers

This is mentioned in the actix_web Changes.md for v4.0:

The client mod was removed. Clients should now use awc directly.

The actix_web::client module has long since largely been a wrapper around the awc crate ever since the 1.0 release, but it seems they now want to separate them entirely.

The types from awc should be near identical to those exposed in prior actix_web releases, however if you're using it with actix_web:4.0 (currently in beta) then you'll want to use awc:3.0 (currently in beta) for compatibility.

like image 199
kmdreko Avatar answered Oct 20 '25 22:10

kmdreko


this is what I used to run the AWC Example

Cargo.toml

[dependencies]
openssl = "0.10.38"
actix-web = "4.0.0-beta.12"
awc = { version = "3.0.0-beta.11", features = [ "openssl" ] }

main.rs

use awc::Client;

#[actix_web::main]
async fn main() {
    let client = Client::new();

    let res = client
         .get("http://www.rust-lang.org")    // <- Create request builder
         .insert_header(("User-Agent", "Actix-web"))
         .send()                             // <- Send http request
         .await;

    println!("Response: {:?}", res);        // <- server http response
}

bests!

like image 45
IHF Avatar answered Oct 20 '25 23:10

IHF