首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用actix-web调用异步reqwest

使用actix-web调用异步reqwest
EN

Stack Overflow用户
提问于 2019-08-25 12:00:04
回答 1查看 2.8K关注 0票数 3

在我的actix-web-server中,我尝试使用reqwest调用外部服务器,然后将响应返回给用户。

代码语言:javascript
复制
use actix_web::{web, App, HttpResponse, HttpServer, Responder};
use serde::{Deserialize, Serialize};
use futures::Future;
use lazy_static::lazy_static;
use reqwest::r#async::Client as HttpClient;
#[macro_use] extern crate serde_json;

#[derive(Debug, Deserialize)]
struct FormData {
    title: String,
}

#[derive(Debug, Serialize, Deserialize)]
struct Response {
    title: String,
}

fn main() {
    HttpServer::new(|| {
        App::new()
            .route("/validate", web::post().to(validator))
    })
    .bind("127.0.0.1:8000")
    .expect("Can not bind to port 8000")
    .run()
    .unwrap();
}

fn validator(form: web::Form<FormData>) -> impl Responder {
    let _resp = validate(form.title.clone());
    HttpResponse::Ok()
}

pub fn validate(title: String) -> impl Future<Item=String, Error=String> {
    let url = "https://jsonplaceholder.typicode.com/posts";
    lazy_static! {
        static ref HTTP_CLIENT: HttpClient = HttpClient::new();
    }
    HTTP_CLIENT.post(url)
        .json(
            &json!({
                "title": title,
            })
        )
        .send()
        .and_then(|mut resp| resp.json())
        .map(|json: Response| {
            println!("{:?}", json);
            json.title
        })
        .map_err(|error| format!("Error: {:?}", error))
}

这有两个问题:

  1. println!("{:?}", json);似乎从未运行过,至少我从未看到任何输出。
  2. 我得到了_resp,这是一个Future,我不知道我怎么能等待这个问题的解决,这样我就可以把一个字符串传回给Responder

供参考:

代码语言:javascript
复制
$ curl -data "title=x" "https://jsonplaceholder.typicode.com/posts"
{
  "title": "x",
  "id": 101
}
EN

回答 1

Stack Overflow用户

发布于 2019-08-26 19:59:37

要使将来的块得到解决,您必须对其调用wait,但这并不理想。

您可以让您的验证器函数返回一个未来,并在路由中调用to_async而不是to。该框架将在未来问题解决后轮询和发送响应。

此外,您应该考虑使用actix附带的http客户机,并减少应用程序中的一个依赖项。

代码语言:javascript
复制
fn main() {
    HttpServer::new(|| {
        App::new()
            .route("/validate", web::post().to_async(validator))
    })
    .bind("127.0.0.1:8000")
    .expect("Can not bind to port 8000")
    .run()
    .unwrap();
}

fn validator(form: web::Form<FormData>) -> impl Future<Item=String, Error=String> {
    let url = "https://jsonplaceholder.typicode.com/posts";
    lazy_static! {
        static ref HTTP_CLIENT: HttpClient = HttpClient::new();
    }
    HTTP_CLIENT.post(url)
        .json(
            &json!({
                "title": form.title.clone(),
            })
        )
        .send()
        .and_then(|mut resp| resp.json())
        .map(|json: Response| {
            println!("{:?}", json);
            HttpResponse::Ok().body(Body::from(json.title))
        })
        .map_err(|error| format!("Error: {:?}", error))
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57645819

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档