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

62 lines
1.5 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
2022-04-29 18:53:41 +02:00
//! cd examples && cargo run -p example-reverse-proxy
2021-10-19 23:52:19 +03:00
//! ```
use axum::{
2022-08-17 17:13:31 +02:00
extract::State,
2021-10-19 23:52:19 +03:00
http::{uri::Uri, Request, Response},
routing::get,
2022-03-01 00:39:22 +01:00
Router,
2021-10-19 23:52:19 +03:00
};
use hyper::{client::HttpConnector, Body};
use std::net::SocketAddr;
2021-10-19 23:52:19 +03:00
type Client = hyper::client::Client<HttpConnector, Body>;
#[tokio::main]
async fn main() {
tokio::spawn(server());
let client = Client::new();
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 addr = SocketAddr::from(([127, 0, 0, 1], 4000));
println!("reverse proxy listening on {}", addr);
axum::Server::bind(&addr)
.serve(app.into_make_service())
.await
.unwrap();
}
2022-08-17 17:13:31 +02:00
async fn handler(State(client): State<Client>, mut req: Request<Body>) -> Response<Body> {
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);
let uri = format!("http://127.0.0.1:3000{}", path_query);
*req.uri_mut() = Uri::try_from(uri).unwrap();
client.request(req).await.unwrap()
}
async fn server() {
let app = Router::new().route("/", get(|| async { "Hello, world!" }));
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
println!("server listening on {}", addr);
axum::Server::bind(&addr)
.serve(app.into_make_service())
.await
.unwrap();
}