2个不稳定版本

0.2.0 2023年2月9日
0.1.0 2021年4月10日

#465HTTP服务器

Download history 80/week @ 2024-03-11 63/week @ 2024-03-18 137/week @ 2024-03-25 212/week @ 2024-04-01 160/week @ 2024-04-08 147/week @ 2024-04-15 162/week @ 2024-04-22 113/week @ 2024-04-29 152/week @ 2024-05-06 201/week @ 2024-05-13 319/week @ 2024-05-20 202/week @ 2024-05-27 198/week @ 2024-06-03 200/week @ 2024-06-10 151/week @ 2024-06-17 96/week @ 2024-06-24

654 每月下载量
zero4rs 中使用

MIT 许可证

9KB
51

actix-proxy

Build Status Codecov Latest Version Downloads Docs License: MIT

一个用于actix-web框架的Rust库。将actix-webawc包粘合在一起。

此库提供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