Skip to content

Commit

Permalink
wip
Browse files Browse the repository at this point in the history
  • Loading branch information
chrislearn committed Jan 18, 2025
1 parent 1ed44ae commit 36f0fbe
Show file tree
Hide file tree
Showing 25 changed files with 355 additions and 288 deletions.
1 change: 1 addition & 0 deletions src/templates/classic/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,7 @@ fn write_file(tmpl: &[u8], file_path: &Path, data: &Object) -> Result<()> {
fs::create_dir_all(parent)?;
}
if file_path.extension() == Some(OsStr::new("liquid")) {
println!("rendering liquid file: {:?}", file_path);
let template = liquid::ParserBuilder::with_stdlib()
.build()
.expect("should create liquid parser")
Expand Down
158 changes: 158 additions & 0 deletions template/_base/src/main.rs.liquid
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@

use crate::db::init_db_conn;
use tokio::signal;
use tracing::info;
use crate::middleware::{handle_404::handle_404,cors::cors_middleware};
use crate::routers::router;
use salvo::server::ServerHandle;
use salvo::catcher::Catcher;
use salvo::conn::rustls::{Keycert, RustlsConfig};
use salvo::prelude::*;
mod config;
mod db;
mod beams;
mod utils;
{%- if db_lib == "diesel" %}
mod schema;
{%- endif %}
mod hoops;
mod routers;

use config::ServerConfig;

pub fn config() -> &'static ServerConfig {
&*crate::config::CONFIG
}

#[tokio::main]
async fn main() {
if let Err(e) = dotenv() {
println!("dotenv error: {:?}", e);
}

let raw_config = Figment::new()
.merge(Toml::file(Env::var("APP_CONFIG").as_deref().unwrap_or("config.toml")))
.merge(Env::prefixed("APP_").global());

let config = match raw_config.extract::<ServerConfig>() {
Ok(s) => s,
Err(e) => {
eprintln!("It looks like your config is invalid. The following error occurred: {e}");
std::process::exit(1);
}
};
crate::config::CONFIG.set(config).expect("config should be set");
let config = crate::config();

{%- if db_lib == "diesel" %}
let thread_pool = Arc::new(ScheduledThreadPool::new(conf.db.helper_threads));

let db_primary = {
let db_connection_config = ConnectionConfig {
statement_timeout: config.db.statement_timeout,
};

let db_config = r2d2::Pool::builder()
.max_size(conf.db.pool_size)
.min_idle(conf.db.min_idle)
.connection_timeout(Duration::from_millis(config.db.connection_timeout))
.connection_customizer(Box::new(db_connection_config))
.thread_pool(thread_pool.clone());

DieselPool::new(&config.db.url, &config.db, db_config).unwrap()
};
crate::db::DIESEL_POOL
.set(db_primary)
.expect("diesel pool should be set");
{%- endif %}

crate::db::migrate();

let _guard = config.log.guard();
tracing::info!("log level: {}", &config.log.filter_level);

let service = Service::new(routers::root()).catcher(Catcher::default().hoop(handle_404)).hoop(cors_hoop()));
println!("🔄 {{listen_on}} {}", &config.listen_addr);
if config.ssl {
println!(
"📖 {{open_api_page}}: https://{}/scalar",
config.listen_addr.replace("0.0.0.0", "127.0.0.1")
);
{%- if code_gen == "website" %}
println!("🔑 {{login_page}}: https://{}/login", config.listen_addr.replace("0.0.0.0", "127.0.0.1"));
{%- endif %}
let config = RustlsConfig::new(
Keycert::new()
.cert(CERT_KEY.cert.clone())
.key(CERT_KEY.key.clone()),
);
let acceptor = TcpListener::new(&config.server.listen_addr)
.rustls(config)
.bind()
.await;
let server = Server::new(acceptor);
tokio::spawn(shutdown_signal(server.handle()));
server.serve(service).await;
} else {
println!(
"📖 {{open_api_page}}: http://{}/scalar",
config.listen_addr.replace("0.0.0.0", "127.0.0.1")
);
{%- if code_gen == "website" %}
println!("🔑 {{login_page}}: http://{}/login", config().server.listen_addr.replace("0.0.0.0", "127.0.0.1"));
{%- endif %}
let acceptor = TcpListener::new(&config.listen_addr).bind().await;
let server = Server::new(acceptor);
tokio::spawn(shutdown_signal(server.handle()));
server.serve(service).await;
}
}

async fn shutdown_signal(handle: ServerHandle) {
let ctrl_c = async {
signal::ctrl_c()
.await
.expect("failed to install Ctrl+C handler");
};

#[cfg(unix)]
let terminate = async {
signal::unix::signal(signal::unix::SignalKind::terminate())
.expect("failed to install signal handler")
.recv()
.await;
};

#[cfg(not(unix))]
let terminate = std::future::pending::<()>();

tokio::select! {
_ = ctrl_c => info!("ctrl_c signal received"),
_ = terminate => info!("terminate signal received"),
}
handle.stop_graceful(std::time::Duration::from_secs(60));
}

#[cfg(test)]
mod tests {
use salvo::prelude::*;
use salvo::test::{ResponseExt, TestClient};

use crate::config;

#[tokio::test]
async fn test_hello_world() {
let service = Service::new(super::router());

let content = TestClient::get(format!(
"http://{}",
&config().address.replace("0.0.0.0", "127.0.0.1")
))
.send(&service)
.await
.take_string()
.await
.unwrap();
assert_eq!(content, "Hello World from salvo");
}
}
2 changes: 1 addition & 1 deletion templates/classic/_base/Cargo.toml.liquid
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ rbdc-pg = { "version": "4"}
{%- endif %}
{%- if db_type == "mysql" %}
rbdc-mysql = { version = "4"}
{% endif %}
{%- endif %}
{%- if db_type == "sqlite" %}
rbdc-sqlite = { version = "4"}
{%- endif %}
Expand Down
52 changes: 26 additions & 26 deletions templates/classic/_base/README.md.liquid
Original file line number Diff line number Diff line change
Expand Up @@ -9,59 +9,59 @@ cargo test
```
# {{ tip_title }}
- {{ password_tip }}
{% if db_lib == "seaorm" and db_type == "sqlx" %}
{%- if db_lib == "seaorm" and db_type == "sqlx" %}
- {{ config_tip }}
{% endif %}
{%- endif %}
# {{ orm_title }}
{% if db_type == "sqlx" %}
{%- if db_type == "sqlx" %}
{{ sqlx_website }}
## sqlx_cli
{{ sqlx_cli }} https://github.com/launchbadge/sqlx/blob/main/sqlx-cli/README.md
## {{ initialization }}
{% if db_type == "sqlx" %}
{%- if db_type == "sqlx" %}
{{ seleted_sqlite }}
{% else %}
{%- else %}
- {{ initialization_sqlx_cli_not_sqlite }}
{% endif %}
{% endif %}
{% if db_lib == "seaorm" %}
{%- endif %}
{%- endif %}
{%- if db_lib == "seaorm" %}
{{ seaorm_website }}
## seaorm_cli
{{ seaorm_cli_website }}
## {{ initialization }}
{%endif%}
{% if db_lib == "seaorm" %}
{% if db_type == "sqlx" %}
{%- endif %}
{%- if db_lib == "seaorm" %}
{%- if db_type == "sqlx" %}
{{ seleted_sqlite }}
{% else %}
{%- else %}
- {{ initialization_seaorm_cli_not_sqlite }}
{%endif%}
{%endif%}
{% if db_lib == "diesel" %}
{%- endif %}
{%- endif %}
{%- if db_lib == "diesel" %}
{{ diesel_website }}
## diesel_cli
{{ diesel_cli_website }}
## {{ initialization }}
{% if db_lib == "sqlite" %}
{%- if db_lib == "sqlite" %}
{{ seleted_sqlite }}
{%else%}
{%- else %}
- {{ initialization_diesel_cli_not_sqlite }}
{%endif%}
{%endif%}
{% if db_lib == "rbatis" %}
{%- endif %}
{%- endif %}
{%- if db_lib == "rbatis" %}
{{ rbatis_website }}
## {{ initialization }}
{% if db_lib == "sqlite" %}
{%- if db_lib == "sqlite" %}
{{ seleted_sqlite }}
{%else%}
{%- else %}
- {{ initialization_rbatis_cli_not_sqlite }}
{%endif%}
{%endif%}
{% if db_type == "mongodb" %}
{%- endif%}
{%- endif %}
{%- if db_type == "mongodb" %}
{{ mongodb_website }}
## {{ nitialization }}
- {{ mongodb_usage_import_user_dat }}
{%endif%}
{%- endif %}

# {{ about_salvo }}
{{ about_salvo_text }}
Binary file modified templates/classic/_base/assets/favicon.ico
Binary file not shown.
2 changes: 1 addition & 1 deletion templates/classic/_base/config.toml.liquid
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ pool_size = 1

[jwt]
secret = "yoursecret"
expire = 3600
expiry = 3600

[log]
file_name = "app.log"
Expand Down
2 changes: 1 addition & 1 deletion templates/classic/_base/src/config/log.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ const FORMAT_COMPACT: &str = "compact";
const FORMAT_JSON: &str = "json";
const FORMAT_FULL: &str = "full";

#[derive(Deserialize, Default, Clone, Debug)]
#[derive(Deserialize, Clone, Debug)]
pub struct LogConfig {
#[serde(default = "default_filter_level")]
pub filter_level: String,
Expand Down
108 changes: 0 additions & 108 deletions templates/classic/_base/src/config/mod.rs.liquid

This file was deleted.

Loading

0 comments on commit 36f0fbe

Please sign in to comment.