first commit

This commit is contained in:
SadlyNotSappho 2023-04-28 12:58:40 -07:00
commit 2de83971b9
5 changed files with 1976 additions and 0 deletions

5
.env.example Normal file
View File

@ -0,0 +1,5 @@
DIRS_LOC=/srv/subdirs
INDEX_PATH=/build
ROOT_NAME=website
IP_ADDR=192.168.0.0:8080

2
.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
/target
.env

1890
Cargo.lock generated Normal file

File diff suppressed because it is too large Load Diff

10
Cargo.toml Normal file
View File

@ -0,0 +1,10 @@
[package]
name = "webserver"
version = "1.0.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
tide = "0.16.0"
async-std = { version = "1.8.0", features = ["attributes"] }

69
src/main.rs Normal file
View File

@ -0,0 +1,69 @@
use std::fs::read_dir;
#[async_std::main]
async fn main() -> tide::Result<()> {
let webdirs = get_env("DIRS_LOC").unwrap();
let index_paths = get_env("INDEX_PATH").unwrap();
let root_name = get_env("ROOT_NAME").unwrap();
let ip_addr = get_env("IP_ADDR").unwrap();
let mut subdirs = read_dir(webdirs.clone())
.unwrap()
.map(|p| {
p.unwrap()
.path()
.display()
.to_string()
.replace(format!("{webdirs}/").as_str(), "")
.trim()
.to_string()
})
.collect::<Vec<String>>();
let mut has_root = false;
if subdirs.contains(&root_name.trim().to_string()) {
subdirs = subdirs
.clone()
.into_iter()
.filter(|r| r != &root_name)
.collect::<Vec<String>>();
has_root = true;
}
let mut app = tide::new();
if has_root {
app.at("/").serve_file(format!(
"{}/{}/{}/index.html",
webdirs, root_name, index_paths
))?;
}
for d in subdirs {
app.at(d.as_str())
.serve_file(format!("{}/{}/{}/index.html", webdirs, d, index_paths))?;
}
app.listen(ip_addr).await?;
Ok(())
}
fn get_env(option: &str) -> Option<String> {
/*
* Get the env var from .env, but if it isn't there, or if the file doesn't exist, get it from the actual env vars
*/
let text_some = std::fs::read_to_string("./.env").ok();
if let Some(text) = text_some {
for line in text.trim().lines().collect::<Vec<&str>>() {
if line.trim().starts_with(option) {
let mut val = line.split('=').collect::<Vec<&str>>();
val.reverse();
val.pop();
val.reverse();
return Some(val.join("=").trim().to_string());
}
}
return std::env::var(option).ok();
} else {
return std::env::var(option).ok();
}
}