adding files
This commit is contained in:
parent
bef4d46aff
commit
99a4dab1b0
91
src/main copy.rs
Normal file
91
src/main copy.rs
Normal file
@ -0,0 +1,91 @@
|
||||
use futures_util::TryStreamExt;
|
||||
use hyper::service::{make_service_fn, service_fn};
|
||||
use hyper::HeaderMap;
|
||||
use hyper::{body::HttpBody as _, Client};
|
||||
use hyper::{Body, Method, Request, Response, Server, StatusCode};
|
||||
use std::fmt::Write as FmtWrite;
|
||||
use std::io::Write as IoWrite;
|
||||
use tokio::io::{self, AsyncWriteExt as _};
|
||||
|
||||
/// This is our service handler. It receives a Request, routes on its
|
||||
/// path, and returns a Future of a Response.
|
||||
async fn echo(req: Request<Body>) -> Result<Response<Body>> {
|
||||
println!("{}", req.uri().path().clone());
|
||||
match req.method() {
|
||||
// Serve some instructions at /
|
||||
&Method::GET => {
|
||||
let headers = req.headers();
|
||||
let proxy_to_host = headers.get("http-to-server").unwrap();
|
||||
let params: HashMap<String, String> = request
|
||||
.uri()
|
||||
.query()
|
||||
.map(|v| {
|
||||
url::form_urlencoded::parse(v.as_bytes())
|
||||
.into_owned()
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_else(HashMap::new);
|
||||
let url = format!(
|
||||
"{}{}",
|
||||
proxy_to_host.to_str().unwrap(),
|
||||
req.uri().path().clone()
|
||||
);
|
||||
let url = url.parse::<hyper::Uri>().unwrap();
|
||||
let proxy_res = get_response(url, headers).await;
|
||||
Ok(Response::new(Body::from(proxy_res)))
|
||||
}
|
||||
|
||||
&Method::POST => {
|
||||
let chunk_stream = req.into_body().map_ok(|chunk| {
|
||||
chunk
|
||||
.iter()
|
||||
.map(|byte| byte.to_ascii_uppercase())
|
||||
.collect::<Vec<u8>>()
|
||||
});
|
||||
Ok(Response::new(Body::wrap_stream(chunk_stream)))
|
||||
}
|
||||
|
||||
_ => {
|
||||
let mut not_found = Response::default();
|
||||
*not_found.status_mut() = StatusCode::NOT_FOUND;
|
||||
Ok(not_found)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type Result<T> = std::result::Result<T, Box<dyn std::error::Error + Send + Sync>>;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<()> {
|
||||
let addr = ([127, 0, 0, 1], 3000).into();
|
||||
|
||||
let service = make_service_fn(|_| async { Ok::<_, hyper::Error>(service_fn(echo)) });
|
||||
|
||||
let server = Server::bind(&addr).serve(service);
|
||||
|
||||
println!("Listening on http://{}", addr);
|
||||
|
||||
server.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn get_response(url: hyper::Uri, headers: &HeaderMap) -> String {
|
||||
let client = Client::new();
|
||||
let mut res = client.get(url).await.ok().unwrap();
|
||||
println!("Response: {}", res.status());
|
||||
println!("Headers: {:#?}\n", res.headers());
|
||||
|
||||
let mut response_val = Vec::new();
|
||||
while let Some(next) = res.data().await {
|
||||
let chunk = next.ok();
|
||||
std::io::Write::write_all(&mut response_val, &chunk.unwrap());
|
||||
//io::stdout().write_all(&chunk).await?;
|
||||
//write!(&mut response_val, "{}", &chunk).await?;
|
||||
}
|
||||
|
||||
let s = String::from_utf8(response_val).unwrap();
|
||||
println!("\n\nDone!");
|
||||
|
||||
s
|
||||
}
|
||||
184
src/main.rs
Normal file
184
src/main.rs
Normal file
@ -0,0 +1,184 @@
|
||||
use fasthash::mum;
|
||||
use rocket::data::{Data, ToByteUnit};
|
||||
use rocket::http::Status;
|
||||
use rocket::request;
|
||||
use rocket::request::Outcome;
|
||||
use rocket::request::{FromRequest, Request};
|
||||
use rocket::routes;
|
||||
use rocket::{get, post};
|
||||
use std::env;
|
||||
use std::fs;
|
||||
use std::io::{self, Write};
|
||||
use std::path::PathBuf;
|
||||
use tokio::io::AsyncReadExt;
|
||||
use std::time::SystemTime;
|
||||
|
||||
use reqwest;
|
||||
|
||||
#[rocket::main]
|
||||
async fn main() {
|
||||
println!("{}", get_cache_dir());
|
||||
rocket::build()
|
||||
.mount("/", routes![files, files_post])
|
||||
.launch()
|
||||
.await;
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
enum HeaderError {
|
||||
NotFound,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Token(String);
|
||||
#[rocket::async_trait]
|
||||
|
||||
impl<'r> FromRequest<'r> for Token {
|
||||
type Error = HeaderError;
|
||||
|
||||
async fn from_request(request: &'r Request<'_>) -> request::Outcome<Self, Self::Error> {
|
||||
let map = request.headers().clone();
|
||||
let x = request.uri();
|
||||
|
||||
for h in map.into_iter() {
|
||||
println!("{} : {}", h.name(), h.value());
|
||||
}
|
||||
let token = request.headers().get_one("http-to-server");
|
||||
match token {
|
||||
Some(token) => {
|
||||
// check validity
|
||||
Outcome::Success(Token(format!("{}{}", token.to_string(), x)))
|
||||
}
|
||||
// token does not exist
|
||||
None => Outcome::Failure((Status::Unauthorized, HeaderError::NotFound)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn hashkey(seed: String) -> u64 {
|
||||
mum::hash64(seed)
|
||||
}
|
||||
|
||||
fn get_cache_dir() -> String {
|
||||
let path = env::current_dir();
|
||||
let cpath = format!("{}/cache", path.unwrap().parent().unwrap().display());
|
||||
println!("{}",cpath);
|
||||
return cpath;
|
||||
}
|
||||
|
||||
#[get("/<file..>")]
|
||||
async fn files(token: Token, file: PathBuf) -> Option<String> {
|
||||
let h = hashkey(token.0.clone());
|
||||
println!("HASH:P{}", h);
|
||||
io::stdout().flush().unwrap();
|
||||
|
||||
let metadata = fs::metadata(format!("{}/{}", get_cache_dir(),h)).unwrap();
|
||||
|
||||
if let Ok(time) = metadata.created() {
|
||||
println!("{:?}", time);
|
||||
} else {
|
||||
println!("Not supported on this platform or filesystem");
|
||||
}
|
||||
|
||||
let cached_data = fs::read_to_string(format!("{}/{}", get_cache_dir(),h));
|
||||
|
||||
match cached_data {
|
||||
Ok(_) => {
|
||||
println!("CACHED");
|
||||
io::stdout().flush().unwrap();
|
||||
|
||||
std::option::Option::Some(cached_data.unwrap())
|
||||
}
|
||||
Err(_) => {
|
||||
let url = token.0.clone();
|
||||
println!("Retrieving: {}", url);
|
||||
io::stdout().flush().unwrap();
|
||||
|
||||
let resp = reqwest::get(url).await.unwrap().text().await;
|
||||
|
||||
match resp {
|
||||
Err(why) => {
|
||||
println!("Error: {}", why);
|
||||
io::stdout().flush().unwrap();
|
||||
|
||||
std::option::Option::Some(String::new())
|
||||
}
|
||||
Ok(_) => {
|
||||
println!("{:#?}", resp);
|
||||
io::stdout().flush().unwrap();
|
||||
|
||||
let fw = fs::write(
|
||||
format!("{}/{}", get_cache_dir(), h),
|
||||
resp.as_ref().unwrap().clone(),
|
||||
);
|
||||
match fw {
|
||||
Ok(_) => {}
|
||||
Err(e) => {
|
||||
println!("error writing to disk {}", e);
|
||||
io::stdout().flush().unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
std::option::Option::Some(resp.unwrap())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[post("/<file..>", data = "<data>")]
|
||||
async fn files_post(token: Token, file: PathBuf, data: Data<'_>) -> Option<String> {
|
||||
let mut post_data = String::new();
|
||||
data.open(2048.kibibytes())
|
||||
.read_to_string(&mut post_data)
|
||||
.await;
|
||||
println!("{}{}", token.0.clone(), post_data.clone());
|
||||
let h = hashkey(format!("{}{}", token.0.clone(), post_data));
|
||||
println!("HASH:{}", h);
|
||||
io::stdout().flush().unwrap();
|
||||
|
||||
let metadata = fs::metadata(format!("{}/{}", get_cache_dir(),h)).unwrap();
|
||||
|
||||
if let Ok(time) = metadata.created() {
|
||||
println!("{:?}", time);
|
||||
} else {
|
||||
println!("Not supported on this platform or filesystem");
|
||||
}
|
||||
let cached_data = fs::read_to_string(format!("{}/{}", get_cache_dir(),h));
|
||||
|
||||
match cached_data {
|
||||
Ok(_) => {
|
||||
println!("CACHED");
|
||||
std::option::Option::Some(cached_data.unwrap())
|
||||
}
|
||||
_ => {
|
||||
let url = token.0.clone();
|
||||
println!("Retrieving: {}", url);
|
||||
io::stdout().flush().unwrap();
|
||||
|
||||
let client = reqwest::Client::new();
|
||||
let res = client.post(url).body(post_data).send().await;
|
||||
|
||||
let x = match res {
|
||||
Err(why) => {
|
||||
println!("Error : {}", why);
|
||||
(String::new())
|
||||
}
|
||||
Ok(resp) => {
|
||||
let x = resp.text().await.unwrap();
|
||||
let fw = fs::write(format!("{}/{}", get_cache_dir(),h), x.clone());
|
||||
|
||||
match fw {
|
||||
Ok(_) => {}
|
||||
Err(_) => {
|
||||
println!("error writing to disk");
|
||||
}
|
||||
}
|
||||
(x)
|
||||
}
|
||||
};
|
||||
|
||||
std::option::Option::Some(x)
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Reference in New Issue
Block a user