在我的actix-web
-server 中,我试图使用reqwest
调用外部服务器,然后将响应返回给用户。
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))
}
这有两个问题:
println!("{:?}", json);
似乎从未运行,或者至少我从未看到任何输出。- 我
_resp
回来了,这是 aFuture
,但我不明白如何等待它解决,以便将字符串传递回Responder
以供参考:
$ curl -data "title=x" "https://jsonplaceholder.typicode.com/posts"
{
"title": "x",
"id": 101
}