在我的actix-web
服务器中,我试图使用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
,即Future
,但我不知道如何等待解决,因此我可以将字符串传回Responder
< / li>
供参考:
$ curl -data "title=x" "https://jsonplaceholder.typicode.com/posts"
{
"title": "x",
"id": 101
}
答案 0 :(得分:0)
要在将来的问题解决之前将其阻止,您必须在其上调用wait
,但这并不理想。
您可以使验证器函数返回未来,并在路由调用to_async
中代替to
。将来解决时,该框架将轮询并发送响应。
此外,您还应该考虑使用actix web随附的http客户端,并减少应用程序中的一种依赖关系。
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))
}