Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Rust file server (Linux)
- // In this example you can upload and download files make a log of last download and view it
- // also you can invoke system commands and print the results as HTML
- //
- // ===== Cargo.toml =====
- // [dependencies]
- // tide = "0.16.0"
- // async-std = { version = "1.6.0", features = ["attributes"] }
- // serde = { version = "1.0", features = ["derive"] }
- // tempfile = "3.5.0"
- // csv = "1.1"
- // chrono = { version = "0.4", features = ["serde"] }
- //
- use std::io::Error as IoError;
- use std::path::Path;
- use std::sync::Arc;
- use async_std::{fs::OpenOptions, io};
- use tempfile::TempDir;
- use tide::prelude::*;
- use tide::{Body, Request, Response, StatusCode, Redirect};
- use std::{env};
- use std::fs::File;
- use std::path::PathBuf;
- use csv::Writer;
- use chrono::{Utc, Local, DateTime, Date};
- use std::process::Command;
- #[derive(Clone)]
- struct TempDirState {
- tempdir: Arc<TempDir>,
- }
- impl TempDirState {
- fn try_new() -> Result<Self, IoError> {
- Ok(Self {
- tempdir: Arc::new(tempfile::tempdir()?),
- })
- }
- fn path(&self) -> &Path {
- self.tempdir.path()
- }
- }
- #[async_std::main]
- async fn main() -> Result<(), IoError> {
- let mut app = tide::with_state(TempDirState::try_new()?);
- app.with(tide::log::LogMiddleware::new());
- app.at(":file")
- // $ curl -T ./a.txt localhost:8080 # this writes the file to a temp directory
- //
- .put(|req: Request<TempDirState>| async move {
- let path = req.param("file")?;
- let p = req.param("file").unwrap().to_string();
- let fs_path = req.state().path().join(path);
- let file = OpenOptions::new()
- .create(true)
- .write(true)
- .open(&fs_path)
- .await?;
- let bytes_written = io::copy(req, file).await?;
- println!("file written bytes {}", bytes_written);
- let export_folder = env::var("EXPORT_FOLDER").map_err(|_| {
- io::Error::new(io::ErrorKind::NotFound, "set env variable EXPORT_FOLDER to export path")
- })?;
- // write to a csv the file and time we downloaded it
- let file_path = PathBuf::from(export_folder).join("input.csv");
- let utc_datetime: DateTime<Utc> = Utc::now();
- println!("{}", utc_datetime);
- let file = File::create(&file_path)?;
- let mut writer = Writer::from_writer(file);
- let f_desc = "file uploaded was ".to_string();
- let text = Utc::now().format("%Y-%m-%d %H:%M:%S:%Z").to_string();
- let records = vec![
- vec![&f_desc, &p, &text],
- ];
- for record in records {
- writer.write_record(record)?;
- }
- writer.flush()?;
- Ok(json!({ "bytes": bytes_written }))
- })
- // $ curl localhost:8080/a.txt # this reads the file from the same temp directory and logs it to a file
- //
- .get(|req: Request<TempDirState>| async move {
- let path = req.param("file")?;
- let p = req.param("file").unwrap().to_string();
- let fs_path = req.state().path().join(path);
- let export_folder = env::var("EXPORT_FOLDER").map_err(|_| {
- io::Error::new(io::ErrorKind::NotFound, "set env variable EXPORT_FOLDER to export path")
- })?;
- // write to a csv the file and time we downloaded it
- let file_path = PathBuf::from(export_folder).join("output.csv");
- let utc_datetime: DateTime<Utc> = Utc::now();
- println!("{}", utc_datetime);
- if let Ok(body) = Body::from_file(fs_path).await {
- let file = File::create(&file_path)?;
- let mut writer = Writer::from_writer(file);
- let f_desc = "file downloaded was ".to_string();
- let text = Utc::now().format("%Y-%m-%d %H:%M:%S:%Z").to_string();
- let records = vec![
- vec![&f_desc, &p, &text],
- ];
- for record in records {
- writer.write_record(record)?;
- }
- writer.flush()?;
- Ok(body.into())
- } else {
- Ok(Response::new(StatusCode::NotFound))
- }
- });
- // curl localhost:8080/showlastdownload
- //
- app.at("/showlastdownload").get(|_req: Request<TempDirState>| async move {
- let export_folder = env::var("EXPORT_FOLDER").map_err(|_| {
- io::Error::new(io::ErrorKind::NotFound, "set env variable EXPORT_FOLDER to export path")
- })?;
- // write to a csv the file and time we downloaded it
- let file_path = PathBuf::from(export_folder).join("output.csv");
- let output = Command::new("/bin/cat")
- //.arg("/home/mark/enfile/output.csv") <---- if you dont want to use the env variable
- .arg(&file_path)
- .output()
- .expect("failed to execute process");
- println!("status: {}", output.status);
- println!("stdout: {}", String::from_utf8_lossy(&output.stdout));
- println!("stderr: {}", String::from_utf8_lossy(&output.stderr));
- Ok(tide::Response::builder(200)
- .body(format!("<html><h2>Download csv :-, {}!</h2></html>",
- String::from_utf8_lossy(&output.stdout)))
- .header("Server", "tide")
- .content_type(tide::http::mime::HTML)
- .build())
- });
- // curl localhost:8080/showlastupload
- //
- app.at("/showlastupload").get(|_req: Request<TempDirState>| async move {
- let export_folder = env::var("EXPORT_FOLDER").map_err(|_| {
- io::Error::new(io::ErrorKind::NotFound, "set env variable EXPORT_FOLDER to export path")
- })?;
- // write to a csv the file and time we downloaded it
- let file_path = PathBuf::from(export_folder).join("input.csv");
- let output = Command::new("/bin/cat")
- //.arg("/home/mark/enfile/input.csv") <---- if you dont want to use the env variable
- .arg(&file_path)
- .output()
- .expect("failed to execute process");
- println!("status: {}", output.status);
- println!("stdout: {}", String::from_utf8_lossy(&output.stdout));
- println!("stderr: {}", String::from_utf8_lossy(&output.stderr));
- Ok(tide::Response::builder(200)
- .body(format!("<html><h2>Upload csv :-, {}!</h2></html>",
- String::from_utf8_lossy(&output.stdout)))
- .header("Server", "tide")
- .content_type(tide::http::mime::HTML)
- .build())
- });
- // shows the contents of the EXPORT_FOLDER variable
- // e.g. EXPORT_FOLDER=/usr/nik/myfles; export EXPORT_FOLDER
- // curl localhost:8080/showdirectory
- //
- app.at("/showdirectory").get(|_req: Request<TempDirState>| async move {
- //let dname = req.param("dir").unwrap().to_string();
- let export_folder = env::var("EXPORT_FOLDER").map_err(|_| {
- io::Error::new(io::ErrorKind::NotFound, "set env variable EXPORT_FOLDER to export path")
- })?;
- let output = Command::new("/bin/ls")
- .args(&["-l", "-a", &export_folder])
- .output()
- .expect("failed to start `ls`");
- println!("status: {}", output.status);
- println!("stdout: {}", String::from_utf8_lossy(&output.stdout));
- println!("stderr: {}", String::from_utf8_lossy(&output.stderr));
- Ok(tide::Response::builder(200)
- .body(format!("<html><h2>Download csv :-, {}!</h2></html>",
- String::from_utf8_lossy(&output.stdout)))
- .header("Server", "tide")
- .content_type(tide::http::mime::HTML)
- .build())
- });
- // curl localhost:8080/rd
- //
- app.at("/rd")
- .get(Redirect::new("https://www.youtube.com/watch?v=GGk_KrRyXLo"));
- app.listen("127.0.0.1:8080").await?;
- Ok(())
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement