chore: clean commented code and request_http thread

This commit is contained in:
Jesús Pérez 2023-09-24 11:23:01 +01:00
parent e8b9344891
commit ecd6c2150f

View File

@ -5,7 +5,6 @@
//! ```
// use axum_auth::AuthBasic;
#![cfg_attr(docsrs, feature(doc_cfg))]
#![doc(html_logo_url = "../images/docserver.svg")]
#[doc = include_str!("../README.md")]
@ -17,31 +16,23 @@ use rand_core::{SeedableRng,OsRng, RngCore};
use rand_chacha::ChaCha8Rng;
use axum::{
extract::Host,
handler::HandlerWithoutStateExt,
routing::MethodRouter,
http::{
StatusCode,
Uri,
header::HeaderValue,
Method,
},
BoxError,
//BoxError,
Extension,
response::Redirect,
// http::Request, handler::HandlerWithoutStateExt, http::StatusCode, routing::get, Router,
Router,
};
use tower::ServiceBuilder;
use axum_server::tls_rustls::RustlsConfig;
use std::{
net::SocketAddr,
path::PathBuf,
sync::{Arc, Mutex},
path::Path,
};
// use std::net::SocketAddr;
// use tower::ServiceExt;
use tower_http::{
services::{ServeDir,ServeFile},
trace::TraceLayer,
@ -96,8 +87,6 @@ pub const PKG_NAME: &str = env!("CARGO_PKG_NAME");
pub const PKG_VERSION: &str = env!("CARGO_PKG_VERSION");
// const PKG_VERSION: Option&<&'static str> = option_env!("CARGO_PKG_VERSION");
// const PKG_DESCRIPTION: &str = env!("CARGO_PKG_DESCRIPTION");
// const COOKIE_NAME: &str = "lc_authz";
// const COOKIE_SEP: &str = ":tk:";
const GIT_VERSION: &str = ""; //git_version::git_version!();
static GIT_VERSION_NAME: Lazy<String> = Lazy::new(|| {
format!("v{} [build: {}]",PKG_VERSION,GIT_VERSION)
@ -112,13 +101,6 @@ pub const USERS_FILESTORE: &str = "users";
pub const OPENID_USERS_FILESTORE: &str = "openid_users";
pub const DEFAULT_ROLES: &str = "user";
#[derive(Clone, Copy)]
struct Ports {
http: u16,
https: u16,
}
pub fn route(path: &str, method_router: MethodRouter) -> Router {
Router::new().route(path, method_router)
}
@ -149,8 +131,6 @@ async fn main() {
.with(tracing_subscriber::fmt::layer())
.init();
// you can convert handler function to service
// let store = FileStore {
// sess_path: "store".to_owned(),
// ses_file: "data".to_owned(),
@ -228,15 +208,6 @@ async fn main() {
std::process::exit(2);
};
let ports = Ports {
http: 7878,
https: 8800,
};
// optional: spawn a second server to redirect http requests to this server
if config.protocol.contains("http") {
tokio::spawn(redirect_http_to_https(ports));
}
let mut origins: Vec<HeaderValue> = Vec::new();
for itm in config.allow_origin.to_owned() {
match HeaderValue::from_str(itm.as_str()) {
@ -324,15 +295,6 @@ async fn main() {
.layer(Extension(Arc::new(Mutex::new(random))))
.fallback_service(handle_404.into_service())
;
// if !config.html_path.is_empty() && !config.html_url.is_empty() {
// MAIN_URL.set(config.server.html_url.to_owned()).unwrap_or_default();
// println!("SpaRoutert local path {} to {}",&config.server.html_path,&config.server.html_url);
// web_router = web_router.merge(
// )
// .fallback(fallback);
// }
if config.verbose > 2 { dbg!("{:?}",&origins); }
if config.allow_origin.len() > 0 {
web_router = web_router.layer(CorsLayer::new()
@ -345,12 +307,6 @@ async fn main() {
tracing::debug!("listening on {} url: {}://{}", addr, config.protocol, config.hostport);
println!("listening on {} url: {}://{}", addr, config.protocol, config.hostport);
if config.protocol.as_str() == "http" {
// let app_with_middleware = middleware.layer(app);
// run https server
//let addr = SocketAddr::from(([127, 0, 0, 1], ports.http));
//tracing::debug!("listening on {}", addr);
// .into_make_service_with_connect_info::<SocketAddr>()
//.into_make_service_with_connect_info::<AppConnectInfo>()
if config.verbose > 0 {
web_router = web_router.layer(TraceLayer::new_for_http());
}
@ -362,15 +318,6 @@ async fn main() {
.await
.unwrap();
} else {
// configure certificate and private key used by https
// let tls_config = RustlsConfig::from_pem_file(
// PathBuf::from(env!("CARGO_MANIFEST_DIR"))
// .join("self_signed_certs")
// .join("cert.pem"),
// PathBuf::from(env!("CARGO_MANIFEST_DIR"))
// .join("self_signed_certs")
// .join("key.pem"),
// )
let tls_config = RustlsConfig::from_pem_file(
PathBuf::from(&config.cert_file),
PathBuf::from(&config.key_file)
@ -380,11 +327,6 @@ async fn main() {
eprintln!("Error TLS config: {}",e);
std::process::exit(2)
});
//let addr = SocketAddr::from(([127, 0, 0, 1], ports.https));
//tracing::debug!("listening on {}", addr);
//let app_with_middleware = middleware.layer(app);
// apply the layer around the whole `Router`middleware.layer(app);
// .serve(web_router.into_make_service())
if config.verbose > 0 {
web_router = web_router.layer(TraceLayer::new_for_http());
}
@ -397,166 +339,4 @@ async fn main() {
.await
.unwrap();
}
/*
// let port = 3002;
// tokio::join!(
// serve(using_serve_dir(), 3001),
// serve(using_serve_dir_with_assets_fallback(), 3002),
// serve(using_serve_dir_only_from_root_via_fallback(), 3003),
// serve(using_serve_dir_with_handler_as_service(), 3004),
// serve(two_serve_dirs(), 3005),
// serve(calling_serve_dir_from_a_handler(), 3006),
// );
//let addr = SocketAddr::from(([127, 0, 0, 1], port));
let addr = SocketAddr::from(([192,168,1,4], port));
let listener = tokio::net::TcpListener::bind(addr).await.unwrap();
tracing::debug!("listening on {}", listener.local_addr().unwrap());
// let _ = axum::Server::bind(&addr)
// .serve(
// // router.layer(TraceLayer::new_for_http())
// //router.into_make_service_with_connect_info::<SocketAddr>()
// router.into_make_service()
// )
// .await
// .expect("server failed");
// axum_server::bind(addr)
// .serve(router.into_make_service())
// .await
// .unwrap();
axum::serve(listener, router.layer(TraceLayer::new_for_http()))
.await
.unwrap();
// let _ = axum::Server::bind(&addr)
// .serve(
// app.layer(TraceLayer::new_for_http()).into_make_service()
// // web_router.into_make_service_with_connect_info::<SocketAddr>()
// // web_router.into_make_service()
// )
// .await
// .unwrap();
*/
}
async fn redirect_http_to_https(ports: Ports) {
fn make_https(host: String, uri: Uri, ports: Ports) -> Result<Uri, BoxError> {
let mut parts = uri.into_parts();
parts.scheme = Some(axum::http::uri::Scheme::HTTPS);
if parts.path_and_query.is_none() {
parts.path_and_query = Some("/".parse().unwrap());
}
let https_host = host.replace(&ports.http.to_string(), &ports.https.to_string());
parts.authority = Some(https_host.parse()?);
Ok(Uri::from_parts(parts)?)
}
let redirect = move |Host(host): Host, uri: Uri| async move {
match make_https(host, uri, ports) {
Ok(uri) => Ok(Redirect::permanent(&uri.to_string())),
Err(error) => {
tracing::warn!(%error, "failed to convert URI to HTTPS");
Err(StatusCode::BAD_REQUEST)
}
}
};
let addr = SocketAddr::from(([127, 0, 0, 1], ports.http));
let listener = tokio::net::TcpListener::bind(addr).await.unwrap();
tracing::debug!("listening on {}", listener.local_addr().unwrap());
axum::serve(listener, redirect.into_make_service_with_connect_info::<SocketAddr>())
.await
.unwrap();
}
/*
fn using_serve_dir() -> Router {
// serve the file in the "assets" directory under `/assets`
Router::new().nest_service("/assets", ServeDir::new("assets"))
}
fn using_serve_dir_with_assets_fallback() -> Router {
// `ServeDir` allows setting a fallback if an asset is not found
// so with this `GET /assets/doesnt-exist.jpg` will return `index.html`
// rather than a 404
let serve_dir = ServeDir::new("assets").not_found_service(ServeFile::new("assets/index.html"));
Router::new()
.route("/foo", get(|| async { "Hi from /foo" }))
.nest_service("/assets", serve_dir.clone())
.fallback_service(serve_dir)
}
fn using_serve_dir_only_from_root_via_fallback() -> Router {
// you can also serve the assets directly from the root (not nested under `/assets`)
// by only setting a `ServeDir` as the fallback
let serve_dir = ServeDir::new("assets").not_found_service(ServeFile::new("assets/index.html"));
Router::new()
.route("/foo", get(|| async { "Hi from /foo" }))
.fallback_service(serve_dir)
}
fn using_serve_dir_with_handler_as_service() -> Router {
async fn handle_404() -> (StatusCode, &'static str) {
(StatusCode::NOT_FOUND, "Not found")
}
// you can convert handler function to service
let service = handle_404.into_service();
let serve_dir = ServeDir::new("assets").not_found_service(service);
Router::new()
.route("/foo", get(|| async { "Hi from /foo" }))
.fallback_service(serve_dir)
}
fn two_serve_dirs() -> Router {
// you can also have two `ServeDir`s nested at different paths
let serve_dir_from_assets = ServeDir::new("assets");
let serve_dir_from_dist = ServeDir::new("dist");
Router::new()
.nest_service("/assets", serve_dir_from_assets)
.nest_service("/dist", serve_dir_from_dist)
}
#[allow(clippy::let_and_return)]
fn calling_serve_dir_from_a_handler() -> Router {
// via `tower::Service::call`, or more conveniently `tower::ServiceExt::oneshot` you can
// call `ServeDir` yourself from a handler
Router::new().nest_service(
"/foo",
get(|request: Request<_>| async {
let service = ServeDir::new("assets");
let result = service.oneshot(request).await;
result
}),
)
}
async fn serve(app: Router, port: u16) {
let addr = SocketAddr::from(([127, 0, 0, 1], port));
let listener = tokio::net::TcpListener::bind(addr).await.unwrap();
tracing::debug!("listening on {}", listener.local_addr().unwrap());
axum::serve(listener, app.layer(TraceLayer::new_for_http()))
.await
.unwrap();
// let _ = axum::Server::bind(&addr)
// .serve(
// app.layer(TraceLayer::new_for_http()).into_make_service()
// // web_router.into_make_service_with_connect_info::<SocketAddr>()
// // web_router.into_make_service()
// )
// .await
// .unwrap();
}
*/
}