Skip to content
Myr

main.rs

This file

Path

examples/reverse-proxy/src/main.rs

67 lines · 1.8 KiB · Rust

Last changed by

Fix return types of serve futures (#3601)Jonas Plattebefore adoptionf3a95d7

History of this file

Take it

1//! Reverse proxy listening in "localhost:4000" will proxy all requests to "localhost:3000"2//! endpoint.3//!4//! Run with5//!6//! ```not_rust7//! cargo run -p example-reverse-proxy8//! ```910use axum::{11    body::Body,12    extract::{Request, State},13    http::uri::Uri,14    response::{IntoResponse, Response},15    routing::get,16    Router,17};18use hyper::StatusCode;19use hyper_util::{client::legacy::connect::HttpConnector, rt::TokioExecutor};2021type Client = hyper_util::client::legacy::Client<HttpConnector, Body>;2223#[tokio::main]24async fn main() {25    tokio::spawn(server());2627    let client: Client =28        hyper_util::client::legacy::Client::<(), ()>::builder(TokioExecutor::new())29            .build(HttpConnector::new());3031    let app = Router::new().route("/", get(handler)).with_state(client);3233    let listener = tokio::net::TcpListener::bind("127.0.0.1:4000")34        .await35        .unwrap();36    println!("listening on {}", listener.local_addr().unwrap());37    axum::serve(listener, app).await;38}3940async fn handler(State(client): State<Client>, mut req: Request) -> Result<Response, StatusCode> {41    let path = req.uri().path();42    let path_query = req43        .uri()44        .path_and_query()45        .map(|v| v.as_str())46        .unwrap_or(path);4748    let uri = format!("http://127.0.0.1:3000{path_query}");4950    *req.uri_mut() = Uri::try_from(uri).unwrap();5152    Ok(client53        .request(req)54        .await55        .map_err(|_| StatusCode::BAD_REQUEST)?56        .into_response())57}5859async fn server() {60    let app = Router::new().route("/", get(|| async { "Hello, world!" }));6162    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")63        .await64        .unwrap();65    println!("listening on {}", listener.local_addr().unwrap());66    axum::serve(listener, app).await;67}