daoyi_cloud_common/
lib.rs

1pub use salvo::catcher::Catcher;
2pub use salvo::conn::rustls::{Keycert, RustlsConfig};
3pub use salvo::prelude::*;
4pub use salvo::server::ServerHandle;
5pub use serde::Serialize;
6pub use tokio;
7pub use tokio::signal;
8pub use tracing::info;
9pub use dotenvy;
10
11pub mod common_test_routers_example;
12pub mod config;
13pub mod db;
14pub mod hoops;
15pub mod models;
16pub mod utils;
17
18pub mod error;
19
20pub use error::AppError;
21pub mod redis;
22pub use redis::RedisClient;
23
24pub type AppResult<T> = Result<T, AppError>;
25pub type JsonResult<T> = Result<Json<T>, AppError>;
26pub type EmptyResult = Result<Json<Empty>, AppError>;
27
28pub fn json_ok<T>(data: T) -> JsonResult<T> {
29    Ok(Json(data))
30}
31#[derive(Serialize, ToSchema, Clone, Copy, Debug)]
32pub struct Empty {}
33pub fn empty_ok() -> JsonResult<Empty> {
34    Ok(Json(Empty {}))
35}
36
37pub async fn shutdown_signal(handle: ServerHandle) {
38    let ctrl_c = async {
39        signal::ctrl_c()
40            .await
41            .expect("failed to install Ctrl+C handler");
42    };
43
44    #[cfg(unix)]
45    let terminate = async {
46        signal::unix::signal(signal::unix::SignalKind::terminate())
47            .expect("failed to install signal handler")
48            .recv()
49            .await;
50    };
51
52    #[cfg(not(unix))]
53    let terminate = std::future::pending::<()>();
54
55    tokio::select! {
56        _ = ctrl_c => info!("ctrl_c signal received"),
57        _ = terminate => info!("terminate signal received"),
58    }
59    handle.stop_graceful(std::time::Duration::from_secs(60));
60}
61
62#[cfg(test)]
63mod tests {
64    use config::{Env, Format, Toml};
65    use salvo::prelude::*;
66    use salvo::test::{ResponseExt, TestClient};
67
68    use crate::config;
69
70    #[tokio::test]
71    async fn test_hello_world() {
72        let profile = Env::var("APP_PROFILE").unwrap_or_else(|| "test".to_string());
73        let data = Toml::file(
74            Env::var("APP_CONFIG")
75                .as_deref()
76                .unwrap_or(format!("config-{}.toml", profile).as_str()),
77        );
78        config::common_init(Some(data));
79
80        let service = Service::new(crate::common_test_routers_example::root());
81
82        let content = TestClient::get(format!(
83            "http://{}",
84            config::get().listen_addr.replace("0.0.0.0", "127.0.0.1")
85        ))
86        .send(&service)
87        .await
88        .take_string()
89        .await
90        .unwrap();
91        assert_eq!(content, "Hello World from salvo");
92    }
93}