Skip to content

Example of how to return a file dynamically #608

Answered by davidpdrsn
ufoscout asked this question in Q&A
Discussion options

You must be logged in to vote

You can do this:

use axum::{
    body::StreamBody,
    http::{header, StatusCode},
    response::{Headers, IntoResponse},
    routing::get,
    Router,
};
use std::net::SocketAddr;
use tokio_util::io::ReaderStream;

#[tokio::main]
async fn main() {
    let app = Router::new().route("/", get(handler));

    let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
    axum::Server::bind(&addr)
        .serve(app.into_make_service())
        .await
        .unwrap();
}

async fn handler() -> impl IntoResponse {
    // `File` implements `AsyncRead`
    let file = match tokio::fs::File::open("Cargo.toml").await {
        Ok(file) => file,
        Err(err) => return Err((StatusCode::NOT_FOUND, format!

Replies: 8 comments 34 replies

Comment options

You must be logged in to vote
14 replies
@AThilenius
Comment options

@danielecr
Comment options

@davidpdrsn
Comment options

@simonsan
Comment options

@davidpdrsn
Comment options

Answer selected by ufoscout
Comment options

You must be logged in to vote
3 replies
@AThilenius
Comment options

@MidKnightXI
Comment options

@davidpdrsn
Comment options

Comment options

You must be logged in to vote
4 replies
@davidpdrsn
Comment options

@hanusek
Comment options

@davidpdrsn
Comment options

@hanusek
Comment options

Comment options

You must be logged in to vote
5 replies
@davidpdrsn
Comment options

@MidKnightXI
Comment options

@davidpdrsn
Comment options

@rogusdev
Comment options

@davidpdrsn
Comment options

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
5 replies
@davidpdrsn
Comment options

@Magicloud
Comment options

@AThilenius
Comment options

@davidpdrsn
Comment options

@AThilenius
Comment options

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
3 replies
@jplatte
Comment options

@Ali-Javanmardi
Comment options

@Ali-Javanmardi
Comment options

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
Converted from issue

This discussion was converted from issue #606 on December 10, 2021 22:41.