Files
axum/examples/reqwest-response/src/main.rs
T

76 lines
2.3 KiB
Rust
Raw Normal View History

//! Run with
//!
//! ```not_rust
//! cargo run -p example-reqwest-response
//! ```
2023-12-17 12:47:45 +01:00
use axum::{
body::{Body, Bytes},
extract::State,
2024-07-30 14:55:15 +08:00
http::StatusCode,
2023-12-17 12:47:45 +01:00
response::{IntoResponse, Response},
routing::get,
Router,
};
use reqwest::Client;
2024-07-30 14:55:15 +08:00
use std::{convert::Infallible, time::Duration};
2023-12-17 12:47:45 +01:00
use tokio_stream::StreamExt;
use tower_http::trace::TraceLayer;
use tracing::Span;
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
2023-12-17 12:47:45 +01:00
#[tokio::main]
async fn main() {
tracing_subscriber::registry()
.with(
tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| "example_reqwest_response=debug,tower_http=debug".into()),
)
.with(tracing_subscriber::fmt::layer())
.init();
2023-12-17 12:47:45 +01:00
let client = Client::new();
2023-12-17 12:47:45 +01:00
let app = Router::new()
2024-07-30 14:55:15 +08:00
.route("/", get(stream_reqwest_response))
2023-12-17 12:47:45 +01:00
.route("/stream", get(stream_some_data))
// Add some logging so we can see the streams going through
.layer(TraceLayer::new_for_http().on_body_chunk(
|chunk: &Bytes, _latency: Duration, _span: &Span| {
tracing::debug!("streaming {} bytes", chunk.len());
},
))
.with_state(client);
2023-12-17 12:47:45 +01:00
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
tracing::debug!("listening on {}", listener.local_addr().unwrap());
axum::serve(listener, app).await.unwrap();
}
2024-07-30 14:55:15 +08:00
async fn stream_reqwest_response(State(client): State<Client>) -> Response {
2023-12-17 12:47:45 +01:00
let reqwest_response = match client.get("http://127.0.0.1:3000/stream").send().await {
Ok(res) => res,
Err(err) => {
tracing::error!(%err, "request failed");
return (StatusCode::BAD_REQUEST, Body::empty()).into_response();
}
};
2024-07-30 14:55:15 +08:00
let mut response_builder = Response::builder().status(reqwest_response.status());
*response_builder.headers_mut().unwrap() = reqwest_response.headers().clone();
2023-12-17 12:47:45 +01:00
response_builder
.body(Body::from_stream(reqwest_response.bytes_stream()))
// This unwrap is fine because the body is empty here
2023-12-17 12:47:45 +01:00
.unwrap()
}
2023-12-17 12:47:45 +01:00
async fn stream_some_data() -> Body {
let stream = tokio_stream::iter(0..5)
.throttle(Duration::from_secs(1))
.map(|n| n.to_string())
.map(Ok::<_, Infallible>);
Body::from_stream(stream)
}