Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Custom route prefix #728

Merged
merged 7 commits into from
Feb 6, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion src/args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,12 @@ pub struct CliArgs {
)]
pub auth: Vec<auth::RequiredAuth>,

/// Use a specific route prefix
#[clap(long = "route-prefix")]
pub route_prefix: Option<String>,

/// Generate a random 6-hexdigit route
#[clap(long = "random-route")]
#[clap(long = "random-route", conflicts_with("route-prefix"))]
pub random_route: bool,

/// Do not follow symbolic links
Expand Down
18 changes: 9 additions & 9 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,8 @@ pub struct MiniserveConfig {
/// Show hidden files
pub show_hidden: bool,

/// Enable random route generation
pub random_route: Option<String>,
/// Route prefix; Either empty or prefixed with slash
pub route_prefix: String,

/// Randomly generated favicon route
pub favicon_route: String,
Expand Down Expand Up @@ -131,16 +131,16 @@ impl MiniserveConfig {
]
};

let random_route = if args.random_route {
Some(nanoid::nanoid!(6, &ROUTE_ALPHABET))
} else {
None
let route_prefix = match (args.route_prefix, args.random_route) {
(Some(prefix), _) => format!("/{}", prefix.trim_matches('/')),
(_, true) => format!("/{}", nanoid::nanoid!(6, &ROUTE_ALPHABET)),
_ => "".to_owned(),
};

// Generate some random routes for the favicon and css so that they are very unlikely to conflict with
// real files.
let favicon_route = nanoid::nanoid!(10, &ROUTE_ALPHABET);
let css_route = nanoid::nanoid!(10, &ROUTE_ALPHABET);
let favicon_route = format!("{}/{}", route_prefix, nanoid::nanoid!(10, &ROUTE_ALPHABET));
let css_route = format!("{}/{}", route_prefix, nanoid::nanoid!(10, &ROUTE_ALPHABET));

let default_color_scheme = args.color_scheme;
let default_color_scheme_dark = args.color_scheme_dark;
Expand Down Expand Up @@ -197,7 +197,7 @@ impl MiniserveConfig {
path_explicitly_chosen,
no_symlinks: args.no_symlinks,
show_hidden: args.hidden,
random_route,
route_prefix,
favicon_route,
css_route,
default_color_scheme,
Expand Down
8 changes: 3 additions & 5 deletions src/listing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ pub fn directory_listing(
let serve_path = req.path();

let base = Path::new(serve_path);
let random_route_abs = format!("/{}", conf.random_route.clone().unwrap_or_default());
let random_route_abs = format!("/{}", conf.route_prefix);
let is_root = base.parent().is_none() || Path::new(&req.path()) == Path::new(&random_route_abs);

let encoded_dir = match base.strip_prefix(random_route_abs) {
Expand All @@ -180,10 +180,8 @@ pub fn directory_listing(
let decoded = percent_decode_str(&encoded_dir).decode_utf8_lossy();

let mut res: Vec<Breadcrumb> = Vec::new();
let mut link_accumulator = match &conf.random_route {
Some(random_route) => format!("/{}/", random_route),
None => "/".to_string(),
};

let mut link_accumulator = format!("{}/", &conf.route_prefix);

let mut components = Path::new(&*decoded).components().peekable();

Expand Down
14 changes: 4 additions & 10 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -165,10 +165,7 @@ async fn run(miniserve_config: MiniserveConfig) -> Result<(), ContextualError> {
Some(_) => format!("https://{}", addr),
None => format!("http://{}", addr),
})
.map(|url| match miniserve_config.random_route {
Some(ref random_route) => format!("{}/{}", url, random_route),
None => url,
})
.map(|url| format!("{}{}", url, miniserve_config.route_prefix))
.collect::<Vec<_>>()
};

Expand All @@ -189,13 +186,10 @@ async fn run(miniserve_config: MiniserveConfig) -> Result<(), ContextualError> {
.app_data(inside_config.clone())
.wrap_fn(errors::error_page_middleware)
.wrap(middleware::Logger::default())
.route(
&format!("/{}", inside_config.favicon_route),
web::get().to(favicon),
)
.route(&format!("/{}", inside_config.css_route), web::get().to(css))
.route(&inside_config.favicon_route, web::get().to(favicon))
.route(&inside_config.css_route, web::get().to(css))
.service(
web::scope(inside_config.random_route.as_deref().unwrap_or(""))
web::scope(&inside_config.route_prefix)
.wrap(middleware::Condition::new(
!inside_config.auth.is_empty(),
actix_web::middleware::Compat::new(HttpAuthentication::basic(
Expand Down
11 changes: 4 additions & 7 deletions src/renderer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,7 @@ pub fn page(
return raw(entries, is_root);
}

let upload_route = match conf.random_route {
Some(ref random_route) => format!("/{}/upload", random_route),
None => "/upload".to_string(),
};
let upload_route = format!("{}/upload", &conf.route_prefix);
let (sort_method, sort_order) = (query_params.sort, query_params.order);

let upload_action = build_upload_action(&upload_route, encoded_dir, sort_method, sort_order);
Expand Down Expand Up @@ -481,8 +478,8 @@ fn page_header(title: &str, file_upload: bool, favicon_route: &str, css_route: &
meta http-equiv="X-UA-Compatible" content="IE=edge";
meta name="viewport" content="width=device-width, initial-scale=1";

link rel="icon" type="image/svg+xml" href={ "/" (favicon_route) };
link rel="stylesheet" href={ "/" (css_route) };
link rel="icon" type="image/svg+xml" href={ (favicon_route) };
link rel="stylesheet" href={ (css_route) };

title { (title) }

Expand Down Expand Up @@ -578,7 +575,7 @@ pub fn render_error(
p { (error) }
}
// WARN don't expose random route!
@if conf.random_route.is_none() {
@if conf.route_prefix.is_empty() {
div.error-nav {
a.error-back href=(return_address) {
"Go back to file listing"
Expand Down
1 change: 1 addition & 0 deletions tests/bind.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ fn bind_ipv4_ipv6(
#[case(&["-i", "0.0.0.0"])]
#[case(&["-i", "::", "-i", "0.0.0.0"])]
#[case(&["--random-route"])]
#[case(&["--route-prefix", "/prefix"])]
fn validate_printed_urls(tmpdir: TempDir, port: u16, #[case] args: &[&str]) -> Result<(), Error> {
let mut child = Command::cargo_bin("miniserve")?
.arg(tmpdir.path())
Expand Down
15 changes: 15 additions & 0 deletions tests/serve_request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -260,3 +260,18 @@ fn serve_index_instead_of_404_in_spa_mode(

Ok(())
}

#[rstest]
#[case(server(&["--route-prefix", "foobar"]))]
#[case(server(&["--route-prefix", "/foobar/"]))]
fn serves_requests_with_route_prefix(#[case] server: TestServer) -> Result<(), Error> {
let url_without_route = server.url();
let status = reqwest::blocking::get(url_without_route)?.status();
assert_eq!(status, StatusCode::NOT_FOUND);

let url_with_route = server.url().join("foobar")?;
let status = reqwest::blocking::get(url_with_route)?.status();
assert_eq!(status, StatusCode::OK);

Ok(())
}