Crates.io | staticdir |
lib.rs | staticdir |
version | 0.3.1 |
source | src |
created_at | 2016-01-06 16:33:49.000426 |
updated_at | 2016-01-06 17:04:36.067566 |
description | Providing list of directory entries for Iron framework |
homepage | https://github.com/franza/staticdir |
repository | https://github.com/franza/staticdir |
max_upload_size | |
id | 3838 |
size | 23,911 |
Serving directory contents for Iron web-framework. Documentation can be found here.
Provides the list of files and directories in a mounted folder. To respond with files use staticfile along with this one. See examples.
Start web server at http://localhost:3000
and mount current directory. List of directory contents will be available as JSON.
extern crate staticdir;
extern crate iron;
use iron::prelude::*;
use staticdir::{ StaticDir, AsJson };
fn main() {
Iron::new(StaticDir::new(".", AsJson)).http("localhost:3000").unwrap();
}
This code will return you
[
{
"file_type": "File",
"file_name": ".gitignore",
"size": 7,
"creation_time": null,
"last_modification_time": 1451939290,
"last_access_time": 1451939309
},
{
"file_type": "File",
"file_name": "Cargo.toml",
"size": 196,
"creation_time": null,
"last_modification_time": 1451939547,
"last_access_time": 1451939547
},
{
"file_type": "Dir",
"file_name": "src",
"size": 4096,
"creation_time": null,
"last_modification_time": 1451939462,
"last_access_time": 1451939462
}
]
You can customize the response using ResponseStrategy
trait. Suppose you need an HTML response instead of JSON:
extern crate staticdir;
extern crate iron;
use iron::prelude::*;
use iron::status::Status;
use staticdir::{ StaticDir, ResponseStrategy };
use std::fs::ReadDir;
use iron::mime::Mime;
struct AsHtml;
fn build_html(dir: ReadDir) -> String {
let mut html = String::new();
for entry in dir {
let entry = entry.unwrap();
html = format!("{}<li>{}</li>", html, entry.file_name().into_string().unwrap());
}
format!("<ul>{}</ul>", html)
}
impl ResponseStrategy for AsHtml {
fn make_response(&self, dir: ReadDir) -> IronResult<Response> {
let html = build_html(dir);
let content_type = "text/html; charset=utf-8".parse::<Mime>().unwrap();
Ok(Response::with((Status::Ok, html, content_type)))
}
}
fn main() {
Iron::new(StaticDir::new(".", AsHtml)).http("localhost:3000").unwrap();
}
This will return an HTML page with next contents
* Cargo.toml
* src
* .git
You can use other modules of iron core bundle like staticfile and mount. In next example you will receive both directory listing and static files.
extern crate staticdir;
extern crate iron;
extern crate mount;
extern crate staticfile;
use iron::prelude::*;
use mount::Mount;
use staticdir::{ StaticDir, AsJson };
use staticfile::Static;
fn main() {
let root = "tests/mount";
let mut handle_statics = Chain::new(Static::new(root));
handle_statics.link_after(StaticDir::new(root, AsJson));
let mut mount = Mount::new();
mount.mount("/static/", handle_statics);
let mut server = Iron::new(mount).http("localhost:3000").unwrap();
}