Files
axum/examples/reverse-proxy/src/main.rs
T

65 lines
1.6 KiB
Rust
Raw Normal View History

2021-10-19 23:52:19 +03:00
//! Reverse proxy listening in "localhost:4000" will proxy all requests to "localhost:3000"
//! endpoint.
//!
//! Run with
//!
//! ```not_rust
//! cargo run -p example-reverse-proxy
2021-10-19 23:52:19 +03:00
//! ```
use axum::{
2023-03-12 16:37:32 +01:00
body::Body,
2023-03-20 21:02:40 +01:00
extract::{Request, State},
http::uri::Uri,
2023-03-12 16:37:32 +01:00
response::{IntoResponse, Response},
routing::get,
2022-03-01 00:39:22 +01:00
Router,
2021-10-19 23:52:19 +03:00
};
2023-07-01 23:08:49 +02:00
use hyper::{client::HttpConnector, StatusCode};
2021-10-19 23:52:19 +03:00
type Client = hyper::client::Client<HttpConnector, Body>;
#[tokio::main]
async fn main() {
tokio::spawn(server());
2023-03-12 16:37:32 +01:00
let client: Client = hyper::Client::builder().build(HttpConnector::new());
2021-10-19 23:52:19 +03:00
2022-11-18 12:02:58 +01:00
let app = Router::new().route("/", get(handler)).with_state(client);
2021-10-19 23:52:19 +03:00
let listener = tokio::net::TcpListener::bind("127.0.0.1:4000")
2021-10-19 23:52:19 +03:00
.await
.unwrap();
println!("listening on {}", listener.local_addr().unwrap());
axum::serve(listener, app).await.unwrap();
2021-10-19 23:52:19 +03:00
}
2023-07-01 23:08:49 +02:00
async fn handler(State(client): State<Client>, mut req: Request) -> Result<Response, StatusCode> {
2021-10-19 23:52:19 +03:00
let path = req.uri().path();
let path_query = req
.uri()
.path_and_query()
.map(|v| v.as_str())
.unwrap_or(path);
2023-09-19 02:51:57 -04:00
let uri = format!("http://127.0.0.1:3000{path_query}");
2021-10-19 23:52:19 +03:00
*req.uri_mut() = Uri::try_from(uri).unwrap();
2023-07-01 23:08:49 +02:00
Ok(client
.request(req)
.await
.map_err(|_| StatusCode::BAD_REQUEST)?
.into_response())
2021-10-19 23:52:19 +03:00
}
async fn server() {
let app = Router::new().route("/", get(|| async { "Hello, world!" }));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
2021-10-19 23:52:19 +03:00
.await
.unwrap();
println!("listening on {}", listener.local_addr().unwrap());
axum::serve(listener, app).await.unwrap();
2021-10-19 23:52:19 +03:00
}