Skip to content

Commit a7af89f

Browse files
replace lazy_static with rust standrad library OnceCell fixed issue #5
1 parent 482bd24 commit a7af89f

File tree

14 files changed

+1196
-859
lines changed

14 files changed

+1196
-859
lines changed

Cargo.lock

+1,119-779
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
[workspace]
2-
2+
resolver = "2"
33
members = [
44
# common for some functions to share
55
"common",

common/Cargo.toml

+1-2
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
name = "common"
33
version = "0.1.0"
44
authors = ["Tianlang <[email protected]>"]
5-
edition = "2021"
5+
edition = "2024"
66

77
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
88

@@ -12,7 +12,6 @@ log = "0.4"
1212
log4rs="1"
1313
blake2 = "0.10" # https://github.com/RustCrypto/hashes
1414
data-encoding = "2"
15-
lazy_static = "1.4"
1615
diesel = {version ="2", features=["mysql","r2d2"]}
1716
uuid = { version = "1", features = ["serde", "v4"] }
1817
serde = { version = "1", features = ["derive"] }

common/src/config_util.rs

+24-24
Original file line numberDiff line numberDiff line change
@@ -1,44 +1,44 @@
1+
use std::sync::OnceLock;
12
use config::{Config, ConfigBuilder, Value};
2-
use lazy_static::lazy_static;
3-
4-
lazy_static! {
5-
pub static ref APP_CONFIG: Config = {
6-
let config_default = Config::builder()
7-
.add_source(config::File::with_name("conf/application"))
8-
.build()
9-
.expect("请提供配置文件confg/application.yaml");
10-
let mut config_builder = Config::builder().add_source(config_default.clone());
11-
config_builder = match config_default.get_string("tl.app.mode") {
12-
Ok(value) => {
13-
let config_file_name = format!("conf/application_{}", value);
14-
config_builder.add_source(config::File::with_name(&config_file_name))
15-
}
16-
_ => config_builder.add_source(config::File::with_name("conf/application_dev")),
17-
};
18-
config_builder
19-
.add_source(config::Environment::with_prefix("TL_APP"))
20-
.build()
21-
.unwrap()
3+
static APP_CONFIG: OnceLock<Config> = OnceLock::new();
4+
pub fn get_app_config() -> &'static Config {
5+
APP_CONFIG.get_or_init(init_app_config)
6+
}
7+
fn init_app_config() -> Config {
8+
let config_default = Config::builder()
9+
.add_source(config::File::with_name("conf/application"))
10+
.build()
11+
.expect("请提供配置文件confg/application.yaml");
12+
let mut config_builder = Config::builder().add_source(config_default.clone());
13+
config_builder = match config_default.get_string("tl.app.mode") {
14+
Ok(value) => {
15+
let config_file_name = format!("conf/application_{}", value);
16+
config_builder.add_source(config::File::with_name(&config_file_name))
17+
}
18+
_ => config_builder.add_source(config::File::with_name("conf/application_dev")),
2219
};
20+
config_builder
21+
.add_source(config::Environment::with_prefix("TL_APP"))
22+
.build()
23+
.unwrap()
2324
}
24-
2525
pub fn is_prod() -> bool {
26-
match APP_CONFIG.get_string("tl.app.mode") {
26+
match get_app_config().get_string("tl.app.mode") {
2727
Ok(value) if value == "prod" => true,
2828
_ => false,
2929
}
3030
}
3131

3232
pub fn need_approval() -> bool {
33-
match APP_CONFIG.get_bool("tl.app.approval.enable") {
33+
match get_app_config().get_bool("tl.app.approval.enable") {
3434
Ok(value) => true,
3535
_ => false,
3636
}
3737
}
3838

3939
//set
4040
pub fn is_approver(username: &str) -> bool {
41-
match APP_CONFIG.get_string("tl.app.approval.users") {
41+
match get_app_config().get_string("tl.app.approval.users") {
4242
Ok(values) => values.split(",").any(|v| v == username),
4343
_ => false,
4444
}

common/src/db_util.rs

+17-16
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,30 @@
1+
use std::sync::OnceLock;
12
use std::time::Duration;
23

34
use diesel::prelude::*;
45
use diesel::r2d2::{self, ConnectionManager};
5-
use lazy_static::lazy_static;
66
use log::info;
7-
8-
use super::config_util;
7+
use crate::config_util::get_app_config;
98

109
pub type DbConnection = MysqlConnection;
1110
pub type Pool = r2d2::Pool<ConnectionManager<DbConnection>>;
1211
pub type PooledConnection = r2d2::PooledConnection<ConnectionManager<DbConnection>>;
13-
14-
lazy_static! {
15-
pub static ref POOL: Pool = {
16-
info!("db pool init");
17-
let connspec = config_util::APP_CONFIG
18-
.get_string("tl.app.db.url")
19-
.expect("db url is required");
20-
let manager = ConnectionManager::<DbConnection>::new(connspec);
21-
r2d2::Pool::builder()
22-
.build(manager)
23-
.expect("Failed to create pool.")
24-
};
12+
// Define the static POOL with OnceLock
13+
static POOL: OnceLock<Pool> = OnceLock::new();
14+
// Usage example (you’d call this wherever POOL is accessed)
15+
pub fn get_pool() -> &'static Pool {
16+
POOL.get_or_init(|| init_pool())
17+
}
18+
fn init_pool() -> Pool {
19+
info!("db pool init");
20+
let conn_url = get_app_config()
21+
.get_string("tl.app.db.url")
22+
.expect("db url is required");
23+
let manager = ConnectionManager::<DbConnection>::new(conn_url);
24+
r2d2::Pool::builder()
25+
.build(manager)
26+
.expect("Failed to create pool.")
2527
}
26-
2728
pub fn get_conn(pool: &Pool) -> Option<PooledConnection> {
2829
match pool.get_timeout(Duration::new(10, 0)) {
2930
Ok(conn) => Some(conn),

common/src/log_util.rs

-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
use lazy_static::lazy_static;
21
use log::{debug, error, info, trace, warn};
32
use log4rs;
43

common/src/sign_util.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ use blake2::{digest::Update, Blake2b, Blake2s256, Digest};
33
use data_encoding::BASE64;
44

55
fn get_salt() -> String {
6-
config_util::APP_CONFIG
6+
config_util::get_app_config()
77
.get_string("tl.app.sign.salt")
88
.expect("tl.app.sign.salt is required")
99
}

dao/Cargo.toml

+1-1
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
name = "dao"
33
version = "0.1.0"
44
authors = ["Tianlang <[email protected]>"]
5-
edition = "2021"
5+
edition = "2024"
66

77
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
88

template/freelancer/common/base.html

+5-5
Original file line numberDiff line numberDiff line change
@@ -282,12 +282,12 @@ <h1 class="h4 text-gray-900 mb-4">Welcome</h1>
282282
<script>
283283
var _hmt = _hmt || [];
284284
(function() {
285-
var hm = document.createElement("script");
286-
hm.src = "https://hm.baidu.com/hm.js?5a990c2b8047428b734d3a86ee9e881f";
287-
var s = document.getElementsByTagName("script")[0];
288-
s.parentNode.insertBefore(hm, s);
285+
var hm = document.createElement("script");
286+
hm.src = "https://hm.baidu.com/hm.js?6b36cffe6ce0975ce8a6fa60cc433d1f";
287+
var s = document.getElementsByTagName("script")[0];
288+
s.parentNode.insertBefore(hm, s);
289289
})();
290-
</script>
290+
</script>
291291
<!-- Google tag (gtag.js) -->
292292
<script async src="https://www.googletagmanager.com/gtag/js?id=G-JZ81SEB2BH"></script>
293293
<script>

template/freelancer/common/base_cn.html

+5-5
Original file line numberDiff line numberDiff line change
@@ -285,12 +285,12 @@ <h1 class="h4 text-gray-900 mb-4">欢迎回来</h1>
285285
<script>
286286
var _hmt = _hmt || [];
287287
(function() {
288-
var hm = document.createElement("script");
289-
hm.src = "https://hm.baidu.com/hm.js?5a990c2b8047428b734d3a86ee9e881f";
290-
var s = document.getElementsByTagName("script")[0];
291-
s.parentNode.insertBefore(hm, s);
288+
var hm = document.createElement("script");
289+
hm.src = "https://hm.baidu.com/hm.js?6b36cffe6ce0975ce8a6fa60cc433d1f";
290+
var s = document.getElementsByTagName("script")[0];
291+
s.parentNode.insertBefore(hm, s);
292292
})();
293-
</script>
293+
</script>
294294
<!-- Google tag (gtag.js) -->
295295
<script async src="https://www.googletagmanager.com/gtag/js?id=G-JZ81SEB2BH"></script>
296296
<script>

web/Cargo.toml

+1-1
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
name = "web"
33
version = "0.1.0"
44
authors = ["Tianlang <[email protected]>"]
5-
edition = "2021"
5+
edition = "2024"
66

77
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
88

web/src/filectrl.rs

+15-17
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@ use async_std::fs::File;
1010
use diesel::r2d2::{self, ConnectionManager};
1111

1212
use futures::{AsyncWriteExt, StreamExt};
13-
use lazy_static::lazy_static;
1413

1514
use log::{error, info};
1615

@@ -37,7 +36,7 @@ pub(crate) async fn upload(
3736

3837
let mut file_ids: Vec<String> = Vec::new();
3938
while let Some(Ok(field)) = multipart.next().await {
40-
let path = &*FILE_SAVE_PATH;
39+
let path = &get_file_save_path();
4140
match save_file(field, path, &username, &pool).await {
4241
Ok(file_id) => file_ids.push(file_id),
4342
Err(err) => return Either::Right(Err(err)),
@@ -55,37 +54,36 @@ pub(crate) async fn upload(
5554
pub(crate) async fn view_file(path_params: web::Path<(String,)>) -> Result<fs::NamedFile> {
5655
let path_params = path_params.into_inner();
5756
let file_id = &path_params.0;
58-
let path = Path::new(&*FILE_SAVE_PATH);
57+
let save_path = get_file_save_path();
58+
let path = Path::new(&save_path);
5959
//todo 判断是否是私有文件
6060
Ok(fs::NamedFile::open(path.join(file_id))?)
6161
}
6262
fn success_with_file_ids(file_ids: Vec<String>) -> HttpResponse {
6363
HttpResponse::Ok().json(result::AjaxResult::success(Some(file_ids)))
6464
}
6565
fn get_file_save_path() -> String {
66-
let path = match config_util::APP_CONFIG.get_string("tl.app.upload.path") {
67-
Ok(path) => path,
68-
Err(_) => String::from("upload"),
69-
};
66+
let path = config_util::get_app_config()
67+
.get_string("tl.app.upload.path")
68+
.unwrap_or_else(|_| String::from("upload"));
7069
match std::fs::create_dir_all(&path) {
7170
Ok(_) => info!(" app upload path:{}", &path),
72-
Err(_) => error!("error create app uplod path: {}", &path),
71+
Err(_) => error!("error create app upload path: {}", &path),
7372
}
7473
path
7574
}
7675

7776
fn get_file_max_size_bytes() -> usize {
78-
let max_size_mb = match config_util::APP_CONFIG.get_float("tl.app.upload.max_size") {
79-
Ok(size_mb) => size_mb,
80-
Err(_) => 1.0,
81-
};
77+
let max_size_mb = config_util::get_app_config()
78+
.get_float("tl.app.upload.max_size")
79+
.unwrap_or_else(|_| 1.0);
8280
(max_size_mb * 1024.0 * 1024.0) as usize
8381
}
8482

85-
lazy_static! {
86-
static ref FILE_SAVE_PATH: String = get_file_save_path();
87-
static ref FILE_MAX_SIZE: usize = get_file_max_size_bytes();
88-
}
83+
/*lazy_static! {
84+
//static ref FILE_SAVE_PATH: String = get_file_save_path();
85+
//static ref FILE_MAX_SIZE: usize = get_file_max_size_bytes();
86+
}*/
8987

9088
//保存文件
9189
async fn save_file(
@@ -107,7 +105,7 @@ async fn save_file(
107105
while let Some(bytes) = field.next().await {
108106
let bytes = bytes?;
109107
length += bytes.len();
110-
if length > *FILE_MAX_SIZE {
108+
if length > get_file_max_size_bytes() {
111109
error!("err:{}", "上传的文件过大");
112110
return Err(error::ErrorInternalServerError("上传的文件过大"));
113111
//return Err(Error::from(Response::new(StatusCode::INTERNAL_SERVER_ERROR).set_body(BoxBody::new("上传的文件过大"))));

web/src/main.rs

+5-5
Original file line numberDiff line numberDiff line change
@@ -38,17 +38,17 @@ async fn main() -> std::io::Result<()> {
3838

3939
tera.register_function(
4040
"list_new_articles",
41-
funs::article::make_list_new_articles(db_util::POOL.clone()),
41+
funs::article::make_list_new_articles(db_util::get_pool().clone()),
4242
);
4343
tera.register_function(
4444
"list_recommend_articles",
45-
funs::article::make_list_recommend_articles(db_util::POOL.clone()),
45+
funs::article::make_list_recommend_articles(db_util::get_pool().clone()),
4646
);
4747
// tera.full_reload();
4848

4949
App::new()
5050
.app_data(web::Data::new(tera))
51-
.app_data(web::Data::new(db_util::POOL.clone())) //绑定数据库链接池
51+
.app_data(web::Data::new(db_util::get_pool().clone())) //绑定数据库链接池
5252
.wrap(middleware::AuthService) //添加根据Session验证登录状态的中间件
5353
.wrap(SessionMiddleware::new(
5454
CookieSessionStore::default(),
@@ -76,10 +76,10 @@ async fn main() -> std::io::Result<()> {
7676
let config = load_rustls_config();
7777
server.bind_rustls("127.0.0.1:8443", config)?.run().await
7878
} else {
79-
let port = config_util::APP_CONFIG
79+
let port = config_util::get_app_config()
8080
.get_string("tl.app.http.port")
8181
.expect("port is required");
82-
let host = config_util::APP_CONFIG
82+
let host = config_util::get_app_config()
8383
.get_string("tl.app.http.host")
8484
.expect("host is required");
8585
let host_port = host + ":" + &port;

web/src/web_util.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ pub fn render_html(
4545
HttpResponse::Ok().content_type("text/html").body(body)
4646
}
4747
pub fn get_tmpl_from_session(_session: &Session) -> String {
48-
config_util::APP_CONFIG
48+
config_util::get_app_config()
4949
.get_string("tl.app.template.name")
5050
.expect("default template name is required")
5151
}

0 commit comments

Comments
 (0)