Skip to content

Commit

Permalink
feature: support http static file server
Browse files Browse the repository at this point in the history
  • Loading branch information
tyrchen committed Mar 24, 2024
1 parent ae4b658 commit c76f146
Show file tree
Hide file tree
Showing 10 changed files with 826 additions and 23 deletions.
738 changes: 725 additions & 13 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.81"
axum = { version = "0.7.4", features = ["http2", "query", "tracing"] }
base64 = "0.22.0"
blake3 = "1.5.1"
clap = { version = "4.5.3", features = ["derive"] }
Expand All @@ -18,4 +19,7 @@ rand = "0.8.5"
serde = { version = "1.0.197", features = ["derive"] }
serde_json = "1.0.114"
serde_yaml = "0.9.33"
tokio = { version = "1.36.0", features = ["rt", "rt-multi-thread", "macros", "net", "fs"] }
tracing = "0.1.40"
tracing-subscriber = { version = "0.3.18", features = ["env-filter"] }
zxcvbn = "2.2.2"
17 changes: 17 additions & 0 deletions src/cli/http.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
use super::verify_path;
use clap::Parser;
use std::path::PathBuf;

#[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: PathBuf,
#[arg(short, long, default_value_t = 8080)]
pub port: u16,
}
7 changes: 5 additions & 2 deletions src/cli/mod.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,17 @@
mod base64;
mod csv;
mod genpass;
mod http;
mod text;

use std::path::{Path, PathBuf};

use self::{csv::CsvOpts, genpass::GenPassOpts};
use clap::Parser;
use std::path::{Path, PathBuf};

pub use self::{
base64::{Base64Format, Base64SubCommand},
csv::OutputFormat,
http::HttpSubCommand,
text::{TextSignFormat, TextSubCommand},
};

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

fn verify_file(filename: &str) -> Result<String, &'static str> {
Expand Down
6 changes: 2 additions & 4 deletions src/cli/text.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
use std::{fmt, path::PathBuf, str::FromStr};

use clap::Parser;

use super::{verify_file, verify_path};
use clap::Parser;
use std::{fmt, path::PathBuf, str::FromStr};

#[derive(Debug, Parser)]
pub enum TextSubCommand {
Expand Down
5 changes: 4 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ mod cli;
mod process;
mod utils;

pub use cli::{Base64Format, Base64SubCommand, Opts, SubCommand, TextSignFormat, TextSubCommand};
pub use cli::{
Base64Format, Base64SubCommand, HttpSubCommand, Opts, SubCommand, TextSignFormat,
TextSubCommand,
};
pub use process::*;
pub use utils::*;
13 changes: 10 additions & 3 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,14 @@ use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
use clap::Parser;
use rcli::{
get_content, get_reader, process_csv, process_decode, process_encode, process_genpass,
process_text_key_generate, process_text_sign, process_text_verify, Base64SubCommand, Opts,
SubCommand, TextSubCommand,
process_http_serve, process_text_key_generate, process_text_sign, process_text_verify,
Base64SubCommand, HttpSubCommand, Opts, SubCommand, 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 @@ -75,6 +77,11 @@ fn main() -> anyhow::Result<()> {
}
}
},
SubCommand::Http(cmd) => match cmd {
HttpSubCommand::Serve(opts) => {
process_http_serve(opts.dir, opts.port).await?;
}
},
}

Ok(())
Expand Down
54 changes: 54 additions & 0 deletions src/process/http_serve.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
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: PathBuf, port: u16) -> Result<()> {
let addr = SocketAddr::from(([0, 0, 0, 0], port));
info!("Serving {:?} on {}", path, addr);

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?;
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() {
(
StatusCode::NOT_FOUND,
format!("File {} note 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,9 +1,11 @@
mod b64;
mod csv_convert;
mod gen_pass;
mod http_serve;
mod text;

pub use b64::{process_decode, process_encode};
pub use csv_convert::process_csv;
pub use gen_pass::process_genpass;
pub use http_serve::process_http_serve;
pub use text::{process_text_key_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/fixtures/ed25519.pk

0 comments on commit c76f146

Please sign in to comment.