| // Copyright (c) 2016 The Rouille developers | |
| // Licensed under the Apache License, Version 2.0 | |
| // <LICENSE-APACHE or | |
| // http://www.apache.org/licenses/LICENSE-2.0> or the MIT | |
| // license <LICENSE-MIT or http://opensource.org/licenses/MIT>, | |
| // at your option. All files in the project carrying such | |
| // notice may not be copied, modified, or distributed except | |
| // according to those terms. | |
| extern crate rouille; | |
| use rouille::Response; | |
| fn main() { | |
| // This example shows how to serve static files with rouille. | |
| // Note that like all examples we only listen on `localhost`, so you can't access this server | |
| // from another machine than your own. | |
| println!("Now listening on localhost:8000"); | |
| rouille::start_server("localhost:8000", move |request| { | |
| { | |
| // The `match_assets` function tries to find a file whose name corresponds to the URL | |
| // of the request. The second parameter (`"."`) tells where the files to look for are | |
| // located. | |
| // In order to avoid potential security threats, `match_assets` will never return any | |
| // file outside of this directory even if the URL is for example `/../../foo.txt`. | |
| let response = rouille::match_assets(&request, "."); | |
| // If a file is found, the `match_assets` function will return a response with a 200 | |
| // status code and the content of the file. If no file is found, it will instead return | |
| // an empty 404 response. | |
| // Here we check whether if a file is found, and if so we return the response. | |
| if response.is_success() { | |
| return response; | |
| } | |
| } | |
| // This point of the code is reached only if no static file matched the request URL. | |
| // In a real website you probably want to serve non-static files here (with the `router!` | |
| // macro for example), but here we just return a 404 response. | |
| Response::html("404 error. Try <a href=\"/README.md\"`>README.md</a> or \ | |
| <a href=\"/src/lib.rs\">src/lib.rs</a> for example.") | |
| .with_status_code(404) | |
| }); | |
| } |