Rokit
Rokit

Reputation: 1141

How do I return the response from an API call with actix-web?

I'm trying to get posts from the Rust subreddit and return the response to my frontend.

This is my App:

App::new()
    .data(Client::default())
    .wrap(middleware::Logger::default())
    .service(
        web::resource("/get/rust/posts").route(web::get().to_async(get_rust_posts))
    )

handler function:

fn get_rust_posts(req: HttpRequest, client: web::Data<Client>) -> impl Future<Item = HttpResponse, Error = Error> {
  client.get("http://www.reddit.com/r/rust.json") // create request builder
    .header("User-Agent", "Actix-web")
    .send() // send http request
    .map_err(Error::from)
    .and_then(|resp| {
      // return resp
    })
}

dependencies:

[dependencies]
actix-web = "1.0.7"
futures = "0.1.29"

Upvotes: 2

Views: 1049

Answers (1)

Đorđe Zeljić
Đorđe Zeljić

Reputation: 1825

fn get_rust_posts(req: HttpRequest, client: web::Data<Client>) -> impl Future<Item = HttpResponse, Error = Error> {
  client.get("http://www.reddit.com/r/rust.json") // create request builder
    .header("User-Agent", "Actix-web")
    .send() // send http request
    .map_err(Error::from)
    .and_then(|resp| Ok::<HttpResponse, Error>(HttpResponse::Ok().streaming(resp)))
}

It works on Ubuntu Linux, but doesn't work on Windows at the moment.

Upvotes: 1

Related Questions