kumarmo2
kumarmo2

Reputation: 1393

Serve Static Files using warp in rust

I am using warp library to make a web app in rust. I am trying to serve the static files. I have read its documentation from Doc.

Here is my code snippet

use serde::Deserialize;
use serde::Serialize;
use warp::path;
use warp::Filter;

#[tokio::main]
async fn main() {
    let static_assets = warp::path("static").and(warp::fs::dir("/www/static"));

    // let routes = get_routes.or(post_routes).or(static_assets).or(file_route);
    let routes = static_assets;

    warp::serve(routes).run(([127, 0, 0, 1], 3030)).await;
}

But When I visit the path localhost:3030/static/index.js, it gives back the 404 response

Here is the file tree

src
├── main.rs
└── www
    └── static
        └── index.js

Upvotes: 2

Views: 5907

Answers (1)

edwardw
edwardw

Reputation: 13942

The error here was surprisingly trivial. The path /www/static is absolute. For it to work, you'll have to have that directory at the root of your file system. By using relative path, it works:

#[tokio::main]
async fn main() {
    let route = warp::path("static").and(warp::fs::dir("www/static"));

    warp::serve(route).run(([127, 0, 0, 1], 3030)).await;
}

Upvotes: 9

Related Questions