Skip to content

Commit

Permalink
feature: add file http serve
Browse files Browse the repository at this point in the history
  • Loading branch information
listenLearning committed Jun 26, 2024
1 parent 58e697e commit 07754ae
Show file tree
Hide file tree
Showing 9 changed files with 757 additions and 8 deletions.
662 changes: 659 additions & 3 deletions Cargo.lock

Large diffs are not rendered by default.

4 changes: 4 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ license = "MIT"

[dependencies]
anyhow = "1.0.86"
axum = { version = "0.7.5", features = ["http2", "query", "tracing"] }
b3sum = "1.5.1"
base64 = "0.22.1"
blake3 = "1.5.1"
Expand All @@ -19,4 +20,7 @@ rand = "0.8.5"
serde = { version = "1.0.203", features = ["derive"] }
serde_json = "1.0.117"
serde_yaml = "0.9.34"
tokio = { version = "1.38.0", features = ["rt", "rt-multi-thread", "net", "macros", "fs"] }
tracing = "0.1.40"
tracing-subscriber = { version = "0.3.18", features = ["env-filter"] }
zxcvbn = "2"
19 changes: 19 additions & 0 deletions src/cli/http.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
// use std::path::PathBuf;

use clap::Parser;

use super::verify_path;

#[derive(Debug, Parser)]
pub enum HttpSubCommand {
#[command(about = "Serve a directory over http")]
Serve(HttpServeOpts),
}

#[derive(Debug, Parser)]
pub struct HttpServeOpts {
#[arg(short, long, value_parser=verify_path, default_value=".")]
pub dir: String,
#[arg(short, long, default_value_t = 8080)]
pub port: u16,
}
4 changes: 4 additions & 0 deletions src/cli/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
mod base64;
mod csv;
mod genpass;
mod http;
mod text;

use clap::Parser;
Expand All @@ -11,6 +12,7 @@ use std::path::Path;
pub use self::{
base64::{Base64Format, Base64SubCommand},
csv::OutputFormat,
http::HttpSubCommand,
text::{TextSignFormat, TextSubCommand},
};

Expand All @@ -31,6 +33,8 @@ pub enum SubCommand {
Base64(Base64SubCommand),
#[command(subcommand)]
Text(TextSubCommand),
#[command(subcommand)]
Http(HttpSubCommand),
}

fn verify_file(file: &str) -> Result<String, String> {
Expand Down
5 changes: 3 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,11 @@ mod process;
mod utils;

pub use cli::{
Base64Format, Base64SubCommand, Opts, OutputFormat, SubCommand, TextSignFormat, TextSubCommand,
Base64Format, Base64SubCommand, HttpSubCommand, Opts, OutputFormat, SubCommand, TextSignFormat,
TextSubCommand,
};
pub use process::{
process_csv, process_decode, process_encode, process_gen_pass, process_generate,
process_text_sign, process_text_verify,
process_http_serve, process_text_sign, process_text_verify,
};
pub use utils::get_reader;
13 changes: 10 additions & 3 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,14 @@ use std::fs;
use clap::Parser;
use rcli::{
process_csv, process_decode, process_encode, process_gen_pass, process_generate,
process_text_sign, process_text_verify, Base64SubCommand, Opts, SubCommand, TextSignFormat,
TextSubCommand,
process_http_serve, process_text_sign, process_text_verify, Base64SubCommand, HttpSubCommand,
Opts, SubCommand, TextSignFormat, TextSubCommand,
};
use zxcvbn::zxcvbn;

fn main() -> anyhow::Result<()> {
#[tokio::main]
async fn main() -> anyhow::Result<()> {
tracing_subscriber::fmt::init();
let opts = Opts::parse();
match opts.cmd {
SubCommand::Csv(opts) => {
Expand Down Expand Up @@ -66,6 +68,11 @@ fn main() -> anyhow::Result<()> {
}
}
},
SubCommand::Http(cmd) => match cmd {
HttpSubCommand::Serve(opts) => {
process_http_serve(&opts.dir, opts.port).await?;
}
},
}
Ok(())
}
53 changes: 53 additions & 0 deletions src/process/http_serve.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
use anyhow::Result;
use axum::{
extract::{Path, State},
http::StatusCode,
routing::get,
Router,
};
use std::{net::SocketAddr, path::PathBuf, sync::Arc};
use tracing::{info, warn};

#[derive(Debug)]
struct HttpServeState {
path: PathBuf,
}

pub async fn process_http_serve(path: &str, port: u16) -> Result<()> {
let addr = SocketAddr::from(([0, 0, 0, 0], port));
info!("Serving {:?} on port {}", path, addr);
let path = PathBuf::from(path);
let state = HttpServeState { path };
// axum router
let router = Router::new()
.route("/*path", get(file_handler))
.with_state(Arc::new(state));
let listener = tokio::net::TcpListener::bind(addr).await?;
axum::serve(listener, router).await.unwrap();
Ok(())
}

async fn file_handler(
State(state): State<Arc<HttpServeState>>,
Path(path): Path<String>,
) -> (StatusCode, String) {
let p = std::path::Path::new(&state.path).join(path);
info!("Reading file {:?}", p);
if !p.exists() {
return (
StatusCode::NOT_FOUND,
format!("File not found:{:?}", p.display()),
);
} else {
match tokio::fs::read_to_string(p).await {
Ok(content) => {
info!("Read {} bytes", content.len());
(StatusCode::OK, content)
}
Err(e) => {
warn!("Error reading file {:?}", e);
(StatusCode::INTERNAL_SERVER_ERROR, e.to_string())
}
}
}
}
2 changes: 2 additions & 0 deletions src/process/mod.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
mod b64;
mod csv_convert;
mod gen_pass;
mod http_serve;
mod text;

pub use csv_convert::process_csv;
pub use gen_pass::process_gen_pass;

pub use b64::{process_decode, process_encode};
pub use http_serve::process_http_serve;
pub use text::{process_generate, process_text_sign, process_text_verify};
3 changes: 3 additions & 0 deletions test.rest
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
### Test index page

GET http://localhost:8080/Cargo.toml

0 comments on commit 07754ae

Please sign in to comment.