2个不稳定版本
0.2.0 | 2023年2月9日 |
---|---|
0.1.0 | 2021年4月10日 |
#465 在 HTTP服务器
654 每月下载量
在 zero4rs 中使用
9KB
51 行
actix-proxy
一个用于actix-web
框架的Rust库。将actix-web
和awc
包粘合在一起。
此库提供IntoHttpResponse
特质,它将awc::ClientResponse
转换为actix_web::HttpResponse
,并通过实现actix_web::ResponseError
,在awc的SendRequestError
和actix-web之间建立桥梁。
有时您需要实现网关或代理,它向某些远程服务发起请求,并将响应转发给发起请求的客户。actix-web 与 awc::Client
HTTP 客户端集成。不幸的是,awc::ClientResponse
,客户端请求的响应类型,没有实现 Responder
特性。因此,您不能从 actix-web 服务器端点返回 awc::ClientResponse
。这使得通过代理端点转发远程位置响应变得困难,需要您将响应转换为实现 Responder
的类型。
使用由 actix-proxy
提供的 IntoHttpResponse
特性,您只需在您的 awc::ClientResponse
上调用 into_http_response
方法,即可将远程服务的响应通过代理转发给原始调用者。
示例
在这个示例中,我们创建了一个基本的 duckduckgo 搜索引擎代理,简单地转发被调用 URL 的路径、查询和片段部分到 duckduckgo
use awc::Client;
use actix_web::{get, web, HttpResponse};
use actix_proxy::{IntoHttpResponse, SendRequestError};
#[get("/{url:.*}")]
async fn proxy(
path: web::Path<(String,)>,
client: web::Data<Client>,
) -> Result<HttpResponse, SendRequestError> {
let (url,) = path.into_inner();
let url = format!("https://duckduckgo.com/{url}");
// here we use `IntoHttpResponse` to return the request to
// duckduckgo back to the client that called this endpoint
Ok(client.get(&url).send().await?.into_http_response())
}
或者,您可以使用 into_wrapped_http_response
方法,避免手动包装结果在 Ok(..)
中
use awc::Client;
use actix_web::{get, web, HttpResponse};
use actix_proxy::{IntoHttpResponse, SendRequestError};
#[get("/{url:.*}")]
async fn proxy(
path: web::Path<(String,)>,
client: web::Data<Client>,
) -> Result<HttpResponse, SendRequestError> {
let (url,) = path.into_inner();
let url = format!("https://duckduckgo.com/{url}");
// here we use `IntoHttpResponse` to return the request to
// duckduckgo back to the client that called this endpoint
client.get(&url).send().await?.into_wrapped_http_response()
}
依赖项
~18–29MB
~532K SLoC