From 9fd77db2a5cbd03ef98d928c0f05e64998223449 Mon Sep 17 00:00:00 2001 From: owen Date: Thu, 6 Jun 2024 22:37:35 +0800 Subject: [PATCH 001/115] select article from article --- src/entity/article.rs | 1 + src/main.rs | 5 +++-- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/src/entity/article.rs b/src/entity/article.rs index d3a54d2..2a2aa7e 100644 --- a/src/entity/article.rs +++ b/src/entity/article.rs @@ -2,6 +2,7 @@ use time::PrimitiveDateTime; #[derive(Clone)] #[derive(Debug)] +#[derive(sqlx::FromRow)] pub struct Article { id: i32, title: String, diff --git a/src/main.rs b/src/main.rs index 8c16b01..7a53b3e 100644 --- a/src/main.rs +++ b/src/main.rs @@ -8,6 +8,7 @@ use sqlx::mysql::MySqlPoolOptions; pub mod person; use crate::person::Person; +use crate::entity::article::Article; @@ -42,11 +43,11 @@ async fn article_detail(){ println!(); let pool = MySqlPoolOptions::new() .connect("mysql://root:onny0620@localhost/blog").await.expect("failed to connect database."); - let row: (i32, String) = sqlx::query_as("SELECT id,title from article") + let article: Article= sqlx::query_as("SELECT id,title from article") .fetch_one(&pool).await.expect("failed!"); //assert_eq!(row.0, 150); - println!("{:?},{:?}",row.0, row.1); + println!("{:?}",article); } async fn me() -> Person<'static>{ -- Gitee From b0ffdc55ea1dab9dbada4fd0cade296d6321ff4d Mon Sep 17 00:00:00 2001 From: owen Date: Thu, 6 Jun 2024 22:44:46 +0800 Subject: [PATCH 002/115] add mod entity --- src/main.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main.rs b/src/main.rs index 7a53b3e..6d76fb1 100644 --- a/src/main.rs +++ b/src/main.rs @@ -6,6 +6,7 @@ use axum::{ use sqlx::mysql::MySqlPoolOptions; pub mod person; +pub mod entity; use crate::person::Person; use crate::entity::article::Article; -- Gitee From 2b009a33edb10f3f3317004b7b3b5c42606ed9ed Mon Sep 17 00:00:00 2001 From: owen Date: Thu, 6 Jun 2024 22:48:30 +0800 Subject: [PATCH 003/115] mysql timestamp -> OffsetDateTime --- src/entity/article.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/entity/article.rs b/src/entity/article.rs index 2a2aa7e..9d508ca 100644 --- a/src/entity/article.rs +++ b/src/entity/article.rs @@ -1,4 +1,4 @@ -use time::PrimitiveDateTime; +use time::OffsetDateTime; #[derive(Clone)] #[derive(Debug)] @@ -10,9 +10,9 @@ pub struct Article { summary: String, path: String, deleted: bool, - createdOn: PrimitiveDateTime, + createdOn: OffsetDateTime, createBy: String, - modifyOn: PrimitiveDateTime, + modifyOn: OffsetDateTime, modifyBy: String, } -- Gitee From ec55fde595c53e1fb79d634e4c416447336fb9ef Mon Sep 17 00:00:00 2001 From: owen Date: Thu, 6 Jun 2024 23:00:46 +0800 Subject: [PATCH 004/115] sqlx offsetdatatime --- Cargo.toml | 2 +- src/entity/article.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 278efec..a759f30 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -15,5 +15,5 @@ askama_axum="0.4.0" tower-http = { version = "0.5.2", features = ["fs", "trace"] } sqlx = { version = "0.7.4", features = ["mysql", "runtime-tokio", "macros"] } -time = "0.3.36" +chrono = "0.4.38" diff --git a/src/entity/article.rs b/src/entity/article.rs index 9d508ca..d56f21a 100644 --- a/src/entity/article.rs +++ b/src/entity/article.rs @@ -1,4 +1,4 @@ -use time::OffsetDateTime; +use sqlx::types::chrono::{OffsetDateTime}; #[derive(Clone)] #[derive(Debug)] -- Gitee From 029aa464c1847c11b2e5ee776a639c438e53440e Mon Sep 17 00:00:00 2001 From: owen Date: Thu, 6 Jun 2024 23:11:14 +0800 Subject: [PATCH 005/115] sqlx::types::time::OffsetDateTime --- src/entity/article.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/entity/article.rs b/src/entity/article.rs index d56f21a..df33250 100644 --- a/src/entity/article.rs +++ b/src/entity/article.rs @@ -1,4 +1,4 @@ -use sqlx::types::chrono::{OffsetDateTime}; +use sqlx::types::time::OffsetDateTime; #[derive(Clone)] #[derive(Debug)] -- Gitee From 04374077b6bbd62a297f956b45ee61a8723044f9 Mon Sep 17 00:00:00 2001 From: owen Date: Thu, 6 Jun 2024 23:31:47 +0800 Subject: [PATCH 006/115] temp remove timestamp --- Cargo.toml | 1 + src/entity/article.rs | 6 +++--- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index a759f30..2e5cd62 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -16,4 +16,5 @@ tower-http = { version = "0.5.2", features = ["fs", "trace"] } sqlx = { version = "0.7.4", features = ["mysql", "runtime-tokio", "macros"] } chrono = "0.4.38" +time = "0.3.36" diff --git a/src/entity/article.rs b/src/entity/article.rs index df33250..0aba849 100644 --- a/src/entity/article.rs +++ b/src/entity/article.rs @@ -1,4 +1,4 @@ -use sqlx::types::time::OffsetDateTime; +use chrono::{NaiveDateTime, Utc, DateTime}; #[derive(Clone)] #[derive(Debug)] @@ -10,9 +10,9 @@ pub struct Article { summary: String, path: String, deleted: bool, - createdOn: OffsetDateTime, + //createdOn: NaiveDateTime, createBy: String, - modifyOn: OffsetDateTime, + //modifyOn: NaiveDateTime, modifyBy: String, } -- Gitee From 7362f6d256f40767bb78d51756cffc4a49a3118c Mon Sep 17 00:00:00 2001 From: "owen.chao" Date: Fri, 7 Jun 2024 12:50:29 +0800 Subject: [PATCH 007/115] feature=chrono, modify time type, query all fields from aritcle --- Cargo.toml | 2 +- resource/scripts/DDL.sql | 8 ++++---- resource/scripts/Test_DML.sql | 2 +- src/entity/article.rs | 6 +++--- src/main.rs | 2 +- 5 files changed, 10 insertions(+), 10 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 2e5cd62..c6e8b6a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -14,7 +14,7 @@ askama_axum="0.4.0" tower-http = { version = "0.5.2", features = ["fs", "trace"] } -sqlx = { version = "0.7.4", features = ["mysql", "runtime-tokio", "macros"] } +sqlx = { version = "0.7.4", features = ["mysql", "runtime-tokio", "macros", "chrono"] } chrono = "0.4.38" time = "0.3.36" diff --git a/resource/scripts/DDL.sql b/resource/scripts/DDL.sql index 259f598..3db8d96 100644 --- a/resource/scripts/DDL.sql +++ b/resource/scripts/DDL.sql @@ -9,9 +9,9 @@ CREATE TABLE article ( `summary` VARCHAR(512) NOT NULL, `path` VARCHAR(128) NOT NULL, `deleted` BIT(1) DEFAULT 0, -- 更明确地指定BIT的长度,尽管默认是1 - `createOn` TIMESTAMP NOT NULL , + `createOn` DATETIME NOT NULL , `createBy` VARCHAR(32) NOT NULL, - `modifyOn` TIMESTAMP NOT NULL , + `modifyOn` DATETIME NOT NULL , `modifyBy` VARCHAR(32) NOT NULL, PRIMARY KEY(`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; @@ -21,9 +21,9 @@ CREATE TABLE category( `id` INT(11) NOT NULL AUTO_INCREMENT, `category` VARCHAR(16) NOT NULL, `deleted` BIT(1) DEFAULT 0, -- 明确BIT长度 - `createOn` TIMESTAMP NOT NULL , + `createOn` DATETIME NOT NULL , `createBy` VARCHAR(32) NOT NULL, - `modifyOn` TIMESTAMP NOT NULL , + `modifyOn` DATETIME NOT NULL , `modifyBy` VARCHAR(32) NOT NULL, PRIMARY KEY(`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; diff --git a/resource/scripts/Test_DML.sql b/resource/scripts/Test_DML.sql index 437c4b5..de09533 100644 --- a/resource/scripts/Test_DML.sql +++ b/resource/scripts/Test_DML.sql @@ -1,2 +1,2 @@ insert article (title,categoryId,summary,`path`, deleted, createOn, createBy, modifyOn, modifyBy) -values ('test', NULL,'summary test','/blog/1.md', 0, now(),'admin', now(),'admin') \ No newline at end of file +values ('test', NULL,'summary test','/blog/1.md', 0, now(),'admin', now(),'admin'); diff --git a/src/entity/article.rs b/src/entity/article.rs index 0aba849..d9c1eb5 100644 --- a/src/entity/article.rs +++ b/src/entity/article.rs @@ -6,13 +6,13 @@ use chrono::{NaiveDateTime, Utc, DateTime}; pub struct Article { id: i32, title: String, - categoryId: i32, + categoryId: Option, summary: String, path: String, deleted: bool, - //createdOn: NaiveDateTime, + createOn: NaiveDateTime, createBy: String, - //modifyOn: NaiveDateTime, + modifyOn: NaiveDateTime, modifyBy: String, } diff --git a/src/main.rs b/src/main.rs index 6d76fb1..e20940c 100644 --- a/src/main.rs +++ b/src/main.rs @@ -44,7 +44,7 @@ async fn article_detail(){ println!(); let pool = MySqlPoolOptions::new() .connect("mysql://root:onny0620@localhost/blog").await.expect("failed to connect database."); - let article: Article= sqlx::query_as("SELECT id,title from article") + let article: Article= sqlx::query_as("SELECT * from article") .fetch_one(&pool).await.expect("failed!"); //assert_eq!(row.0, 150); -- Gitee From afddeda458fbb853a9948d8beadedc3e66bdbfe3 Mon Sep 17 00:00:00 2001 From: "owen.chao" Date: Fri, 7 Jun 2024 18:40:43 +0800 Subject: [PATCH 008/115] blog list html --- templates/html/blog_list.html | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/templates/html/blog_list.html b/templates/html/blog_list.html index ca057fd..6075114 100644 --- a/templates/html/blog_list.html +++ b/templates/html/blog_list.html @@ -4,22 +4,34 @@ 你的网页标题 - - + +

hello

+ + +
+ +
+
Card title
+ +

Some quick example text to build on the card title and make up the bulk of the card's content.

+ Go somewhere +
+
+ - +

© 2023 你的公司名或个人名. All rights reserved.

- + + + + + diff --git a/templates/html/blog_list.html b/templates/html/blog_list.html index 6075114..5bc58af 100644 --- a/templates/html/blog_list.html +++ b/templates/html/blog_list.html @@ -12,18 +12,21 @@

hello

- -
- -
-
Card title
- -

Some quick example text to build on the card title and make up the bulk of the card's content.

- Go somewhere -
+
+
+
+
+
+
Card title
+

Some quick example text to build on the card title and make up the bulk of the card's content. + Some quick example text to build on the card title and make up the bulk of the card's content. +

+ Go somewhere +
+
+
-
-- Gitee From dfa30baba4b9e692060710a88263da34ffd76457 Mon Sep 17 00:00:00 2001 From: owen Date: Sun, 9 Jun 2024 19:22:08 +0800 Subject: [PATCH 010/115] add article summary --- src/main.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main.rs b/src/main.rs index 2107c20..f620258 100644 --- a/src/main.rs +++ b/src/main.rs @@ -10,7 +10,7 @@ pub mod entity; use crate::person::Person; use crate::entity::article::Article; -use crate::entity::article::ArticleSummary; +use crate::entity::article_summary::ArticleSummary; -- Gitee From 1dfac1257ef36c16fdbf0eec2697398dd1a343ee Mon Sep 17 00:00:00 2001 From: owen Date: Sun, 9 Jun 2024 19:28:00 +0800 Subject: [PATCH 011/115] add article summary --- src/entity/article_summary.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/entity/article_summary.rs b/src/entity/article_summary.rs index fda2c45..d81edda 100644 --- a/src/entity/article_summary.rs +++ b/src/entity/article_summary.rs @@ -8,7 +8,6 @@ pub struct ArticleSummary { title: String, categoryId: Option, summary: String, - path: String, createOn: NaiveDateTime, createBy: String, } -- Gitee From 8ad7092e9fd853f0733f2ab664559b784d24aad4 Mon Sep 17 00:00:00 2001 From: "owen.chao" Date: Sun, 9 Jun 2024 19:36:20 +0800 Subject: [PATCH 012/115] fix bug --- src/main.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main.rs b/src/main.rs index f620258..afe41d9 100644 --- a/src/main.rs +++ b/src/main.rs @@ -45,7 +45,7 @@ async fn article_detail(){ println!(); let pool = MySqlPoolOptions::new() .connect("mysql://root:onny0620@localhost/blog").await.expect("failed to connect database."); - let article: Article= sqlx::query_as("SELECT id, title, categoryId, summary, createOn, createBy from article") + let article: ArticleSummary= sqlx::query_as("SELECT id, title, categoryId, summary, createOn, createBy from article") .fetch_one(&pool).await.expect("failed!"); //assert_eq!(row.0, 150); -- Gitee From 93fa8d367abb1ca693b940ae77d8fc8e6d83a9e9 Mon Sep 17 00:00:00 2001 From: owen Date: Sun, 9 Jun 2024 19:44:37 +0800 Subject: [PATCH 013/115] query muti-records --- src/main.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main.rs b/src/main.rs index afe41d9..c2b185c 100644 --- a/src/main.rs +++ b/src/main.rs @@ -45,8 +45,8 @@ async fn article_detail(){ println!(); let pool = MySqlPoolOptions::new() .connect("mysql://root:onny0620@localhost/blog").await.expect("failed to connect database."); - let article: ArticleSummary= sqlx::query_as("SELECT id, title, categoryId, summary, createOn, createBy from article") - .fetch_one(&pool).await.expect("failed!"); + let summary_vec: ArticleSummary= sqlx::query_as("SELECT id, title, categoryId, summary, createOn, createBy from article limit ?, ?", 0, 10) + .fetch_all(&pool).await.expect("failed!"); //assert_eq!(row.0, 150); println!("{:?}",article); -- Gitee From 9abd573e13cf092fae90759a9df7f8343de6838a Mon Sep 17 00:00:00 2001 From: owen Date: Sun, 9 Jun 2024 19:52:07 +0800 Subject: [PATCH 014/115] get the param from path --- src/main.rs | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/main.rs b/src/main.rs index c2b185c..d8f409c 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,6 +1,7 @@ use axum::{ routing::get, Router, + extract::{Extension, Path} }; use sqlx::mysql::MySqlPoolOptions; @@ -22,7 +23,8 @@ async fn main() { let workspace = std::env::current_dir().unwrap(); println!("{:?}", workspace); - let router = Router::new().route("/", get(article_detail)) + let router = Router::new().route("/", get(me)) + .route("/list/:offset", get(article_detail)) .route("/me", get(me)) .nest_service("/assets", tower_http::services::ServeDir::new("assets")); @@ -41,8 +43,8 @@ async fn say_hello()-> String{ row.0 } -async fn article_detail(){ - println!(); +async fn article_detail(Path(offset): Path){ + println!("the offset is {}", offset); let pool = MySqlPoolOptions::new() .connect("mysql://root:onny0620@localhost/blog").await.expect("failed to connect database."); let summary_vec: ArticleSummary= sqlx::query_as("SELECT id, title, categoryId, summary, createOn, createBy from article limit ?, ?", 0, 10) -- Gitee From a038673a758b15872fc4471d4533329f0997e13c Mon Sep 17 00:00:00 2001 From: owen Date: Sun, 9 Jun 2024 19:57:42 +0800 Subject: [PATCH 015/115] bind param to sqlx --- src/main.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main.rs b/src/main.rs index d8f409c..8cd0eed 100644 --- a/src/main.rs +++ b/src/main.rs @@ -51,7 +51,7 @@ async fn article_detail(Path(offset): Path){ .fetch_all(&pool).await.expect("failed!"); //assert_eq!(row.0, 150); - println!("{:?}",article); + println!("{:?}",summary_vec); } -- Gitee From 9c4cee249d50e6675a032b6aa835d43798f1efa0 Mon Sep 17 00:00:00 2001 From: owen Date: Sun, 9 Jun 2024 20:00:46 +0800 Subject: [PATCH 016/115] bind param to sqlx --- src/main.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main.rs b/src/main.rs index 8cd0eed..9c71bd3 100644 --- a/src/main.rs +++ b/src/main.rs @@ -47,7 +47,7 @@ async fn article_detail(Path(offset): Path){ println!("the offset is {}", offset); let pool = MySqlPoolOptions::new() .connect("mysql://root:onny0620@localhost/blog").await.expect("failed to connect database."); - let summary_vec: ArticleSummary= sqlx::query_as("SELECT id, title, categoryId, summary, createOn, createBy from article limit ?, ?", 0, 10) + let summary_vec: Vec= sqlx::query_as("SELECT id, title, categoryId, summary, createOn, createBy from article limit ?, ?", 0, 10) .fetch_all(&pool).await.expect("failed!"); //assert_eq!(row.0, 150); -- Gitee From 0a7abed2fa5f787746cf4613086ce2b04d822d2e Mon Sep 17 00:00:00 2001 From: owen Date: Sun, 9 Jun 2024 20:03:59 +0800 Subject: [PATCH 017/115] bing muti-params --- src/main.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/main.rs b/src/main.rs index 9c71bd3..ef9358e 100644 --- a/src/main.rs +++ b/src/main.rs @@ -47,7 +47,9 @@ async fn article_detail(Path(offset): Path){ println!("the offset is {}", offset); let pool = MySqlPoolOptions::new() .connect("mysql://root:onny0620@localhost/blog").await.expect("failed to connect database."); - let summary_vec: Vec= sqlx::query_as("SELECT id, title, categoryId, summary, createOn, createBy from article limit ?, ?", 0, 10) + let summary_vec: Vec= sqlx::query_as("SELECT id, title, categoryId, summary, createOn, createBy from article limit ?, ?") + .bind(0) + .bind(10) .fetch_all(&pool).await.expect("failed!"); //assert_eq!(row.0, 150); -- Gitee From f5a9dedce9ebffe59761a2288f44c397068d5434 Mon Sep 17 00:00:00 2001 From: owen Date: Sun, 9 Jun 2024 21:04:11 +0800 Subject: [PATCH 018/115] add article detail method and bug fix --- src/main.rs | 25 ++++++++++++++++--------- 1 file changed, 16 insertions(+), 9 deletions(-) diff --git a/src/main.rs b/src/main.rs index ef9358e..cf73476 100644 --- a/src/main.rs +++ b/src/main.rs @@ -24,7 +24,8 @@ async fn main() { println!("{:?}", workspace); let router = Router::new().route("/", get(me)) - .route("/list/:offset", get(article_detail)) + .route("/list/:offset", get(article_list)) + .route("/article/:id", get(article_detail)) .route("/me", get(me)) .nest_service("/assets", tower_http::services::ServeDir::new("assets")); @@ -43,13 +44,13 @@ async fn say_hello()-> String{ row.0 } -async fn article_detail(Path(offset): Path){ - println!("the offset is {}", offset); - let pool = MySqlPoolOptions::new() +async fn article_list(Path(offset): Path){ + println!("the offset is {}", &offset); + let pool = MySqlPoolOptions::new() .connect("mysql://root:onny0620@localhost/blog").await.expect("failed to connect database."); - let summary_vec: Vec= sqlx::query_as("SELECT id, title, categoryId, summary, createOn, createBy from article limit ?, ?") - .bind(0) - .bind(10) + let summary_vec: Vec= sqlx::query_as("SELECT id, title, categoryId, summary, createOn, createBy FROM article WHERE deleted=0 limit ?, ?") + .bind(offset) + .bind(10) .fetch_all(&pool).await.expect("failed!"); //assert_eq!(row.0, 150); @@ -57,8 +58,14 @@ async fn article_detail(Path(offset): Path){ } -async fn article_list(){ - +async fn article_detail(Path(id): Path){ + println!("the article id is {}", &id); + let pool = MySqlPoolOptions::new() + .connect("mysql://root:onny0620@localhost/blog").await.expect("failed to connect database."); + let article: Article = sqlx::query_as("SELECT id, title, categoryId, summary, path, deleted, createOn, createBy, modifyOn, modifyBy FROM article WHERE ID=?") + .bind(id) + .fetch_one(&pool).await.expect("Can not find the article detail"); + println!("the article detail {:?}", article); } async fn me() -> Person<'static>{ -- Gitee From 634e54f41afad873383964109f507927a37c14b3 Mon Sep 17 00:00:00 2001 From: owen Date: Sun, 9 Jun 2024 21:14:34 +0800 Subject: [PATCH 019/115] bug fix --- src/main.rs | 4 ---- 1 file changed, 4 deletions(-) diff --git a/src/main.rs b/src/main.rs index cf73476..a35420b 100644 --- a/src/main.rs +++ b/src/main.rs @@ -3,7 +3,6 @@ use axum::{ Router, extract::{Extension, Path} }; - use sqlx::mysql::MySqlPoolOptions; pub mod person; @@ -13,9 +12,6 @@ use crate::person::Person; use crate::entity::article::Article; use crate::entity::article_summary::ArticleSummary; - - - #[tokio::main] async fn main() { // build our application with a single route -- Gitee From 8055a37684b51fa03f231f230f44ac34d15ebfe5 Mon Sep 17 00:00:00 2001 From: owen Date: Sun, 9 Jun 2024 21:26:31 +0800 Subject: [PATCH 020/115] some change --- src/main.rs | 5 ++--- templates/html/blog_list.html | 28 ++++++++++++++-------------- 2 files changed, 16 insertions(+), 17 deletions(-) diff --git a/src/main.rs b/src/main.rs index a35420b..2f5e4a4 100644 --- a/src/main.rs +++ b/src/main.rs @@ -21,20 +21,19 @@ async fn main() { let router = Router::new().route("/", get(me)) .route("/list/:offset", get(article_list)) - .route("/article/:id", get(article_detail)) + .route("/article/:id", get(article_detail)) .route("/me", get(me)) .nest_service("/assets", tower_http::services::ServeDir::new("assets")); // run our app with hyper, listening globally on port 3000 let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap(); axum::serve(listener, router).await.unwrap(); - } async fn say_hello()-> String{ let pool = MySqlPoolOptions::new() .connect("mysql://root:onny0620@localhost/blog").await.expect("failed to connect database."); - let row: (String,) = sqlx::query_as("SELECT 'hello world, Rust!'") + let row: (String,) = sqlx::query_as("SELECT 'hello world, Rust!'") .fetch_one(&pool).await.expect("failed!"); //assert_eq!(row.0, 150); row.0 diff --git a/templates/html/blog_list.html b/templates/html/blog_list.html index 5bc58af..8a9a2f1 100644 --- a/templates/html/blog_list.html +++ b/templates/html/blog_list.html @@ -12,20 +12,20 @@

hello

-
-
-
-
-
-
Card title
-

Some quick example text to build on the card title and make up the bulk of the card's content. - Some quick example text to build on the card title and make up the bulk of the card's content. -

- Go somewhere -
-
-
-
+
+
+
+
+
+
Card title
+

Some quick example text to build on the card title and make up the bulk of the card's content. + Some quick example text to build on the card title and make up the bulk of the card's content. +

+ Go somewhere +
+
+
+
-- Gitee From 85261acfc6193c66eb49ddf215eae14e6add741f Mon Sep 17 00:00:00 2001 From: owen Date: Wed, 12 Jun 2024 08:21:41 +0800 Subject: [PATCH 021/115] template --- src/entity/article_summary_vec.rs | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 src/entity/article_summary_vec.rs diff --git a/src/entity/article_summary_vec.rs b/src/entity/article_summary_vec.rs new file mode 100644 index 0000000..5c55725 --- /dev/null +++ b/src/entity/article_summary_vec.rs @@ -0,0 +1,17 @@ +#[derive(Clone)] +#[derive(Debug)] +#[derive(Template)] +#[template(path = "article_list.html")] +pub struct ArticleSummaryVec { + vec: Option> +} + +impl ArticleSummaryVec { + fn new(vec: Vec) ->ArticleSummaryVec{ + ArticleSummaryVec{ + vec: Some(vec), + } + } +} + + -- Gitee From fa439e84897f9aa4a8b0d291e90eddaa3018fbc0 Mon Sep 17 00:00:00 2001 From: owen Date: Wed, 12 Jun 2024 22:47:48 +0800 Subject: [PATCH 022/115] add askama template --- src/entity/article_summary_vec.rs | 7 +++++-- src/entity/mod.rs | 1 + src/main.rs | 6 ++++-- 3 files changed, 10 insertions(+), 4 deletions(-) diff --git a/src/entity/article_summary_vec.rs b/src/entity/article_summary_vec.rs index 5c55725..65d5c38 100644 --- a/src/entity/article_summary_vec.rs +++ b/src/entity/article_summary_vec.rs @@ -1,13 +1,16 @@ +use crate::entity::article_summary::ArticleSummary; +use askama_axum::Template; + #[derive(Clone)] #[derive(Debug)] #[derive(Template)] -#[template(path = "article_list.html")] +#[template(path = "html/blog_list.html")] pub struct ArticleSummaryVec { vec: Option> } impl ArticleSummaryVec { - fn new(vec: Vec) ->ArticleSummaryVec{ + pub fn new(vec: Vec) ->ArticleSummaryVec{ ArticleSummaryVec{ vec: Some(vec), } diff --git a/src/entity/mod.rs b/src/entity/mod.rs index d34dbc9..9f70794 100644 --- a/src/entity/mod.rs +++ b/src/entity/mod.rs @@ -1,2 +1,3 @@ pub mod article; pub mod article_summary; +pub mod article_summary_vec; diff --git a/src/main.rs b/src/main.rs index 2f5e4a4..7f1265c 100644 --- a/src/main.rs +++ b/src/main.rs @@ -11,6 +11,7 @@ pub mod entity; use crate::person::Person; use crate::entity::article::Article; use crate::entity::article_summary::ArticleSummary; +use crate::entity::article_summary_vec::ArticleSummaryVec; #[tokio::main] async fn main() { @@ -39,7 +40,7 @@ async fn say_hello()-> String{ row.0 } -async fn article_list(Path(offset): Path){ +async fn article_list(Path(offset): Path) -> ArticleSummaryVec{ println!("the offset is {}", &offset); let pool = MySqlPoolOptions::new() .connect("mysql://root:onny0620@localhost/blog").await.expect("failed to connect database."); @@ -49,7 +50,8 @@ async fn article_list(Path(offset): Path){ .fetch_all(&pool).await.expect("failed!"); //assert_eq!(row.0, 150); - println!("{:?}",summary_vec); + println!("{:?}",&summary_vec); + ArticleSummaryVec::new(summary_vec) } -- Gitee From 785783e55cad76b853164c7db771777599301641 Mon Sep 17 00:00:00 2001 From: owen Date: Wed, 12 Jun 2024 23:06:39 +0800 Subject: [PATCH 023/115] modidfy list struct --- src/entity/article_summary.rs | 12 ++++++------ src/entity/article_summary_vec.rs | 4 ++-- templates/html/blog_list.html | 4 ++++ 3 files changed, 12 insertions(+), 8 deletions(-) diff --git a/src/entity/article_summary.rs b/src/entity/article_summary.rs index d81edda..6b2c700 100644 --- a/src/entity/article_summary.rs +++ b/src/entity/article_summary.rs @@ -4,12 +4,12 @@ use chrono::{NaiveDateTime, Utc, DateTime}; #[derive(Debug)] #[derive(sqlx::FromRow)] pub struct ArticleSummary { - id: i32, - title: String, - categoryId: Option, - summary: String, - createOn: NaiveDateTime, - createBy: String, + pub id: i32, + pub title: String, + pub categoryId: Option, + pub summary: String, + pub createOn: NaiveDateTime, + pub createBy: String, } diff --git a/src/entity/article_summary_vec.rs b/src/entity/article_summary_vec.rs index 65d5c38..f667a7d 100644 --- a/src/entity/article_summary_vec.rs +++ b/src/entity/article_summary_vec.rs @@ -6,13 +6,13 @@ use askama_axum::Template; #[derive(Template)] #[template(path = "html/blog_list.html")] pub struct ArticleSummaryVec { - vec: Option> + vec: Vec } impl ArticleSummaryVec { pub fn new(vec: Vec) ->ArticleSummaryVec{ ArticleSummaryVec{ - vec: Some(vec), + vec } } } diff --git a/templates/html/blog_list.html b/templates/html/blog_list.html index 8a9a2f1..3c5bfb0 100644 --- a/templates/html/blog_list.html +++ b/templates/html/blog_list.html @@ -24,6 +24,10 @@ Go somewhere
+ {% for article in vec %} +
  • {{ article.title|e }}
  • + {% endfor %} +
    -- Gitee From b2a3699447bd4359253d490ca42a4a86063b2161 Mon Sep 17 00:00:00 2001 From: owen Date: Fri, 14 Jun 2024 08:17:41 +0800 Subject: [PATCH 024/115] list page --- Cargo.toml | 2 +- src/entity/article_summary_vec.rs | 10 +++++++--- src/main.rs | 16 +++++++++++++++- templates/html/blog_list.html | 24 +++++++++++------------- 4 files changed, 34 insertions(+), 18 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index c6e8b6a..30d89df 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -7,7 +7,7 @@ edition = "2021" [dependencies] axum="0.7.5" -tokio={version="1.37.0",features=["macros","rt-multi-thread"]} +tokio={version="1.37.0",features=["macros","rt-multi-thread","time"]} askama = {version="0.12.1"} askama_axum="0.4.0" diff --git a/src/entity/article_summary_vec.rs b/src/entity/article_summary_vec.rs index f667a7d..8939fbf 100644 --- a/src/entity/article_summary_vec.rs +++ b/src/entity/article_summary_vec.rs @@ -6,13 +6,17 @@ use askama_axum::Template; #[derive(Template)] #[template(path = "html/blog_list.html")] pub struct ArticleSummaryVec { - vec: Vec + vec1: Vec, + vec2: Vec, + vec3: Vec } impl ArticleSummaryVec { - pub fn new(vec: Vec) ->ArticleSummaryVec{ + pub fn new(vec1: Vec, vec2: Vec, vec3: Vec,) ->ArticleSummaryVec{ ArticleSummaryVec{ - vec + vec1, + vec2, + vec3, } } } diff --git a/src/main.rs b/src/main.rs index 7f1265c..85e6d72 100644 --- a/src/main.rs +++ b/src/main.rs @@ -51,7 +51,21 @@ async fn article_list(Path(offset): Path) -> ArticleSummaryVec{ //assert_eq!(row.0, 150); println!("{:?}",&summary_vec); - ArticleSummaryVec::new(summary_vec) + let mut vec1: Vec = vec![]; + let mut vec2: Vec = vec![]; + let mut vec3: Vec = vec![]; + for (position, article) in summary_vec.iter().enumerate() { + if (position%3==0){ + vec1.push(article); + } + if (position%3==1){ + vec2.push(article); + } + if (position%3==2){ + vec3.push(article); + } + } + ArticleSummaryVec::new(vec1, vec2, vec3) } diff --git a/templates/html/blog_list.html b/templates/html/blog_list.html index 3c5bfb0..feedf7a 100644 --- a/templates/html/blog_list.html +++ b/templates/html/blog_list.html @@ -14,19 +14,17 @@
    -
    -
    -
    -
    Card title
    -

    Some quick example text to build on the card title and make up the bulk of the card's content. - Some quick example text to build on the card title and make up the bulk of the card's content. -

    - Go somewhere -
    -
    - {% for article in vec %} -
  • {{ article.title|e }}
  • - {% endfor %} + {% for article in vec1 %} +
    +
    +
    +
    {{article.title|e}}
    +

    + Go somewhere +

    +
    + {%end for%} +
    -- Gitee From 5454f647fdad67c809a410ea9a0d587f0eae8ed2 Mon Sep 17 00:00:00 2001 From: owen Date: Fri, 14 Jun 2024 09:02:14 +0800 Subject: [PATCH 025/115] modify summary list, & --- src/entity/article_summary_vec.rs | 6 +++--- templates/html/blog_list.html | 4 ++-- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/entity/article_summary_vec.rs b/src/entity/article_summary_vec.rs index 8939fbf..41d5ebd 100644 --- a/src/entity/article_summary_vec.rs +++ b/src/entity/article_summary_vec.rs @@ -6,9 +6,9 @@ use askama_axum::Template; #[derive(Template)] #[template(path = "html/blog_list.html")] pub struct ArticleSummaryVec { - vec1: Vec, - vec2: Vec, - vec3: Vec + vec1: Vec<&ArticleSummary>, + vec2: Vec<&ArticleSummary>, + vec3: Vec<&ArticleSummary> } impl ArticleSummaryVec { diff --git a/templates/html/blog_list.html b/templates/html/blog_list.html index feedf7a..10da402 100644 --- a/templates/html/blog_list.html +++ b/templates/html/blog_list.html @@ -23,9 +23,9 @@ Go somewhere
    - {%end for%} + {% endfor %} + - -- Gitee From 1054503e808643758af62fbe9a5d4ae792040308 Mon Sep 17 00:00:00 2001 From: "owen.chao" Date: Fri, 14 Jun 2024 13:32:41 +0800 Subject: [PATCH 026/115] article list page and rust code modify --- src/entity/article_summary_vec.rs | 6 +- src/main.rs | 7 +- ...blog_list (\345\211\257\346\234\254).html" | 2 +- templates/html/blog_list.html | 74 +++++++++++-------- 4 files changed, 50 insertions(+), 39 deletions(-) diff --git a/src/entity/article_summary_vec.rs b/src/entity/article_summary_vec.rs index 41d5ebd..8939fbf 100644 --- a/src/entity/article_summary_vec.rs +++ b/src/entity/article_summary_vec.rs @@ -6,9 +6,9 @@ use askama_axum::Template; #[derive(Template)] #[template(path = "html/blog_list.html")] pub struct ArticleSummaryVec { - vec1: Vec<&ArticleSummary>, - vec2: Vec<&ArticleSummary>, - vec3: Vec<&ArticleSummary> + vec1: Vec, + vec2: Vec, + vec3: Vec } impl ArticleSummaryVec { diff --git a/src/main.rs b/src/main.rs index 85e6d72..a539592 100644 --- a/src/main.rs +++ b/src/main.rs @@ -55,14 +55,15 @@ async fn article_list(Path(offset): Path) -> ArticleSummaryVec{ let mut vec2: Vec = vec![]; let mut vec3: Vec = vec![]; for (position, article) in summary_vec.iter().enumerate() { + println!("position: {}", position); if (position%3==0){ - vec1.push(article); + vec1.push(article.clone()); } if (position%3==1){ - vec2.push(article); + vec2.push(article.clone()); } if (position%3==2){ - vec3.push(article); + vec3.push(article.clone()); } } ArticleSummaryVec::new(vec1, vec2, vec3) diff --git "a/templates/html/blog_list (\345\211\257\346\234\254).html" "b/templates/html/blog_list (\345\211\257\346\234\254).html" index 2cd200c..8648c35 100644 --- "a/templates/html/blog_list (\345\211\257\346\234\254).html" +++ "b/templates/html/blog_list (\345\211\257\346\234\254).html" @@ -10,7 +10,7 @@ -

    hello

    +

    hello

    diff --git a/templates/html/blog_list.html b/templates/html/blog_list.html index 10da402..bbb2ace 100644 --- a/templates/html/blog_list.html +++ b/templates/html/blog_list.html @@ -3,31 +3,53 @@ - 你的网页标题 + RustAll - -

    hello

    - -
    -
    - {% for article in vec1 %} -
    -
    -
    -
    {{article.title|e}}
    -

    - Go somewhere -

    -
    - {% endfor %} - - -
    -
    +

    Rust All

    + +
    +
    +
    + {% for article in vec1 %} +
    +
    +
    {{article.title|e}}
    +

    {{article.summary|e}}

    + Go +
    +
    + {% endfor %} +
    + +
    + {% for article in vec2 %} +
    +
    +
    {{article.title|e}}
    +

    {{article.summary|e}}

    + Go +
    +
    + {% endfor %} +
    + +
    + {% for article in vec3 %} +
    +
    +
    {{article.title|e}}
    +

    {{article.summary|e}}

    + Go +
    +
    + {% endfor %} +
    +
    +
    @@ -35,19 +57,7 @@

    © 2023 你的公司名或个人名. All rights reserved.

    - - -- Gitee From ca7b86a25f96f5b54ac5bdbf12d83d950d5a96c7 Mon Sep 17 00:00:00 2001 From: "owen.chao" Date: Fri, 14 Jun 2024 19:26:49 +0800 Subject: [PATCH 027/115] page list css --- templates/html/blog_list.html | 34 ++++++++++++++++++++++++++++++++-- 1 file changed, 32 insertions(+), 2 deletions(-) diff --git a/templates/html/blog_list.html b/templates/html/blog_list.html index bbb2ace..d1344c8 100644 --- a/templates/html/blog_list.html +++ b/templates/html/blog_list.html @@ -6,12 +6,30 @@ RustAll - +

    Rust All

    -
    +
    {% for article in vec1 %} @@ -48,6 +66,18 @@
    {% endfor %}
    + + + + + +
    -- Gitee From e2a2922002b2adcdecc6b56668b7396b4df49fe0 Mon Sep 17 00:00:00 2001 From: owen Date: Sat, 15 Jun 2024 00:37:37 +0800 Subject: [PATCH 028/115] read file and return string --- src/entity/article.rs | 20 ++++++++++++++++++++ src/entity/article_summary_vec.rs | 8 ++++++-- src/main.rs | 27 +++++++++++++++++++-------- 3 files changed, 45 insertions(+), 10 deletions(-) diff --git a/src/entity/article.rs b/src/entity/article.rs index d9c1eb5..cb1385e 100644 --- a/src/entity/article.rs +++ b/src/entity/article.rs @@ -1,3 +1,7 @@ +use std::fs::File; +use std::io::BufReader; +use std::io::Read; + use chrono::{NaiveDateTime, Utc, DateTime}; #[derive(Clone)] @@ -16,4 +20,20 @@ pub struct Article { modifyBy: String, } +impl Article { + pub async fn read_file(self) -> String { + let file = match File::open(&self.path) { + Ok(file) => file, + Err(err) => { + println!("无法打开文件: {}", err); + return String::from("Sorry, 找不到此博客。"); + } + }; + let mut buf_reader = BufReader::new(file); + let mut contents = String::new(); + let _ = buf_reader.read_to_string(&mut contents); + contents + } +} + diff --git a/src/entity/article_summary_vec.rs b/src/entity/article_summary_vec.rs index 8939fbf..557e6f3 100644 --- a/src/entity/article_summary_vec.rs +++ b/src/entity/article_summary_vec.rs @@ -8,15 +8,19 @@ use askama_axum::Template; pub struct ArticleSummaryVec { vec1: Vec, vec2: Vec, - vec3: Vec + vec3: Vec, + page_total: i32, + page_num: i32, } impl ArticleSummaryVec { - pub fn new(vec1: Vec, vec2: Vec, vec3: Vec,) ->ArticleSummaryVec{ + pub fn new(vec1: Vec, vec2: Vec, vec3: Vec, page_total: i32, page_num: i32) ->ArticleSummaryVec{ ArticleSummaryVec{ vec1, vec2, vec3, + page_total, + page_num, } } } diff --git a/src/main.rs b/src/main.rs index a539592..0987b77 100644 --- a/src/main.rs +++ b/src/main.rs @@ -40,15 +40,22 @@ async fn say_hello()-> String{ row.0 } -async fn article_list(Path(offset): Path) -> ArticleSummaryVec{ +async fn article_list(Path(page_num): Path) -> ArticleSummaryVec{ + println!("page_num: {}", page_num); + let page_size :i32 = 9; + let offset = (page_num-1)*page_size; println!("the offset is {}", &offset); let pool = MySqlPoolOptions::new() .connect("mysql://root:onny0620@localhost/blog").await.expect("failed to connect database."); - let summary_vec: Vec= sqlx::query_as("SELECT id, title, categoryId, summary, createOn, createBy FROM article WHERE deleted=0 limit ?, ?") + let summary_vec: Vec= sqlx::query_as("SELECT id, title, categoryId, summary, createOn, createBy FROM article WHERE deleted=0 order by id desc limit ?, ? ") .bind(offset) - .bind(10) + .bind(page_size) .fetch_all(&pool).await.expect("failed!"); //assert_eq!(row.0, 150); + let total: i32 = sqlx::query_scalar("select count(id) from article where deleted=0") + .fetch_one(&pool) + .await.expect("Query page total failed!"); + let page_total = total/page_size; println!("{:?}",&summary_vec); let mut vec1: Vec = vec![]; @@ -66,10 +73,12 @@ async fn article_list(Path(offset): Path) -> ArticleSummaryVec{ vec3.push(article.clone()); } } - ArticleSummaryVec::new(vec1, vec2, vec3) + ArticleSummaryVec::new(vec1, vec2, vec3, page_total, page_num) } + + async fn article_detail(Path(id): Path){ println!("the article id is {}", &id); let pool = MySqlPoolOptions::new() @@ -77,14 +86,16 @@ async fn article_detail(Path(id): Path){ let article: Article = sqlx::query_as("SELECT id, title, categoryId, summary, path, deleted, createOn, createBy, modifyOn, modifyBy FROM article WHERE ID=?") .bind(id) .fetch_one(&pool).await.expect("Can not find the article detail"); - println!("the article detail {:?}", article); + println!("the article detail {:?}", &article); + article.read_file(); } async fn me() -> Person<'static>{ Person{name:"Owen"} } -async fn rsa(){ - //rsa::gen_keys_to_pem(); -} + + + + -- Gitee From 5f08bdd075bdb27855d65ee6bdef862fbc29cc03 Mon Sep 17 00:00:00 2001 From: owen Date: Sat, 15 Jun 2024 00:42:35 +0800 Subject: [PATCH 029/115] print article content --- src/entity/article.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/entity/article.rs b/src/entity/article.rs index cb1385e..5c12332 100644 --- a/src/entity/article.rs +++ b/src/entity/article.rs @@ -32,6 +32,7 @@ impl Article { let mut buf_reader = BufReader::new(file); let mut contents = String::new(); let _ = buf_reader.read_to_string(&mut contents); + println!("article content {}",&contents); contents } } -- Gitee From 26334ae3ff20bf7285c0d450ae670b2cec436e2b Mon Sep 17 00:00:00 2001 From: owen Date: Sat, 15 Jun 2024 00:48:29 +0800 Subject: [PATCH 030/115] add log --- src/entity/article.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/entity/article.rs b/src/entity/article.rs index 5c12332..579e4d7 100644 --- a/src/entity/article.rs +++ b/src/entity/article.rs @@ -22,8 +22,12 @@ pub struct Article { impl Article { pub async fn read_file(self) -> String { + println!("文件路径 {}。", &self.path); let file = match File::open(&self.path) { - Ok(file) => file, + Ok(file) => { + println!("成功找到文件。"); + file + }, Err(err) => { println!("无法打开文件: {}", err); return String::from("Sorry, 找不到此博客。"); -- Gitee From 3be3591daf9da3bee5e2efe51837ffc7b444d89b Mon Sep 17 00:00:00 2001 From: owen Date: Sat, 15 Jun 2024 00:49:59 +0800 Subject: [PATCH 031/115] add log --- src/main.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main.rs b/src/main.rs index 0987b77..6d5ca70 100644 --- a/src/main.rs +++ b/src/main.rs @@ -87,7 +87,7 @@ async fn article_detail(Path(id): Path){ .bind(id) .fetch_one(&pool).await.expect("Can not find the article detail"); println!("the article detail {:?}", &article); - article.read_file(); + article.read_file().await; } async fn me() -> Person<'static>{ -- Gitee From 76ab2be2737c1c02f9f0ac852a953f4b5a72cdfa Mon Sep 17 00:00:00 2001 From: owen Date: Sat, 15 Jun 2024 02:04:25 +0800 Subject: [PATCH 032/115] readme add notice, add blog detail page --- README.md | 7 ++++++ src/entity/article.rs | 8 ++++-- src/entity/article_detail.rs | 36 +++++++++++++++++++++++++++ src/entity/article_summary.rs | 2 +- src/entity/mod.rs | 1 + src/main.rs | 26 ++++++++++++++------ templates/html/blog.html | 46 +++++++++++++++++++++++++++++++++++ 7 files changed, 115 insertions(+), 11 deletions(-) create mode 100644 src/entity/article_detail.rs create mode 100644 templates/html/blog.html diff --git a/README.md b/README.md index c870904..1ca5e9f 100644 --- a/README.md +++ b/README.md @@ -11,3 +11,10 @@ #### 技术细节 模板默认是放在名为templates文件夹下,此文件夹下可以有子文件夹, 使用#[template(path="./me/index.html")]绑定实体struct和模板文件。 + + +### 注意 + + +- 文件名建议中文,如果是英文的话,如果路径中使用反斜杠那么名字可能被转移,例如\test.md, \t 就被当作换行符。 +- 路径名为全路径名称 \ No newline at end of file diff --git a/src/entity/article.rs b/src/entity/article.rs index 579e4d7..2e15b68 100644 --- a/src/entity/article.rs +++ b/src/entity/article.rs @@ -2,7 +2,7 @@ use std::fs::File; use std::io::BufReader; use std::io::Read; -use chrono::{NaiveDateTime, Utc, DateTime}; +use chrono::{NaiveDateTime}; #[derive(Clone)] #[derive(Debug)] @@ -21,7 +21,7 @@ pub struct Article { } impl Article { - pub async fn read_file(self) -> String { + pub async fn read_file(&self) -> String { println!("文件路径 {}。", &self.path); let file = match File::open(&self.path) { Ok(file) => { @@ -39,6 +39,10 @@ impl Article { println!("article content {}",&contents); contents } + + pub fn getInfo(self) -> (i32, String, NaiveDateTime) { + (self.id, self.title, self.createOn) + } } diff --git a/src/entity/article_detail.rs b/src/entity/article_detail.rs new file mode 100644 index 0000000..a10998e --- /dev/null +++ b/src/entity/article_detail.rs @@ -0,0 +1,36 @@ +use askama_axum::Template; + +use chrono::{NaiveDateTime}; + +#[derive(Clone)] +#[derive(Debug)] +#[derive(Template)] +#[template(path = "html/blog.html")] +pub struct ArticleDetail { + pub id: i32, + pub title: String, + pub categorys: Vec, + pub content: String, + pub createOn: NaiveDateTime, +} + +impl ArticleDetail { + pub fn new(id: i32, title: String, categorys: Vec, createOn: NaiveDateTime) ->Self { + ArticleDetail { + id, + title, + categorys, + content: String::new(), + createOn, + } + } + + pub fn setContent(mut self, content: String) -> Self { + self.content = content; + self + } +} + + + + diff --git a/src/entity/article_summary.rs b/src/entity/article_summary.rs index 6b2c700..8502ef9 100644 --- a/src/entity/article_summary.rs +++ b/src/entity/article_summary.rs @@ -1,4 +1,4 @@ -use chrono::{NaiveDateTime, Utc, DateTime}; +use chrono::{NaiveDateTime}; #[derive(Clone)] #[derive(Debug)] diff --git a/src/entity/mod.rs b/src/entity/mod.rs index 9f70794..67aa4b0 100644 --- a/src/entity/mod.rs +++ b/src/entity/mod.rs @@ -1,3 +1,4 @@ pub mod article; pub mod article_summary; pub mod article_summary_vec; +pub mod article_detail; diff --git a/src/main.rs b/src/main.rs index 6d5ca70..b6475fb 100644 --- a/src/main.rs +++ b/src/main.rs @@ -12,6 +12,7 @@ use crate::person::Person; use crate::entity::article::Article; use crate::entity::article_summary::ArticleSummary; use crate::entity::article_summary_vec::ArticleSummaryVec; +use crate::entity::article_detail::ArticleDetail; #[tokio::main] async fn main() { @@ -63,23 +64,29 @@ async fn article_list(Path(page_num): Path) -> ArticleSummaryVec{ let mut vec3: Vec = vec![]; for (position, article) in summary_vec.iter().enumerate() { println!("position: {}", position); - if (position%3==0){ + + match position%3 { + 0 => vec1.push(article.clone()), + 1 => vec2.push(article.clone()), + 2 => vec3.push(article.clone()), + _ => (), + } + /* + if position%3==0 { vec1.push(article.clone()); } - if (position%3==1){ + if position%3==1 { vec2.push(article.clone()); } - if (position%3==2){ + if position%3==2 { vec3.push(article.clone()); } + */ } ArticleSummaryVec::new(vec1, vec2, vec3, page_total, page_num) } - - - -async fn article_detail(Path(id): Path){ +async fn article_detail(Path(id): Path) -> ArticleDetail{ println!("the article id is {}", &id); let pool = MySqlPoolOptions::new() .connect("mysql://root:onny0620@localhost/blog").await.expect("failed to connect database."); @@ -87,7 +94,10 @@ async fn article_detail(Path(id): Path){ .bind(id) .fetch_one(&pool).await.expect("Can not find the article detail"); println!("the article detail {:?}", &article); - article.read_file().await; + let (article_id, article_title, article_create_on) = article.clone().getInfo(); + let mut article_detail = ArticleDetail::new(article_id, article_title, vec!(),article_create_on); + let content = article.read_file().await; + article_detail.setContent(content) } async fn me() -> Person<'static>{ diff --git a/templates/html/blog.html b/templates/html/blog.html new file mode 100644 index 0000000..dd3d06f --- /dev/null +++ b/templates/html/blog.html @@ -0,0 +1,46 @@ + + + + + + RustAll + + + + + +

    Rust All

    + +
    +
    +
    +
    + + + +
    +

    © 2023 你的公司名或个人名. All rights reserved.

    +
    + + + + + -- Gitee From 600d62e90de2594a3393af26fee5f1d65abba952 Mon Sep 17 00:00:00 2001 From: "owen.chao" Date: Sat, 15 Jun 2024 10:56:01 +0800 Subject: [PATCH 033/115] article detail page --- templates/html/blog.html | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/templates/html/blog.html b/templates/html/blog.html index dd3d06f..853bd4c 100644 --- a/templates/html/blog.html +++ b/templates/html/blog.html @@ -27,10 +27,14 @@ -

    Rust All

    + +

    hello

    + -
    -
    +
    + +
    +
    -- Gitee From 3525992ca9633332ebd595120a790607eed2165b Mon Sep 17 00:00:00 2001 From: owen Date: Sat, 15 Jun 2024 11:06:41 +0800 Subject: [PATCH 034/115] article detail test --- templates/html/blog.html | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/templates/html/blog.html b/templates/html/blog.html index 853bd4c..67fc4d5 100644 --- a/templates/html/blog.html +++ b/templates/html/blog.html @@ -28,11 +28,11 @@ -

    hello

    +

    {{title}}

    -
    - +
    +

    {{content}}

    -- Gitee From 60bda669c72b46c238ce6cd1945b66354047629f Mon Sep 17 00:00:00 2001 From: "owen.chao" Date: Sat, 15 Jun 2024 11:37:26 +0800 Subject: [PATCH 035/115] detail page modify --- templates/html/blog.html | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/templates/html/blog.html b/templates/html/blog.html index 67fc4d5..917dd8a 100644 --- a/templates/html/blog.html +++ b/templates/html/blog.html @@ -32,10 +32,7 @@
    -

    {{content}}

    -
    - -
    +
    @@ -44,7 +41,20 @@

    © 2023 你的公司名或个人名. All rights reserved.

    + + + -- Gitee From e2c531706690fbb4d186b5d1a607cc36c66d2fd4 Mon Sep 17 00:00:00 2001 From: owen Date: Sat, 15 Jun 2024 14:35:39 +0800 Subject: [PATCH 036/115] detial page --- templates/html/blog.html | 24 ++++++++++++------- ...blog_list (\345\211\257\346\234\254).html" | 9 ++++--- templates/html/blog_list.html | 2 -- 3 files changed, 19 insertions(+), 16 deletions(-) diff --git a/templates/html/blog.html b/templates/html/blog.html index 917dd8a..327af33 100644 --- a/templates/html/blog.html +++ b/templates/html/blog.html @@ -26,14 +26,19 @@ } - + -

    {{title}}

    - -
    -
    -
    +
    +
    +

    {{title}}

    +
    +
    +
    +
    +
    +
    +
    @@ -48,11 +53,12 @@ window.addEventListener('load', function() { var converter = new showdown.Converter(); - var text = `{{content}}`; - var html = converter.makeHtml(text); + var text = `## hello + - world + - world`; + var html = converter.makeHtml(text); console.log(html); document.getElementById("content").innerHTML=html; - } ); diff --git "a/templates/html/blog_list (\345\211\257\346\234\254).html" "b/templates/html/blog_list (\345\211\257\346\234\254).html" index 8648c35..4f68376 100644 --- "a/templates/html/blog_list (\345\211\257\346\234\254).html" +++ "b/templates/html/blog_list (\345\211\257\346\234\254).html" @@ -138,11 +138,10 @@ window.addEventListener('load', function() { var converter = new showdown.Converter(), - text = '# hello, markdown!', - html = converter.makeHtml(text); - console.log(html); - document.getElementById("hello").innerHTML=html; - + text = {{content}} + html = converter.makeHtml(text); + console.log(html); + document.getElementById("hello").innerHTML=html; } ); diff --git a/templates/html/blog_list.html b/templates/html/blog_list.html index d1344c8..ffa9f81 100644 --- a/templates/html/blog_list.html +++ b/templates/html/blog_list.html @@ -27,8 +27,6 @@ -

    Rust All

    -
    -- Gitee From 85966990eeb40ce79bc0b8e6820cea834fc2dd01 Mon Sep 17 00:00:00 2001 From: "owen.chao" Date: Sat, 15 Jun 2024 20:15:19 +0800 Subject: [PATCH 037/115] article detail --- templates/html/blog.html | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/templates/html/blog.html b/templates/html/blog.html index 327af33..b468c5a 100644 --- a/templates/html/blog.html +++ b/templates/html/blog.html @@ -53,9 +53,7 @@ window.addEventListener('load', function() { var converter = new showdown.Converter(); - var text = `## hello - - world - - world`; + var text = `{{content}}`; var html = converter.makeHtml(text); console.log(html); document.getElementById("content").innerHTML=html; -- Gitee From 6828a4de431e6dae9204697fa07cceec44b85164 Mon Sep 17 00:00:00 2001 From: owen Date: Sat, 15 Jun 2024 22:09:50 +0800 Subject: [PATCH 038/115] scheduler job --- Cargo.toml | 1 + src/job/mod.rs | 1 + src/job/update_blog.rs | 9 +++++++++ src/lib.rs | 1 + src/main.rs | 2 ++ templates/html/blog.html | 4 ++-- 6 files changed, 16 insertions(+), 2 deletions(-) create mode 100644 src/job/mod.rs create mode 100644 src/job/update_blog.rs diff --git a/Cargo.toml b/Cargo.toml index 30d89df..7d0cac6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -17,4 +17,5 @@ tower-http = { version = "0.5.2", features = ["fs", "trace"] } sqlx = { version = "0.7.4", features = ["mysql", "runtime-tokio", "macros", "chrono"] } chrono = "0.4.38" time = "0.3.36" +cron = "0.12.1" diff --git a/src/job/mod.rs b/src/job/mod.rs new file mode 100644 index 0000000..dd1aedd --- /dev/null +++ b/src/job/mod.rs @@ -0,0 +1 @@ +pub mod update_blog; diff --git a/src/job/update_blog.rs b/src/job/update_blog.rs new file mode 100644 index 0000000..ac664b3 --- /dev/null +++ b/src/job/update_blog.rs @@ -0,0 +1,9 @@ +use cron::Schedule; +use chrono::Utc; +use std::str::FromStr; + +struct RefreshJob { + path: String, + scheduler: Schedule, +} + diff --git a/src/lib.rs b/src/lib.rs index 781160f..24660cc 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -4,4 +4,5 @@ //pub mod traits; //pub mod common; pub mod entity; +pub mod job; diff --git a/src/main.rs b/src/main.rs index b6475fb..68445c5 100644 --- a/src/main.rs +++ b/src/main.rs @@ -109,3 +109,5 @@ async fn me() -> Person<'static>{ + + diff --git a/templates/html/blog.html b/templates/html/blog.html index b468c5a..fc6b41b 100644 --- a/templates/html/blog.html +++ b/templates/html/blog.html @@ -8,7 +8,7 @@ diff --git a/templates/html/blog_list.html b/templates/html/blog_list.html index 113987f..d8e5690 100644 --- a/templates/html/blog_list.html +++ b/templates/html/blog_list.html @@ -22,7 +22,7 @@ text-align: center; padding: 20px 0; position: relative; - margin-top: auto; /* 与min-height一起确保footer在内容不足时也能置底 */ + margin-top: 40px; /* 与min-height一起确保footer在内容不足时也能置底 */ } @@ -64,39 +64,35 @@
    {% endfor %}
    -
    +
    -
    -
    -
    -
    - -
    - -
    -
    - +
    +
    +
    + + +
    - - - -
    +
    +
    + +
    -- Gitee From b7c92e632ea43fc3d8a0992539cd2bc1489e9dae Mon Sep 17 00:00:00 2001 From: owen Date: Sun, 16 Jun 2024 22:28:07 +0800 Subject: [PATCH 041/115] page --- templates/html/blog_list.html | 63 ++++++++++++++++++++++++++++++----- 1 file changed, 55 insertions(+), 8 deletions(-) diff --git a/templates/html/blog_list.html b/templates/html/blog_list.html index d8e5690..459c6be 100644 --- a/templates/html/blog_list.html +++ b/templates/html/blog_list.html @@ -67,21 +67,19 @@
    -
    -
    +
    +
    -
    +
    @@ -101,6 +99,55 @@ + + + + -- Gitee From aff70f07b9ea784af5df3a5ac8f9c9dc379c9f50 Mon Sep 17 00:00:00 2001 From: owen Date: Sun, 16 Jun 2024 22:37:08 +0800 Subject: [PATCH 042/115] page --- templates/html/blog_list.html | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/templates/html/blog_list.html b/templates/html/blog_list.html index 459c6be..8b2c554 100644 --- a/templates/html/blog_list.html +++ b/templates/html/blog_list.html @@ -106,7 +106,7 @@ function reloadPages() { var current_page = 30; - var page_total = 40; + var page_total = 70; //nextPage and prePage control if(page_total===1){ @@ -129,6 +129,10 @@ if(current_page_min_num>10){ $("#prePage").attr("href", "/list/"+(current_page_min_num-1)); } + if(current_page_max_num"+current_page_min_num+""); -- Gitee From 95d1aa84bd8905b0ec89e040e74fc065b07cf6a1 Mon Sep 17 00:00:00 2001 From: owen Date: Sun, 16 Jun 2024 22:44:40 +0800 Subject: [PATCH 043/115] default home page --- src/main.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main.rs b/src/main.rs index 68445c5..872b6a9 100644 --- a/src/main.rs +++ b/src/main.rs @@ -21,7 +21,8 @@ async fn main() { let workspace = std::env::current_dir().unwrap(); println!("{:?}", workspace); - let router = Router::new().route("/", get(me)) + let router = Router::new().route("", get(article_list)) + .route("/", get(article_list)) .route("/list/:offset", get(article_list)) .route("/article/:id", get(article_detail)) .route("/me", get(me)) -- Gitee From b66756a5b86374825ac9c6611c1f04131cb9f7d4 Mon Sep 17 00:00:00 2001 From: "owen.chao" Date: Sun, 16 Jun 2024 23:00:51 +0800 Subject: [PATCH 044/115] bf --- src/main.rs | 6 +++--- templates/html/blog_list.html | 4 ++-- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/main.rs b/src/main.rs index 872b6a9..291cd15 100644 --- a/src/main.rs +++ b/src/main.rs @@ -21,8 +21,7 @@ async fn main() { let workspace = std::env::current_dir().unwrap(); println!("{:?}", workspace); - let router = Router::new().route("", get(article_list)) - .route("/", get(article_list)) + let router = Router::new().route("/", get(article_list)) .route("/list/:offset", get(article_list)) .route("/article/:id", get(article_detail)) .route("/me", get(me)) @@ -57,8 +56,9 @@ async fn article_list(Path(page_num): Path) -> ArticleSummaryVec{ let total: i32 = sqlx::query_scalar("select count(id) from article where deleted=0") .fetch_one(&pool) .await.expect("Query page total failed!"); + println!("total: {}",&total); let page_total = total/page_size; - + println!("total pages: {}",&page_total); println!("{:?}",&summary_vec); let mut vec1: Vec = vec![]; let mut vec2: Vec = vec![]; diff --git a/templates/html/blog_list.html b/templates/html/blog_list.html index 8b2c554..4d36758 100644 --- a/templates/html/blog_list.html +++ b/templates/html/blog_list.html @@ -105,8 +105,8 @@ - - - - + + + + + -- Gitee From 1a22f168a48a77678edda8757a19121302e100c0 Mon Sep 17 00:00:00 2001 From: owen Date: Thu, 20 Jun 2024 00:41:58 +0800 Subject: [PATCH 051/115] bf --- templates/html/blog_list.html | 12 ++---------- 1 file changed, 2 insertions(+), 10 deletions(-) diff --git a/templates/html/blog_list.html b/templates/html/blog_list.html index 61c9fa2..2b40b65 100644 --- a/templates/html/blog_list.html +++ b/templates/html/blog_list.html @@ -113,16 +113,8 @@ + + + + + + + + -- Gitee From 2cb76cdcb0f8376d3f7608731aee2d0a55bba499 Mon Sep 17 00:00:00 2001 From: owen Date: Thu, 20 Jun 2024 01:03:25 +0800 Subject: [PATCH 053/115] background --- templates/html/blog_list.html~ | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/templates/html/blog_list.html~ b/templates/html/blog_list.html~ index fede8b8..ba0c6f7 100644 --- a/templates/html/blog_list.html~ +++ b/templates/html/blog_list.html~ @@ -64,7 +64,7 @@
    {% for article in vec3 %} -
    +
    {{article.title|e}}

    {{article.summary|e}}

    -- Gitee From bb2d94791925856caa5e68543d72ba8652d9e0db Mon Sep 17 00:00:00 2001 From: owen Date: Thu, 20 Jun 2024 01:04:37 +0800 Subject: [PATCH 054/115] background --- templates/html/blog_list.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/templates/html/blog_list.html b/templates/html/blog_list.html index ba0c6f7..961716e 100644 --- a/templates/html/blog_list.html +++ b/templates/html/blog_list.html @@ -64,7 +64,7 @@
    {% for article in vec3 %} -
    +
    {{article.title|e}}

    {{article.summary|e}}

    -- Gitee From 5a9e18d79bef8efd545963b8349ed9e9553f89ca Mon Sep 17 00:00:00 2001 From: "owen.chao" Date: Thu, 20 Jun 2024 13:02:41 +0800 Subject: [PATCH 055/115] home page --- src/main.rs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/main.rs b/src/main.rs index 5fdb747..6d523d1 100644 --- a/src/main.rs +++ b/src/main.rs @@ -21,8 +21,8 @@ async fn main() { let workspace = std::env::current_dir().unwrap(); println!("{:?}", workspace); - let router = Router::new().route("/", get(article_list)) - .route("/list/:offset", get(article_list)) + let router = Router::new().route("/", get(me)) + .route("/list/:page_num", get(article_list)) .route("/article/:id", get(article_detail)) .route("/me", get(me)) .nest_service("/assets", tower_http::services::ServeDir::new("assets")); @@ -34,7 +34,7 @@ async fn main() { async fn say_hello()-> String{ let pool = MySqlPoolOptions::new() - .connect("mysql://user:pass@localhost/blog").await.expect("failed to connect database."); + .connect("mysql://root:onny0620@localhost/blog").await.expect("failed to connect database."); let row: (String,) = sqlx::query_as("SELECT 'hello world, Rust!'") .fetch_one(&pool).await.expect("failed!"); //assert_eq!(row.0, 150); @@ -47,7 +47,7 @@ async fn article_list(Path(page_num): Path) -> ArticleSummaryVec{ let offset = (page_num-1)*page_size; println!("the offset is {}", &offset); let pool = MySqlPoolOptions::new() - .connect("mysql://user:pass@localhost/blog").await.expect("failed to connect database."); + .connect("mysql://root:onny0620@localhost/blog").await.expect("failed to connect database."); let summary_vec: Vec= sqlx::query_as("SELECT id, title, categoryId, summary, createOn, createBy FROM article WHERE deleted=0 order by id desc limit ?, ? ") .bind(offset) .bind(page_size) @@ -90,7 +90,7 @@ async fn article_list(Path(page_num): Path) -> ArticleSummaryVec{ async fn article_detail(Path(id): Path) -> ArticleDetail{ println!("the article id is {}", &id); let pool = MySqlPoolOptions::new() - .connect("mysql://user:pass@localhost/blog").await.expect("failed to connect database."); + .connect("mysql://root:onny0620@localhost/blog").await.expect("failed to connect database."); let article: Article = sqlx::query_as("SELECT id, title, categoryId, summary, path, deleted, createOn, createBy, modifyOn, modifyBy FROM article WHERE ID=?") .bind(id) .fetch_one(&pool).await.expect("Can not find the article detail"); -- Gitee From 27eaddaecfb4c01e68e60d2d2c1826fe100d12fd Mon Sep 17 00:00:00 2001 From: owen Date: Sun, 23 Jun 2024 08:51:41 +0800 Subject: [PATCH 056/115] file extractor --- src/error/mod.rs | 0 src/job/file_extractor.rs | 41 +++++++++++++++++++++++++++++++++++++++ src/job/mod.rs | 2 ++ 3 files changed, 43 insertions(+) create mode 100644 src/error/mod.rs create mode 100644 src/job/file_extractor.rs diff --git a/src/error/mod.rs b/src/error/mod.rs new file mode 100644 index 0000000..e69de29 diff --git a/src/job/file_extractor.rs b/src/job/file_extractor.rs new file mode 100644 index 0000000..94a80e4 --- /dev/null +++ b/src/job/file_extractor.rs @@ -0,0 +1,41 @@ +use std::fs::DirEntry; +use std::path::Path; +use std::fs; +use std::io; + +use crate::entity::article::Article; + +pub struct Extractor<'a> { + path: &'a Path, +} + +impl Extractor<'_> { + // one possible implementation of walking a directory only visiting files + pub fn visit_dirs(path: &Path, cb: &dyn Fn(&DirEntry)) -> io::Result<()> { + let dir = Path::new(path); + if dir.is_dir() { + for entry in fs::read_dir(dir)? { + let entry = entry?; + let path = entry.path(); + if path.is_dir() { + Self::visit_dirs(&path, cb)?; + } else if path.is_file(){ + cb(&entry); + } else { + println!("it is not dir or file."); + } + } + } + Ok(()) + } + + pub fn extract(dirEntry: &DirEntry) -> Result{ + let article = Article::new(30, "test", "test","/home/test.md" ); + Ok(article) + } +} + + + + + diff --git a/src/job/mod.rs b/src/job/mod.rs index dd1aedd..8436450 100644 --- a/src/job/mod.rs +++ b/src/job/mod.rs @@ -1 +1,3 @@ pub mod update_blog; + +pub mod file_extractor; -- Gitee From 88c86be6bc0825d387693c355dbcffe5d23f9ff2 Mon Sep 17 00:00:00 2001 From: owen Date: Sun, 23 Jun 2024 23:10:26 +0800 Subject: [PATCH 057/115] file extractor --- src/job/file_extractor.rs | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/src/job/file_extractor.rs b/src/job/file_extractor.rs index 94a80e4..133874a 100644 --- a/src/job/file_extractor.rs +++ b/src/job/file_extractor.rs @@ -3,6 +3,8 @@ use std::path::Path; use std::fs; use std::io; +use sqlx::Pool; + use crate::entity::article::Article; pub struct Extractor<'a> { @@ -29,7 +31,17 @@ impl Extractor<'_> { Ok(()) } - pub fn extract(dirEntry: &DirEntry) -> Result{ + pub fn extract(dirEntry: &DirEntry, pool: &Pool) -> Result{ + let path = dirEntry.path().as_path(); + println!("the file name is {}", &path); + if let Some(extension) = &path.extension() { + let file_suffix = extension.to_str().unwrap(); + println!("The file extension is: {:?}", &file_suffix); + + + } else { + println!("The file has no extension."); + } let article = Article::new(30, "test", "test","/home/test.md" ); Ok(article) } -- Gitee From 02af4f641aa10425250acea340c9adb651daa0b7 Mon Sep 17 00:00:00 2001 From: owen Date: Sun, 23 Jun 2024 23:32:13 +0800 Subject: [PATCH 058/115] file extractor --- src/job/file_extractor.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/job/file_extractor.rs b/src/job/file_extractor.rs index 133874a..baedbad 100644 --- a/src/job/file_extractor.rs +++ b/src/job/file_extractor.rs @@ -51,3 +51,5 @@ impl Extractor<'_> { + + -- Gitee From 551892837205f89f4ae05c25bbbcb5dcafc376fb Mon Sep 17 00:00:00 2001 From: "owen.chao" Date: Tue, 25 Jun 2024 18:52:06 +0800 Subject: [PATCH 059/115] modify file extractor --- src/entity/article.rs | 4 +++- src/job/file_extractor.rs | 10 +++++----- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/src/entity/article.rs b/src/entity/article.rs index 2e15b68..23e38f6 100644 --- a/src/entity/article.rs +++ b/src/entity/article.rs @@ -21,7 +21,9 @@ pub struct Article { } impl Article { - pub async fn read_file(&self) -> String { + + + pub async fn read_file(&self) -> String { println!("文件路径 {}。", &self.path); let file = match File::open(&self.path) { Ok(file) => { diff --git a/src/job/file_extractor.rs b/src/job/file_extractor.rs index baedbad..94e8df9 100644 --- a/src/job/file_extractor.rs +++ b/src/job/file_extractor.rs @@ -4,6 +4,7 @@ use std::fs; use std::io; use sqlx::Pool; +use sqlx::MySql; use crate::entity::article::Article; @@ -31,9 +32,10 @@ impl Extractor<'_> { Ok(()) } - pub fn extract(dirEntry: &DirEntry, pool: &Pool) -> Result{ - let path = dirEntry.path().as_path(); - println!("the file name is {}", &path); + pub fn extract(dirEntry: &DirEntry, _pool: &Pool){ + let path_buf = dirEntry.path(); + let path = path_buf.as_path(); + println!("the file name is {:?}", &path); if let Some(extension) = &path.extension() { let file_suffix = extension.to_str().unwrap(); println!("The file extension is: {:?}", &file_suffix); @@ -42,8 +44,6 @@ impl Extractor<'_> { } else { println!("The file has no extension."); } - let article = Article::new(30, "test", "test","/home/test.md" ); - Ok(article) } } -- Gitee From e2a0d0c0ee063efd1cb06f951848c83d97d142ad Mon Sep 17 00:00:00 2001 From: owen Date: Tue, 25 Jun 2024 22:34:27 +0800 Subject: [PATCH 060/115] md --- src/job/file_extractor.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/job/file_extractor.rs b/src/job/file_extractor.rs index 94e8df9..eb32fc3 100644 --- a/src/job/file_extractor.rs +++ b/src/job/file_extractor.rs @@ -39,7 +39,9 @@ impl Extractor<'_> { if let Some(extension) = &path.extension() { let file_suffix = extension.to_str().unwrap(); println!("The file extension is: {:?}", &file_suffix); - + if file_suffix == 'md' { + + } } else { println!("The file has no extension."); -- Gitee From 106926b2ecc882ecb030caf9304b07bc9b368f6e Mon Sep 17 00:00:00 2001 From: owen Date: Thu, 27 Jun 2024 23:23:55 +0800 Subject: [PATCH 061/115] add test code for file extractor --- src/entity/article.rs | 53 ++++++------- src/job/file_extractor.rs | 46 +++++++---- src/job/update_blog.rs | 7 +- src/main.rs | 162 +++++++++++++++++++------------------- test/test.md | 3 + 5 files changed, 142 insertions(+), 129 deletions(-) create mode 100644 test/test.md diff --git a/src/entity/article.rs b/src/entity/article.rs index 23e38f6..3207a59 100644 --- a/src/entity/article.rs +++ b/src/entity/article.rs @@ -2,34 +2,31 @@ use std::fs::File; use std::io::BufReader; use std::io::Read; -use chrono::{NaiveDateTime}; +use chrono::NaiveDateTime; -#[derive(Clone)] -#[derive(Debug)] -#[derive(sqlx::FromRow)] +#[warn(dead_code)] +#[derive(Clone, Debug, sqlx::FromRow)] pub struct Article { - id: i32, - title: String, - categoryId: Option, - summary: String, - path: String, - deleted: bool, - createOn: NaiveDateTime, - createBy: String, - modifyOn: NaiveDateTime, - modifyBy: String, + id: i32, + title: String, + categoryId: Option, + summary: String, + path: String, + deleted: bool, + createOn: NaiveDateTime, + createBy: String, + modifyOn: NaiveDateTime, + modifyBy: String, } impl Article { - - - pub async fn read_file(&self) -> String { - println!("文件路径 {}。", &self.path); + pub async fn read_file(&self) -> String { + println!("文件路径 {}。", &self.path); let file = match File::open(&self.path) { Ok(file) => { - println!("成功找到文件。"); + println!("成功找到文件。"); file - }, + } Err(err) => { println!("无法打开文件: {}", err); return String::from("Sorry, 找不到此博客。"); @@ -37,14 +34,12 @@ impl Article { }; let mut buf_reader = BufReader::new(file); let mut contents = String::new(); - let _ = buf_reader.read_to_string(&mut contents); - println!("article content {}",&contents); - contents - } - - pub fn getInfo(self) -> (i32, String, NaiveDateTime) { + let _ = buf_reader.read_to_string(&mut contents); + println!("article content {}", &contents); + contents + } + + pub fn getInfo(self) -> (i32, String, NaiveDateTime) { (self.id, self.title, self.createOn) - } + } } - - diff --git a/src/job/file_extractor.rs b/src/job/file_extractor.rs index eb32fc3..010db8c 100644 --- a/src/job/file_extractor.rs +++ b/src/job/file_extractor.rs @@ -1,10 +1,10 @@ -use std::fs::DirEntry; -use std::path::Path; use std::fs; +use std::fs::DirEntry; use std::io; +use std::path::Path; -use sqlx::Pool; use sqlx::MySql; +use sqlx::Pool; use crate::entity::article::Article; @@ -14,7 +14,7 @@ pub struct Extractor<'a> { impl Extractor<'_> { // one possible implementation of walking a directory only visiting files - pub fn visit_dirs(path: &Path, cb: &dyn Fn(&DirEntry)) -> io::Result<()> { + pub fn visit_dirs(path: &Path, cb: &dyn Fn(&DirEntry)) -> io::Result<()> { let dir = Path::new(path); if dir.is_dir() { for entry in fs::read_dir(dir)? { @@ -22,7 +22,7 @@ impl Extractor<'_> { let path = entry.path(); if path.is_dir() { Self::visit_dirs(&path, cb)?; - } else if path.is_file(){ + } else if path.is_file() { cb(&entry); } else { println!("it is not dir or file."); @@ -31,27 +31,41 @@ impl Extractor<'_> { } Ok(()) } - - pub fn extract(dirEntry: &DirEntry, _pool: &Pool){ - let path_buf = dirEntry.path(); + + pub fn extract(dir_entry: &DirEntry, _pool: &Pool) { + let path_buf = dir_entry.path(); let path = path_buf.as_path(); println!("the file name is {:?}", &path); if let Some(extension) = &path.extension() { let file_suffix = extension.to_str().unwrap(); println!("The file extension is: {:?}", &file_suffix); - if file_suffix == 'md' { - + if file_suffix.to_lowercase() == "md" { + println!("-----------md file----------"); } - } else { println!("The file has no extension."); } } } +#[cfg(test)] +mod test { + use super::*; + use sqlx::mysql::MySqlPoolOptions; + use std::path::Path; + use tokio::test; - - - - - + #[tokio::test] + async fn test_extract() { + let mut path = Path::new("/home/owen/code/rust_project/axum-hello/test/"); + let pool = MySqlPoolOptions::new() + .connect("mysql://root:onny0620@localhost/blog") + .await + .expect("failed to connect database."); + for entry in path.read_dir().expect("read_dir call failed") { + if let Ok(entry) = entry { + Extractor::extract(&entry, &pool); + } + } + } +} diff --git a/src/job/update_blog.rs b/src/job/update_blog.rs index ac664b3..230c554 100644 --- a/src/job/update_blog.rs +++ b/src/job/update_blog.rs @@ -1,9 +1,6 @@ use cron::Schedule; -use chrono::Utc; -use std::str::FromStr; struct RefreshJob { - path: String, - scheduler: Schedule, + path: String, + scheduler: Schedule, } - diff --git a/src/main.rs b/src/main.rs index 6d523d1..73490db 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,114 +1,118 @@ use axum::{ + extract::{Extension, Path}, routing::get, Router, - extract::{Extension, Path} }; use sqlx::mysql::MySqlPoolOptions; -pub mod person; pub mod entity; +pub mod person; -use crate::person::Person; use crate::entity::article::Article; +use crate::entity::article_detail::ArticleDetail; use crate::entity::article_summary::ArticleSummary; use crate::entity::article_summary_vec::ArticleSummaryVec; -use crate::entity::article_detail::ArticleDetail; +use crate::person::Person; #[tokio::main] async fn main() { // build our application with a single route - - let workspace = std::env::current_dir().unwrap(); + + let workspace = std::env::current_dir().unwrap(); println!("{:?}", workspace); - - let router = Router::new().route("/", get(me)) - .route("/list/:page_num", get(article_list)) - .route("/article/:id", get(article_detail)) - .route("/me", get(me)) - .nest_service("/assets", tower_http::services::ServeDir::new("assets")); + + let router = Router::new() + .route("/", get(me)) + .route("/list/:page_num", get(article_list)) + .route("/article/:id", get(article_detail)) + .route("/me", get(me)) + .nest_service("/assets", tower_http::services::ServeDir::new("assets")); // run our app with hyper, listening globally on port 3000 let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap(); axum::serve(listener, router).await.unwrap(); } -async fn say_hello()-> String{ - let pool = MySqlPoolOptions::new() - .connect("mysql://root:onny0620@localhost/blog").await.expect("failed to connect database."); - let row: (String,) = sqlx::query_as("SELECT 'hello world, Rust!'") - .fetch_one(&pool).await.expect("failed!"); - //assert_eq!(row.0, 150); +async fn say_hello() -> String { + let pool = MySqlPoolOptions::new() + .connect("mysql://root:onny0620@localhost/blog") + .await + .expect("failed to connect database."); + + let row: (String,) = sqlx::query_as("SELECT 'hello world, Rust!'") + .fetch_one(&pool) + .await + .expect("failed!"); + //assert_eq!(row.0, 150); row.0 } -async fn article_list(Path(page_num): Path) -> ArticleSummaryVec{ +async fn article_list(Path(page_num): Path) -> ArticleSummaryVec { println!("page_num: {}", page_num); - let page_size :i32 = 9; - let offset = (page_num-1)*page_size; - println!("the offset is {}", &offset); - let pool = MySqlPoolOptions::new() - .connect("mysql://root:onny0620@localhost/blog").await.expect("failed to connect database."); - let summary_vec: Vec= sqlx::query_as("SELECT id, title, categoryId, summary, createOn, createBy FROM article WHERE deleted=0 order by id desc limit ?, ? ") + let page_size: i32 = 9; + let offset = (page_num - 1) * page_size; + println!("the offset is {}", &offset); + let pool = MySqlPoolOptions::new() + .connect("mysql://root:onny0620@localhost/blog") + .await + .expect("failed to connect database."); + let summary_vec: Vec= sqlx::query_as("SELECT id, title, categoryId, summary, createOn, createBy FROM article WHERE deleted=0 order by id desc limit ?, ? ") .bind(offset) - .bind(page_size) + .bind(page_size) .fetch_all(&pool).await.expect("failed!"); - //assert_eq!(row.0, 150); - let total: i32 = sqlx::query_scalar("select count(id) from article where deleted=0") - .fetch_one(&pool) - .await.expect("Query page total failed!"); - println!("total: {}",&total); - let page_total = ((total as f64 /page_size as f64).ceil()) as i32; - println!("total pages: {}",&page_total); - println!("{:?}",&summary_vec); - let mut vec1: Vec = vec![]; - let mut vec2: Vec = vec![]; - let mut vec3: Vec = vec![]; - for (position, article) in summary_vec.iter().enumerate() { - println!("position: {}", position); - - match position%3 { - 0 => vec1.push(article.clone()), - 1 => vec2.push(article.clone()), - 2 => vec3.push(article.clone()), - _ => (), - } - /* - if position%3==0 { - vec1.push(article.clone()); - } - if position%3==1 { - vec2.push(article.clone()); - } - if position%3==2 { - vec3.push(article.clone()); - } - */ - } - ArticleSummaryVec::new(vec1, vec2, vec3, page_total, page_num) + //assert_eq!(row.0, 150); + let total: i32 = sqlx::query_scalar("select count(id) from article where deleted=0") + .fetch_one(&pool) + .await + .expect("Query page total failed!"); + println!("total: {}", &total); + let page_total = ((total as f64 / page_size as f64).ceil()) as i32; + println!("total pages: {}", &page_total); + println!("{:?}", &summary_vec); + let mut vec1: Vec = vec![]; + let mut vec2: Vec = vec![]; + let mut vec3: Vec = vec![]; + for (position, article) in summary_vec.iter().enumerate() { + println!("position: {}", position); + + match position % 3 { + 0 => vec1.push(article.clone()), + 1 => vec2.push(article.clone()), + 2 => vec3.push(article.clone()), + _ => (), + } + /* + if position%3==0 { + vec1.push(article.clone()); + } + if position%3==1 { + vec2.push(article.clone()); + } + if position%3==2 { + vec3.push(article.clone()); + } + */ + } + ArticleSummaryVec::new(vec1, vec2, vec3, page_total, page_num) } -async fn article_detail(Path(id): Path) -> ArticleDetail{ - println!("the article id is {}", &id); - let pool = MySqlPoolOptions::new() - .connect("mysql://root:onny0620@localhost/blog").await.expect("failed to connect database."); - let article: Article = sqlx::query_as("SELECT id, title, categoryId, summary, path, deleted, createOn, createBy, modifyOn, modifyBy FROM article WHERE ID=?") +async fn article_detail(Path(id): Path) -> ArticleDetail { + println!("the article id is {}", &id); + let pool = MySqlPoolOptions::new() + .connect("mysql://root:onny0620@localhost/blog") + .await + .expect("failed to connect database."); + let article: Article = sqlx::query_as("SELECT id, title, categoryId, summary, path, deleted, createOn, createBy, modifyOn, modifyBy FROM article WHERE ID=?") .bind(id) .fetch_one(&pool).await.expect("Can not find the article detail"); - println!("the article detail {:?}", &article); - let (article_id, article_title, article_create_on) = article.clone().getInfo(); - let mut article_detail = ArticleDetail::new(article_id, article_title, vec!(),article_create_on); - let content = article.read_file().await; - article_detail.setContent(content) + println!("the article detail {:?}", &article); + let (article_id, article_title, article_create_on) = article.clone().getInfo(); + let mut article_detail = + ArticleDetail::new(article_id, article_title, vec![], article_create_on); + let content = article.read_file().await; + article_detail.setContent(content) } -async fn me() -> Person<'static>{ - Person{name:"Owen"} +async fn me() -> Person<'static> { + Person { name: "Owen" } } - - - - - - - - diff --git a/test/test.md b/test/test.md new file mode 100644 index 0000000..fe89366 --- /dev/null +++ b/test/test.md @@ -0,0 +1,3 @@ +sdf + +sdfd -- Gitee From ee8a995a37b8f830c15a93eaef52e49e2a7141cd Mon Sep 17 00:00:00 2001 From: owen Date: Fri, 28 Jun 2024 00:04:19 +0800 Subject: [PATCH 062/115] test code --- src/entity/article_summary.rs | 27 ++++++++++++++++++++++++++- src/job/file_extractor.rs | 5 ++--- 2 files changed, 28 insertions(+), 4 deletions(-) diff --git a/src/entity/article_summary.rs b/src/entity/article_summary.rs index 8502ef9..790ffa4 100644 --- a/src/entity/article_summary.rs +++ b/src/entity/article_summary.rs @@ -1,4 +1,4 @@ -use chrono::{NaiveDateTime}; +use chrono::{NaiveDateTime, Utc}; #[derive(Clone)] #[derive(Debug)] @@ -12,4 +12,29 @@ pub struct ArticleSummary { pub createBy: String, } +impl ArticleSummary { + pub fn new(title: &str, summary: &str)->Self{ + ArticleSummary{ + id: 0, + title: title.to_string(), + categoryId: Some(0), + summary: summary.to_string(), + createOn: Utc::now().naive_utc(), + createBy: "Admin".to_string(); + } + + } + +} + +#[cfg(test)] +mod test { + use super::*; + + #[test] + fn test_new() { + let article_sumary = ArticleSummary::new("test_title", "test_summary"); + assert_eq!(article_sumary.title, "test_title"); + } +} diff --git a/src/job/file_extractor.rs b/src/job/file_extractor.rs index 010db8c..9cb91bf 100644 --- a/src/job/file_extractor.rs +++ b/src/job/file_extractor.rs @@ -43,7 +43,7 @@ impl Extractor<'_> { println!("-----------md file----------"); } } else { - println!("The file has no extension."); + println!("Can not find markdown file."); } } } @@ -53,11 +53,10 @@ mod test { use super::*; use sqlx::mysql::MySqlPoolOptions; use std::path::Path; - use tokio::test; #[tokio::test] async fn test_extract() { - let mut path = Path::new("/home/owen/code/rust_project/axum-hello/test/"); + let path = Path::new("/home/owen/code/rust_project/axum-hello/test/"); let pool = MySqlPoolOptions::new() .connect("mysql://root:onny0620@localhost/blog") .await -- Gitee From d2701a063b7c192ebe478d85cd7fc861b6a3331c Mon Sep 17 00:00:00 2001 From: owen Date: Sun, 30 Jun 2024 20:11:16 +0800 Subject: [PATCH 063/115] file extractor --- src/entity/article_summary.rs | 27 +++++++----------- src/job/file_extractor.rs | 54 +++++++++++++++++++++++++++++------ 2 files changed, 57 insertions(+), 24 deletions(-) diff --git a/src/entity/article_summary.rs b/src/entity/article_summary.rs index 790ffa4..29f3502 100644 --- a/src/entity/article_summary.rs +++ b/src/entity/article_summary.rs @@ -1,31 +1,26 @@ use chrono::{NaiveDateTime, Utc}; -#[derive(Clone)] -#[derive(Debug)] -#[derive(sqlx::FromRow)] +#[derive(Clone, Debug, sqlx::FromRow)] pub struct ArticleSummary { - pub id: i32, - pub title: String, - pub categoryId: Option, - pub summary: String, - pub createOn: NaiveDateTime, - pub createBy: String, + pub id: i32, + pub title: String, + pub categoryId: Option, + pub summary: String, + pub createOn: NaiveDateTime, + pub createBy: String, } impl ArticleSummary { - - pub fn new(title: &str, summary: &str)->Self{ - ArticleSummary{ + pub fn new(title: &str, summary: &str) -> Self { + ArticleSummary { id: 0, title: title.to_string(), categoryId: Some(0), summary: summary.to_string(), - createOn: Utc::now().naive_utc(), - createBy: "Admin".to_string(); + createOn: Utc::now().naive_utc(), + createBy: "Admin".to_string(), } - } - } #[cfg(test)] diff --git a/src/job/file_extractor.rs b/src/job/file_extractor.rs index 9cb91bf..795f5a4 100644 --- a/src/job/file_extractor.rs +++ b/src/job/file_extractor.rs @@ -1,12 +1,14 @@ use std::fs; use std::fs::DirEntry; +use std::fs::File; use std::io; +use std::io::{BufRead, BufReader, Error, ErrorKind}; use std::path::Path; use sqlx::MySql; use sqlx::Pool; -use crate::entity::article::Article; +use crate::entity::article_summary::ArticleSummary; pub struct Extractor<'a> { path: &'a Path, @@ -32,19 +34,53 @@ impl Extractor<'_> { Ok(()) } - pub fn extract(dir_entry: &DirEntry, _pool: &Pool) { - let path_buf = dir_entry.path(); - let path = path_buf.as_path(); - println!("the file name is {:?}", &path); - if let Some(extension) = &path.extension() { - let file_suffix = extension.to_str().unwrap(); + pub async fn extract(dir_entry: &DirEntry, pool: &Pool) -> Result<(), Error> { + let path = dir_entry.path(); + println!("the file name is {:?}", &path.file_name()); + if let Some(extension) = path.extension() { + let file_suffix = extension + .to_str() + .ok_or_else(|| Error::new(ErrorKind::InvalidData, "Invalid file suffix"))?; println!("The file extension is: {:?}", &file_suffix); if file_suffix.to_lowercase() == "md" { println!("-----------md file----------"); + let file = File::open(&path)?; + let buffer = BufReader::new(file); + let mut summary = String::new(); + for line in buffer.lines() { + let line = line?; + if line.trim().is_empty() { + println!("The summary has been read."); + break; + } + if !summary.is_empty() { + summary.push('\n'); + } + summary.push_str(&line); + } + let article_summary = ArticleSummary::new( + path.file_name() + .ok_or_else(|| Error::new(ErrorKind::InvalidInput, "Invalid file name"))? + .to_str() + .ok_or_else(|| { + Error::new(ErrorKind::InvalidData, "File name is not valid UTF-8") + })?, + summary.as_str(), + ); + println!("{:?}", article_summary); + //insert into database + sqlx::query!( + r#"INSERT INTO articles (title, body) VALUES (?, ?)"#, + article_summary.title, + article_summary.summary + ) + .execute(pool) + .await?; } } else { println!("Can not find markdown file."); } + Ok(()) } } @@ -57,13 +93,15 @@ mod test { #[tokio::test] async fn test_extract() { let path = Path::new("/home/owen/code/rust_project/axum-hello/test/"); + let pool = MySqlPoolOptions::new() .connect("mysql://root:onny0620@localhost/blog") .await .expect("failed to connect database."); + for entry in path.read_dir().expect("read_dir call failed") { if let Ok(entry) = entry { - Extractor::extract(&entry, &pool); + let _ = Extractor::extract(&entry, &pool); } } } -- Gitee From 6229be8e33a9eec083ef671abaa3e2c0d1b093a4 Mon Sep 17 00:00:00 2001 From: owen Date: Sun, 30 Jun 2024 20:26:19 +0800 Subject: [PATCH 064/115] delete markdown file --- src/job/file_extractor.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/job/file_extractor.rs b/src/job/file_extractor.rs index 795f5a4..f371dc4 100644 --- a/src/job/file_extractor.rs +++ b/src/job/file_extractor.rs @@ -76,6 +76,9 @@ impl Extractor<'_> { ) .execute(pool) .await?; + println!("insert a article summary!"); + //remove markdown file + fs::remove_file(path); } } else { println!("Can not find markdown file."); -- Gitee From 9727cb120ea4434463c63cffdf9cccd2d53295cf Mon Sep 17 00:00:00 2001 From: owen Date: Sun, 30 Jun 2024 22:04:48 +0800 Subject: [PATCH 065/115] try to call function extractor --- src/job/file_extractor.rs | 12 +++++++++--- src/main.rs | 13 +++++++++++++ 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/src/job/file_extractor.rs b/src/job/file_extractor.rs index f371dc4..fea4b5a 100644 --- a/src/job/file_extractor.rs +++ b/src/job/file_extractor.rs @@ -16,16 +16,20 @@ pub struct Extractor<'a> { impl Extractor<'_> { // one possible implementation of walking a directory only visiting files - pub fn visit_dirs(path: &Path, cb: &dyn Fn(&DirEntry)) -> io::Result<()> { + pub fn visit_dirs( + path: &Path, + pool: &Pool, + cb: &dyn Fn(&DirEntry, &Pool), + ) -> io::Result<()> { let dir = Path::new(path); if dir.is_dir() { for entry in fs::read_dir(dir)? { let entry = entry?; let path = entry.path(); if path.is_dir() { - Self::visit_dirs(&path, cb)?; + Self::visit_dirs(&path, pool, cb)?; } else if path.is_file() { - cb(&entry); + cb(&entry, pool); } else { println!("it is not dir or file."); } @@ -69,6 +73,7 @@ impl Extractor<'_> { ); println!("{:?}", article_summary); //insert into database + /* sqlx::query!( r#"INSERT INTO articles (title, body) VALUES (?, ?)"#, article_summary.title, @@ -76,6 +81,7 @@ impl Extractor<'_> { ) .execute(pool) .await?; + */ println!("insert a article summary!"); //remove markdown file fs::remove_file(path); diff --git a/src/main.rs b/src/main.rs index 73490db..838eff0 100644 --- a/src/main.rs +++ b/src/main.rs @@ -6,6 +6,7 @@ use axum::{ use sqlx::mysql::MySqlPoolOptions; pub mod entity; +pub mod job; pub mod person; use crate::entity::article::Article; @@ -14,6 +15,8 @@ use crate::entity::article_summary::ArticleSummary; use crate::entity::article_summary_vec::ArticleSummaryVec; use crate::person::Person; +use crate::job::file_extractor::Extractor; + #[tokio::main] async fn main() { // build our application with a single route @@ -21,6 +24,16 @@ async fn main() { let workspace = std::env::current_dir().unwrap(); println!("{:?}", workspace); + let pool = MySqlPoolOptions::new() + .connect("mysql://root:onny0620@localhost/blog") + .await + .expect("failed to connect database."); + Extractor::visit_dirs( + std::path::Path::new("/home/owen/code/rust_project/axum-hello"), + &pool, + &Extractor::extract, + ); + let router = Router::new() .route("/", get(me)) .route("/list/:page_num", get(article_list)) -- Gitee From 2e76687537ba494801fc763ec3535966b888c1a5 Mon Sep 17 00:00:00 2001 From: owen Date: Sun, 30 Jun 2024 22:42:10 +0800 Subject: [PATCH 066/115] extractor modify --- src/job/file_extractor.rs | 14 +++++--------- src/main.rs | 3 +-- 2 files changed, 6 insertions(+), 11 deletions(-) diff --git a/src/job/file_extractor.rs b/src/job/file_extractor.rs index fea4b5a..211b59e 100644 --- a/src/job/file_extractor.rs +++ b/src/job/file_extractor.rs @@ -16,20 +16,16 @@ pub struct Extractor<'a> { impl Extractor<'_> { // one possible implementation of walking a directory only visiting files - pub fn visit_dirs( - path: &Path, - pool: &Pool, - cb: &dyn Fn(&DirEntry, &Pool), - ) -> io::Result<()> { + pub fn visit_dirs(path: &Path, pool: &Pool) -> io::Result<()> { let dir = Path::new(path); if dir.is_dir() { for entry in fs::read_dir(dir)? { let entry = entry?; let path = entry.path(); if path.is_dir() { - Self::visit_dirs(&path, pool, cb)?; + let _ = Self::visit_dirs(&path, pool); } else if path.is_file() { - cb(&entry, pool); + let _ = Extractor::extract(&entry, pool); } else { println!("it is not dir or file."); } @@ -73,7 +69,7 @@ impl Extractor<'_> { ); println!("{:?}", article_summary); //insert into database - /* + sqlx::query!( r#"INSERT INTO articles (title, body) VALUES (?, ?)"#, article_summary.title, @@ -81,7 +77,7 @@ impl Extractor<'_> { ) .execute(pool) .await?; - */ + println!("insert a article summary!"); //remove markdown file fs::remove_file(path); diff --git a/src/main.rs b/src/main.rs index 838eff0..abaa664 100644 --- a/src/main.rs +++ b/src/main.rs @@ -28,10 +28,9 @@ async fn main() { .connect("mysql://root:onny0620@localhost/blog") .await .expect("failed to connect database."); - Extractor::visit_dirs( + let _ = Extractor::visit_dirs( std::path::Path::new("/home/owen/code/rust_project/axum-hello"), &pool, - &Extractor::extract, ); let router = Router::new() -- Gitee From 0ed76a6172ef18b9d2b941f52b4204cdbabca513 Mon Sep 17 00:00:00 2001 From: "owen.chao" Date: Thu, 4 Jul 2024 19:07:12 +0800 Subject: [PATCH 067/115] add insert UT code --- src/job/file_extractor.rs | 8 +++++--- src/main.rs | 39 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+), 3 deletions(-) diff --git a/src/job/file_extractor.rs b/src/job/file_extractor.rs index 211b59e..b49ada0 100644 --- a/src/job/file_extractor.rs +++ b/src/job/file_extractor.rs @@ -69,15 +69,15 @@ impl Extractor<'_> { ); println!("{:?}", article_summary); //insert into database - +/* sqlx::query!( - r#"INSERT INTO articles (title, body) VALUES (?, ?)"#, + r#"INSERT INTO articles (title, summary) VALUES (?, ?)"#, article_summary.title, article_summary.summary ) .execute(pool) .await?; - +*/ println!("insert a article summary!"); //remove markdown file fs::remove_file(path); @@ -110,4 +110,6 @@ mod test { } } } + + } diff --git a/src/main.rs b/src/main.rs index abaa664..51227f1 100644 --- a/src/main.rs +++ b/src/main.rs @@ -128,3 +128,42 @@ async fn article_detail(Path(id): Path) -> ArticleDetail { async fn me() -> Person<'static> { Person { name: "Owen" } } + + + + +#[cfg(test)] +mod test { + use super::*; + use sqlx::mysql::MySqlPoolOptions; + use std::path::Path; + + #[tokio::test] + async fn test_extract() { + let path = Path::new("/home/owen/code/rust_project/axum-hello/test/"); + + let pool = MySqlPoolOptions::new() + .connect("mysql://root:onny0620@localhost/blog") + .await + .expect("failed to connect database."); + + for entry in path.read_dir().expect("read_dir call failed") { + if let Ok(entry) = entry { + let _ = Extractor::extract(&entry, &pool); + } + } + } + + #[tokio::test] + async fn insert_db(){ + let pool = MySqlPoolOptions::new() + .connect("mysql://root:onny0620@localhost/blog") + .await + .expect("failed to connect database."); + + sqlx::query( + r#"INSERT INTO articles (title, summary) VALUES ('UT', 'summary')"# + ).execute(&pool).await; + } +} + -- Gitee From 6f877e1ade0b8c446d4281613f5a1e23dcfcddde Mon Sep 17 00:00:00 2001 From: "owen.chao" Date: Fri, 5 Jul 2024 14:53:47 +0800 Subject: [PATCH 068/115] insert recrod into database --- src/main.rs | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/src/main.rs b/src/main.rs index 51227f1..7c97bb8 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,9 +1,10 @@ use axum::{ - extract::{Extension, Path}, + extract::Path, routing::get, Router, }; use sqlx::mysql::MySqlPoolOptions; +use sqlx::MySqlPool; pub mod entity; pub mod job; @@ -45,6 +46,7 @@ async fn main() { axum::serve(listener, router).await.unwrap(); } +#[warn(dead_code)] async fn say_hello() -> String { let pool = MySqlPoolOptions::new() .connect("mysql://root:onny0620@localhost/blog") @@ -110,16 +112,24 @@ async fn article_list(Path(page_num): Path) -> ArticleSummaryVec { async fn article_detail(Path(id): Path) -> ArticleDetail { println!("the article id is {}", &id); - let pool = MySqlPoolOptions::new() + let mut pool = MySqlPoolOptions::new() .connect("mysql://root:onny0620@localhost/blog") .await .expect("failed to connect database."); let article: Article = sqlx::query_as("SELECT id, title, categoryId, summary, path, deleted, createOn, createBy, modifyOn, modifyBy FROM article WHERE ID=?") .bind(id) .fetch_one(&pool).await.expect("Can not find the article detail"); + + let mysql_conn = MySqlPool::connect("mysql://root:onny0620@localhost/blog").await.expect("Failed to connect to database"); + + let _ = sqlx::query( + r#"INSERT INTO article (title, summary, path, createBy, createOn, modifyBy, modifyOn) VALUES ('UT', 'summary', 'E:\\test.md', 'admin', now(), 'admin',now() )"# + ).execute(&mysql_conn).await.expect("INsert article failed"); + + println!("the article detail {:?}", &article); let (article_id, article_title, article_create_on) = article.clone().getInfo(); - let mut article_detail = + let article_detail = ArticleDetail::new(article_id, article_title, vec![], article_create_on); let content = article.read_file().await; article_detail.setContent(content) @@ -156,6 +166,7 @@ mod test { #[tokio::test] async fn insert_db(){ + println!("insert article into db"); let pool = MySqlPoolOptions::new() .connect("mysql://root:onny0620@localhost/blog") .await -- Gitee From f3ea9d6d8d17d51affb1d6720a0bc7e7a520e06e Mon Sep 17 00:00:00 2001 From: "owen.chao" Date: Fri, 5 Jul 2024 18:46:59 +0800 Subject: [PATCH 069/115] remove unuseful mut --- .gitignore | 1 + src/main.rs | 19 ++++++------------- 2 files changed, 7 insertions(+), 13 deletions(-) diff --git a/.gitignore b/.gitignore index ff47c2d..353c2a1 100644 --- a/.gitignore +++ b/.gitignore @@ -2,6 +2,7 @@ # will have compiled files and executables debug/ target/ +.lapce/ # Remove Cargo.lock from gitignore if creating an executable, leave it for libraries # More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html diff --git a/src/main.rs b/src/main.rs index 7c97bb8..56eb29a 100644 --- a/src/main.rs +++ b/src/main.rs @@ -112,7 +112,7 @@ async fn article_list(Path(page_num): Path) -> ArticleSummaryVec { async fn article_detail(Path(id): Path) -> ArticleDetail { println!("the article id is {}", &id); - let mut pool = MySqlPoolOptions::new() + let pool = MySqlPoolOptions::new() .connect("mysql://root:onny0620@localhost/blog") .await .expect("failed to connect database."); @@ -120,11 +120,7 @@ async fn article_detail(Path(id): Path) -> ArticleDetail { .bind(id) .fetch_one(&pool).await.expect("Can not find the article detail"); - let mysql_conn = MySqlPool::connect("mysql://root:onny0620@localhost/blog").await.expect("Failed to connect to database"); - - let _ = sqlx::query( - r#"INSERT INTO article (title, summary, path, createBy, createOn, modifyBy, modifyOn) VALUES ('UT', 'summary', 'E:\\test.md', 'admin', now(), 'admin',now() )"# - ).execute(&mysql_conn).await.expect("INsert article failed"); + println!("the article detail {:?}", &article); @@ -167,14 +163,11 @@ mod test { #[tokio::test] async fn insert_db(){ println!("insert article into db"); - let pool = MySqlPoolOptions::new() - .connect("mysql://root:onny0620@localhost/blog") - .await - .expect("failed to connect database."); + let mysql_conn = MySqlPool::connect("mysql://root:onny0620@localhost/blog").await.expect("Failed to connect to database"); - sqlx::query( - r#"INSERT INTO articles (title, summary) VALUES ('UT', 'summary')"# - ).execute(&pool).await; + let _ = sqlx::query( + r#"INSERT INTO article (title, summary, path, createBy, createOn, modifyBy, modifyOn) VALUES ('UT', 'summary', 'E:\\test.md', 'admin', now(), 'admin',now() )"# + ).execute(&mysql_conn).await.expect("INsert article failed"); } } -- Gitee From 2dd3db3bd3e2d6fd03dd7428c6b6b0fc4599cf84 Mon Sep 17 00:00:00 2001 From: "owen.chao" Date: Fri, 5 Jul 2024 18:58:35 +0800 Subject: [PATCH 070/115] test code insert db --- src/main.rs | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/src/main.rs b/src/main.rs index 56eb29a..ad8eedd 100644 --- a/src/main.rs +++ b/src/main.rs @@ -120,9 +120,6 @@ async fn article_detail(Path(id): Path) -> ArticleDetail { .bind(id) .fetch_one(&pool).await.expect("Can not find the article detail"); - - - println!("the article detail {:?}", &article); let (article_id, article_title, article_create_on) = article.clone().getInfo(); let article_detail = @@ -163,11 +160,16 @@ mod test { #[tokio::test] async fn insert_db(){ println!("insert article into db"); - let mysql_conn = MySqlPool::connect("mysql://root:onny0620@localhost/blog").await.expect("Failed to connect to database"); + //let mysql_conn = MySqlPool::connect("mysql://root:onny0620@localhost/blog").await.expect("Failed to connect to database"); + + let mysql_conn = MySqlPoolOptions::new() + .connect("mysql://root:onny0620@localhost/blog") + .await + .expect("failed to connect database."); let _ = sqlx::query( - r#"INSERT INTO article (title, summary, path, createBy, createOn, modifyBy, modifyOn) VALUES ('UT', 'summary', 'E:\\test.md', 'admin', now(), 'admin',now() )"# - ).execute(&mysql_conn).await.expect("INsert article failed"); + r#"INSERT INTO article (title, summary, path, createBy, createOn, modifyBy, modifyOn) VALUES ('UT', '鸿蒙系统', 'E:\\test.md', 'Owwww', now(), 'YYYY',now() )"# + ).execute(&mysql_conn).await; } } -- Gitee From 855661a686669903ffac56d4869bb2a95686b075 Mon Sep 17 00:00:00 2001 From: "owen.chao" Date: Fri, 5 Jul 2024 19:14:03 +0800 Subject: [PATCH 071/115] file extractor insert db --- src/job/file_extractor.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/job/file_extractor.rs b/src/job/file_extractor.rs index b49ada0..952bc91 100644 --- a/src/job/file_extractor.rs +++ b/src/job/file_extractor.rs @@ -68,6 +68,9 @@ impl Extractor<'_> { summary.as_str(), ); println!("{:?}", article_summary); + let _ = sqlx::query( + r#"INSERT INTO article (title, summary, path, createBy, createOn, modifyBy, modifyOn) VALUES ('UT', '鸿蒙系统', 'E:\\test.md', 'Owwww', now(), 'YYYY',now() )"# + ).execute(pool).await; //insert into database /* sqlx::query!( -- Gitee From 9950d9d17ba0f472dc8002b5d33396104bb3cd0e Mon Sep 17 00:00:00 2001 From: "owen.chao" Date: Fri, 5 Jul 2024 19:30:35 +0800 Subject: [PATCH 072/115] file extractor --- src/job/file_extractor.rs | 5 +++-- src/main.rs | 7 +++++++ 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/src/job/file_extractor.rs b/src/job/file_extractor.rs index 952bc91..2d122aa 100644 --- a/src/job/file_extractor.rs +++ b/src/job/file_extractor.rs @@ -16,7 +16,7 @@ pub struct Extractor<'a> { impl Extractor<'_> { // one possible implementation of walking a directory only visiting files - pub fn visit_dirs(path: &Path, pool: &Pool) -> io::Result<()> { + pub async fn visit_dirs(path: &Path, pool: &Pool) -> io::Result<()> { let dir = Path::new(path); if dir.is_dir() { for entry in fs::read_dir(dir)? { @@ -25,9 +25,10 @@ impl Extractor<'_> { if path.is_dir() { let _ = Self::visit_dirs(&path, pool); } else if path.is_file() { - let _ = Extractor::extract(&entry, pool); + let _ = Extractor::extract(&entry, pool).await.expect("error"); } else { println!("it is not dir or file."); + panic!("it is not dir or file."); } } } diff --git a/src/main.rs b/src/main.rs index ad8eedd..dd2b10d 100644 --- a/src/main.rs +++ b/src/main.rs @@ -116,6 +116,13 @@ async fn article_detail(Path(id): Path) -> ArticleDetail { .connect("mysql://root:onny0620@localhost/blog") .await .expect("failed to connect database."); + + + let _ = Extractor::visit_dirs( + std::path::Path::new("/home/owen/code/rust_project/axum-hello"), + &pool, + ).await.expect("error error"); + let article: Article = sqlx::query_as("SELECT id, title, categoryId, summary, path, deleted, createOn, createBy, modifyOn, modifyBy FROM article WHERE ID=?") .bind(id) .fetch_one(&pool).await.expect("Can not find the article detail"); -- Gitee From dcf44704c49b8967fdadb26b9184698275a87571 Mon Sep 17 00:00:00 2001 From: owen Date: Tue, 9 Jul 2024 23:47:19 +0800 Subject: [PATCH 073/115] add extract file mehtod --- src/main.rs | 59 +++++++++++++++++++++++++++-------------------------- 1 file changed, 30 insertions(+), 29 deletions(-) diff --git a/src/main.rs b/src/main.rs index dd2b10d..7cff527 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,8 +1,5 @@ -use axum::{ - extract::Path, - routing::get, - Router, -}; +use axum::extract; +use axum::{extract::Path, routing::get, Router}; use sqlx::mysql::MySqlPoolOptions; use sqlx::MySqlPool; @@ -39,6 +36,7 @@ async fn main() { .route("/list/:page_num", get(article_list)) .route("/article/:id", get(article_detail)) .route("/me", get(me)) + .route("/new", extract_article()) .nest_service("/assets", tower_http::services::ServeDir::new("assets")); // run our app with hyper, listening globally on port 3000 @@ -116,32 +114,36 @@ async fn article_detail(Path(id): Path) -> ArticleDetail { .connect("mysql://root:onny0620@localhost/blog") .await .expect("failed to connect database."); - - - let _ = Extractor::visit_dirs( - std::path::Path::new("/home/owen/code/rust_project/axum-hello"), - &pool, - ).await.expect("error error"); - + let article: Article = sqlx::query_as("SELECT id, title, categoryId, summary, path, deleted, createOn, createBy, modifyOn, modifyBy FROM article WHERE ID=?") .bind(id) .fetch_one(&pool).await.expect("Can not find the article detail"); - + println!("the article detail {:?}", &article); let (article_id, article_title, article_create_on) = article.clone().getInfo(); - let article_detail = - ArticleDetail::new(article_id, article_title, vec![], article_create_on); + let article_detail = ArticleDetail::new(article_id, article_title, vec![], article_create_on); let content = article.read_file().await; article_detail.setContent(content) } +pub async fn extract_article() { + let pool = MySqlPoolOptions::new() + .connect("mysql://root:onny0620@localhost/blog") + .await + .expect("failed to connect database."); + + let _ = Extractor::visit_dirs( + std::path::Path::new("/home/owen/code/rust_project/axum-hello"), + &pool, + ) + .await + .expect("extract article failed!!!"); +} + async fn me() -> Person<'static> { Person { name: "Owen" } } - - - #[cfg(test)] mod test { use super::*; @@ -163,20 +165,19 @@ mod test { } } } - + #[tokio::test] - async fn insert_db(){ + async fn insert_db() { println!("insert article into db"); - //let mysql_conn = MySqlPool::connect("mysql://root:onny0620@localhost/blog").await.expect("Failed to connect to database"); - + //let mysql_conn = MySqlPool::connect("mysql://root:onny0620@localhost/blog").await.expect("Failed to connect to database"); + let mysql_conn = MySqlPoolOptions::new() - .connect("mysql://root:onny0620@localhost/blog") - .await - .expect("failed to connect database."); - + .connect("mysql://root:onny0620@localhost/blog") + .await + .expect("failed to connect database."); + let _ = sqlx::query( r#"INSERT INTO article (title, summary, path, createBy, createOn, modifyBy, modifyOn) VALUES ('UT', '鸿蒙系统', 'E:\\test.md', 'Owwww', now(), 'YYYY',now() )"# - ).execute(&mysql_conn).await; - } + ).execute(&mysql_conn).await; + } } - -- Gitee From 18289d459dee2a4cb919ac8456218a07d14b81aa Mon Sep 17 00:00:00 2001 From: owen Date: Tue, 9 Jul 2024 23:50:13 +0800 Subject: [PATCH 074/115] add extract file mehtod --- src/main.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main.rs b/src/main.rs index 7cff527..e4dea3c 100644 --- a/src/main.rs +++ b/src/main.rs @@ -36,7 +36,7 @@ async fn main() { .route("/list/:page_num", get(article_list)) .route("/article/:id", get(article_detail)) .route("/me", get(me)) - .route("/new", extract_article()) + .route("/new", get(extract_article)) .nest_service("/assets", tower_http::services::ServeDir::new("assets")); // run our app with hyper, listening globally on port 3000 -- Gitee From ddb46864c2d07e44e645a82dc01e3e720f428d6f Mon Sep 17 00:00:00 2001 From: owen Date: Tue, 9 Jul 2024 23:53:17 +0800 Subject: [PATCH 075/115] add extract file mehtod --- src/job/file_extractor.rs | 24 +++++++++++------------- src/main.rs | 4 +--- 2 files changed, 12 insertions(+), 16 deletions(-) diff --git a/src/job/file_extractor.rs b/src/job/file_extractor.rs index 2d122aa..c691411 100644 --- a/src/job/file_extractor.rs +++ b/src/job/file_extractor.rs @@ -16,7 +16,7 @@ pub struct Extractor<'a> { impl Extractor<'_> { // one possible implementation of walking a directory only visiting files - pub async fn visit_dirs(path: &Path, pool: &Pool) -> io::Result<()> { + pub fn visit_dirs(path: &Path, pool: &Pool) -> io::Result<()> { let dir = Path::new(path); if dir.is_dir() { for entry in fs::read_dir(dir)? { @@ -71,17 +71,17 @@ impl Extractor<'_> { println!("{:?}", article_summary); let _ = sqlx::query( r#"INSERT INTO article (title, summary, path, createBy, createOn, modifyBy, modifyOn) VALUES ('UT', '鸿蒙系统', 'E:\\test.md', 'Owwww', now(), 'YYYY',now() )"# - ).execute(pool).await; + ).execute(pool).await; //insert into database -/* - sqlx::query!( - r#"INSERT INTO articles (title, summary) VALUES (?, ?)"#, - article_summary.title, - article_summary.summary - ) - .execute(pool) - .await?; -*/ + /* + sqlx::query!( + r#"INSERT INTO articles (title, summary) VALUES (?, ?)"#, + article_summary.title, + article_summary.summary + ) + .execute(pool) + .await?; + */ println!("insert a article summary!"); //remove markdown file fs::remove_file(path); @@ -114,6 +114,4 @@ mod test { } } } - - } diff --git a/src/main.rs b/src/main.rs index e4dea3c..b11d318 100644 --- a/src/main.rs +++ b/src/main.rs @@ -135,9 +135,7 @@ pub async fn extract_article() { let _ = Extractor::visit_dirs( std::path::Path::new("/home/owen/code/rust_project/axum-hello"), &pool, - ) - .await - .expect("extract article failed!!!"); + ); } async fn me() -> Person<'static> { -- Gitee From 5ca68a0ccdecaae849984d8f784fff6affe96161 Mon Sep 17 00:00:00 2001 From: owen Date: Tue, 9 Jul 2024 23:54:54 +0800 Subject: [PATCH 076/115] add extract file mehtod --- src/job/file_extractor.rs | 2 +- src/main.rs | 4 ---- 2 files changed, 1 insertion(+), 5 deletions(-) diff --git a/src/job/file_extractor.rs b/src/job/file_extractor.rs index c691411..6827efd 100644 --- a/src/job/file_extractor.rs +++ b/src/job/file_extractor.rs @@ -35,7 +35,7 @@ impl Extractor<'_> { Ok(()) } - pub async fn extract(dir_entry: &DirEntry, pool: &Pool) -> Result<(), Error> { + pub fn extract(dir_entry: &DirEntry, pool: &Pool) -> Result<(), Error> { let path = dir_entry.path(); println!("the file name is {:?}", &path.file_name()); if let Some(extension) = path.extension() { diff --git a/src/main.rs b/src/main.rs index b11d318..1820fb5 100644 --- a/src/main.rs +++ b/src/main.rs @@ -26,10 +26,6 @@ async fn main() { .connect("mysql://root:onny0620@localhost/blog") .await .expect("failed to connect database."); - let _ = Extractor::visit_dirs( - std::path::Path::new("/home/owen/code/rust_project/axum-hello"), - &pool, - ); let router = Router::new() .route("/", get(me)) -- Gitee From 814c4d7bff11a4e9786990019ac0e58b9d5745de Mon Sep 17 00:00:00 2001 From: owen Date: Wed, 10 Jul 2024 00:02:15 +0800 Subject: [PATCH 077/115] add extract file mehtod --- src/job/file_extractor.rs | 10 ++++++---- src/main.rs | 7 +++++-- 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/src/job/file_extractor.rs b/src/job/file_extractor.rs index 6827efd..084e393 100644 --- a/src/job/file_extractor.rs +++ b/src/job/file_extractor.rs @@ -16,7 +16,7 @@ pub struct Extractor<'a> { impl Extractor<'_> { // one possible implementation of walking a directory only visiting files - pub fn visit_dirs(path: &Path, pool: &Pool) -> io::Result<()> { + pub async fn visit_dirs(path: &Path, pool: &Pool) -> io::Result<()> { let dir = Path::new(path); if dir.is_dir() { for entry in fs::read_dir(dir)? { @@ -25,7 +25,9 @@ impl Extractor<'_> { if path.is_dir() { let _ = Self::visit_dirs(&path, pool); } else if path.is_file() { - let _ = Extractor::extract(&entry, pool).await.expect("error"); + let _ = Extractor::extract(&entry, pool) + .await + .expect("failed insert article!"); } else { println!("it is not dir or file."); panic!("it is not dir or file."); @@ -35,7 +37,7 @@ impl Extractor<'_> { Ok(()) } - pub fn extract(dir_entry: &DirEntry, pool: &Pool) -> Result<(), Error> { + pub async fn extract(dir_entry: &DirEntry, pool: &Pool) -> Result<(), Error> { let path = dir_entry.path(); println!("the file name is {:?}", &path.file_name()); if let Some(extension) = path.extension() { @@ -71,7 +73,7 @@ impl Extractor<'_> { println!("{:?}", article_summary); let _ = sqlx::query( r#"INSERT INTO article (title, summary, path, createBy, createOn, modifyBy, modifyOn) VALUES ('UT', '鸿蒙系统', 'E:\\test.md', 'Owwww', now(), 'YYYY',now() )"# - ).execute(pool).await; + ).execute(pool).await.expect("insert article failed"); //insert into database /* sqlx::query!( diff --git a/src/main.rs b/src/main.rs index 1820fb5..47cc0e0 100644 --- a/src/main.rs +++ b/src/main.rs @@ -122,7 +122,7 @@ async fn article_detail(Path(id): Path) -> ArticleDetail { article_detail.setContent(content) } -pub async fn extract_article() { +pub async fn extract_article() -> Result { let pool = MySqlPoolOptions::new() .connect("mysql://root:onny0620@localhost/blog") .await @@ -131,7 +131,10 @@ pub async fn extract_article() { let _ = Extractor::visit_dirs( std::path::Path::new("/home/owen/code/rust_project/axum-hello"), &pool, - ); + ) + .await + .expect_err("failed insert article"); + Ok(String::from("OK")) } async fn me() -> Person<'static> { -- Gitee From 02d66ed694fe5e7abc3a9936401d53583a2d2327 Mon Sep 17 00:00:00 2001 From: owen Date: Wed, 10 Jul 2024 00:13:36 +0800 Subject: [PATCH 078/115] add extract file mehtod --- src/job/file_extractor.rs | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/src/job/file_extractor.rs b/src/job/file_extractor.rs index 084e393..f572433 100644 --- a/src/job/file_extractor.rs +++ b/src/job/file_extractor.rs @@ -16,7 +16,7 @@ pub struct Extractor<'a> { impl Extractor<'_> { // one possible implementation of walking a directory only visiting files - pub async fn visit_dirs(path: &Path, pool: &Pool) -> io::Result<()> { + pub async fn visit_dirs(path: &Path, pool: &Pool) -> Result<(), Error> { let dir = Path::new(path); if dir.is_dir() { for entry in fs::read_dir(dir)? { @@ -25,11 +25,8 @@ impl Extractor<'_> { if path.is_dir() { let _ = Self::visit_dirs(&path, pool); } else if path.is_file() { - let _ = Extractor::extract(&entry, pool) - .await - .expect("failed insert article!"); + let _ = Extractor::extract(&entry, pool).await?; } else { - println!("it is not dir or file."); panic!("it is not dir or file."); } } -- Gitee From 40b58d49e19a86457d06682ca696f37579b22faa Mon Sep 17 00:00:00 2001 From: owen Date: Wed, 10 Jul 2024 00:21:02 +0800 Subject: [PATCH 079/115] add extract file mehtod --- src/job/file_extractor.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/job/file_extractor.rs b/src/job/file_extractor.rs index f572433..eb84b27 100644 --- a/src/job/file_extractor.rs +++ b/src/job/file_extractor.rs @@ -23,6 +23,7 @@ impl Extractor<'_> { let entry = entry?; let path = entry.path(); if path.is_dir() { + println!("is dir, loop into sub dir"); let _ = Self::visit_dirs(&path, pool); } else if path.is_file() { let _ = Extractor::extract(&entry, pool).await?; -- Gitee From 9cca6869b3cfe0bb8b81a592803799f26907070d Mon Sep 17 00:00:00 2001 From: "owen.chao" Date: Wed, 10 Jul 2024 13:40:35 +0800 Subject: [PATCH 080/115] now insert article successfully --- src/job/file_extractor.rs | 4 +++- src/main.rs | 15 ++++++++------- 2 files changed, 11 insertions(+), 8 deletions(-) diff --git a/src/job/file_extractor.rs b/src/job/file_extractor.rs index eb84b27..171a1fd 100644 --- a/src/job/file_extractor.rs +++ b/src/job/file_extractor.rs @@ -17,6 +17,7 @@ pub struct Extractor<'a> { impl Extractor<'_> { // one possible implementation of walking a directory only visiting files pub async fn visit_dirs(path: &Path, pool: &Pool) -> Result<(), Error> { + println!("-------------visit_dirs start--------------"); let dir = Path::new(path); if dir.is_dir() { for entry in fs::read_dir(dir)? { @@ -26,6 +27,7 @@ impl Extractor<'_> { println!("is dir, loop into sub dir"); let _ = Self::visit_dirs(&path, pool); } else if path.is_file() { + println!("-------------extract start--------------"); let _ = Extractor::extract(&entry, pool).await?; } else { panic!("it is not dir or file."); @@ -84,7 +86,7 @@ impl Extractor<'_> { */ println!("insert a article summary!"); //remove markdown file - fs::remove_file(path); + let _ = fs::remove_file(path); } } else { println!("Can not find markdown file."); diff --git a/src/main.rs b/src/main.rs index 47cc0e0..fdef296 100644 --- a/src/main.rs +++ b/src/main.rs @@ -3,6 +3,8 @@ use axum::{extract::Path, routing::get, Router}; use sqlx::mysql::MySqlPoolOptions; use sqlx::MySqlPool; +use std::io::Error; + pub mod entity; pub mod job; pub mod person; @@ -32,7 +34,7 @@ async fn main() { .route("/list/:page_num", get(article_list)) .route("/article/:id", get(article_detail)) .route("/me", get(me)) - .route("/new", get(extract_article)) + .route("/article/new", get(extract_article)) .nest_service("/assets", tower_http::services::ServeDir::new("assets")); // run our app with hyper, listening globally on port 3000 @@ -122,19 +124,18 @@ async fn article_detail(Path(id): Path) -> ArticleDetail { article_detail.setContent(content) } -pub async fn extract_article() -> Result { +pub async fn extract_article() { let pool = MySqlPoolOptions::new() .connect("mysql://root:onny0620@localhost/blog") .await .expect("failed to connect database."); let _ = Extractor::visit_dirs( - std::path::Path::new("/home/owen/code/rust_project/axum-hello"), + std::path::Path::new("E:\\rust\\markdown"), &pool, ) - .await - .expect_err("failed insert article"); - Ok(String::from("OK")) + .await.expect_err("failed insert article......"); + } async fn me() -> Person<'static> { @@ -149,7 +150,7 @@ mod test { #[tokio::test] async fn test_extract() { - let path = Path::new("/home/owen/code/rust_project/axum-hello/test/"); + let path = Path::new("E:\\test\\markdown"); let pool = MySqlPoolOptions::new() .connect("mysql://root:onny0620@localhost/blog") -- Gitee From c55df4754bff49f7e6c73094a1f41867c5c55950 Mon Sep 17 00:00:00 2001 From: "owen.chao" Date: Wed, 10 Jul 2024 19:03:36 +0800 Subject: [PATCH 081/115] use the global database connection --- src/main.rs | 17 +++++++---------- 1 file changed, 7 insertions(+), 10 deletions(-) diff --git a/src/main.rs b/src/main.rs index fdef296..6ebcf3a 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,5 +1,5 @@ use axum::extract; -use axum::{extract::Path, routing::get, Router}; +use axum::{extract::Path, routing::get, Router, extract::State}; use sqlx::mysql::MySqlPoolOptions; use sqlx::MySqlPool; @@ -35,7 +35,8 @@ async fn main() { .route("/article/:id", get(article_detail)) .route("/me", get(me)) .route("/article/new", get(extract_article)) - .nest_service("/assets", tower_http::services::ServeDir::new("assets")); + .nest_service("/assets", tower_http::services::ServeDir::new("assets")) + .with_state(pool); // run our app with hyper, listening globally on port 3000 let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap(); @@ -43,11 +44,7 @@ async fn main() { } #[warn(dead_code)] -async fn say_hello() -> String { - let pool = MySqlPoolOptions::new() - .connect("mysql://root:onny0620@localhost/blog") - .await - .expect("failed to connect database."); +async fn say_hello(State(pool): State) -> String { let row: (String,) = sqlx::query_as("SELECT 'hello world, Rust!'") .fetch_one(&pool) @@ -57,7 +54,7 @@ async fn say_hello() -> String { row.0 } -async fn article_list(Path(page_num): Path) -> ArticleSummaryVec { +async fn article_list(State(pool): State, Path(page_num): Path) -> ArticleSummaryVec { println!("page_num: {}", page_num); let page_size: i32 = 9; let offset = (page_num - 1) * page_size; @@ -106,7 +103,7 @@ async fn article_list(Path(page_num): Path) -> ArticleSummaryVec { ArticleSummaryVec::new(vec1, vec2, vec3, page_total, page_num) } -async fn article_detail(Path(id): Path) -> ArticleDetail { +async fn article_detail(State(pool): State, Path(id): Path) -> ArticleDetail { println!("the article id is {}", &id); let pool = MySqlPoolOptions::new() .connect("mysql://root:onny0620@localhost/blog") @@ -124,7 +121,7 @@ async fn article_detail(Path(id): Path) -> ArticleDetail { article_detail.setContent(content) } -pub async fn extract_article() { +pub async fn extract_article(State(pool): State) { let pool = MySqlPoolOptions::new() .connect("mysql://root:onny0620@localhost/blog") .await -- Gitee From 054eb81a2241aa4b30db25be1b06cdd2566d097e Mon Sep 17 00:00:00 2001 From: "owen.chao" Date: Wed, 10 Jul 2024 19:07:42 +0800 Subject: [PATCH 082/115] use global database connection pool, remove the connection pool in ervery method body --- src/main.rs | 13 +------------ 1 file changed, 1 insertion(+), 12 deletions(-) diff --git a/src/main.rs b/src/main.rs index 6ebcf3a..82484be 100644 --- a/src/main.rs +++ b/src/main.rs @@ -59,10 +59,7 @@ async fn article_list(State(pool): State, Path(page_num): Path) let page_size: i32 = 9; let offset = (page_num - 1) * page_size; println!("the offset is {}", &offset); - let pool = MySqlPoolOptions::new() - .connect("mysql://root:onny0620@localhost/blog") - .await - .expect("failed to connect database."); + let summary_vec: Vec= sqlx::query_as("SELECT id, title, categoryId, summary, createOn, createBy FROM article WHERE deleted=0 order by id desc limit ?, ? ") .bind(offset) .bind(page_size) @@ -105,10 +102,6 @@ async fn article_list(State(pool): State, Path(page_num): Path) async fn article_detail(State(pool): State, Path(id): Path) -> ArticleDetail { println!("the article id is {}", &id); - let pool = MySqlPoolOptions::new() - .connect("mysql://root:onny0620@localhost/blog") - .await - .expect("failed to connect database."); let article: Article = sqlx::query_as("SELECT id, title, categoryId, summary, path, deleted, createOn, createBy, modifyOn, modifyBy FROM article WHERE ID=?") .bind(id) @@ -122,10 +115,6 @@ async fn article_detail(State(pool): State, Path(id): Path) -> A } pub async fn extract_article(State(pool): State) { - let pool = MySqlPoolOptions::new() - .connect("mysql://root:onny0620@localhost/blog") - .await - .expect("failed to connect database."); let _ = Extractor::visit_dirs( std::path::Path::new("E:\\rust\\markdown"), -- Gitee From 745db926f3acdf4a9d516728d2ccc05ae0e985ce Mon Sep 17 00:00:00 2001 From: "owen.chao" Date: Fri, 12 Jul 2024 19:17:39 +0800 Subject: [PATCH 083/115] reconstruction file extractor --- src/job/file_extractor.rs | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/src/job/file_extractor.rs b/src/job/file_extractor.rs index 171a1fd..dbc29d3 100644 --- a/src/job/file_extractor.rs +++ b/src/job/file_extractor.rs @@ -47,7 +47,16 @@ impl Extractor<'_> { println!("The file extension is: {:?}", &file_suffix); if file_suffix.to_lowercase() == "md" { println!("-----------md file----------"); - let file = File::open(&path)?; + let article = Extractor::read_markdown(&path)?; + } + } else { + println!("Can not find markdown file."); + } + Ok(()) + } + + pub fn read_markdown(path :&PathBuf) -> Result { + let file = File::open(&path)?; let buffer = BufReader::new(file); let mut summary = String::new(); for line in buffer.lines() { @@ -87,11 +96,6 @@ impl Extractor<'_> { println!("insert a article summary!"); //remove markdown file let _ = fs::remove_file(path); - } - } else { - println!("Can not find markdown file."); - } - Ok(()) } } -- Gitee From 505429d79ebcdb85734aa1ab2f7e1aef8d1f7262 Mon Sep 17 00:00:00 2001 From: "owen.chao" Date: Fri, 12 Jul 2024 19:34:40 +0800 Subject: [PATCH 084/115] reconstruction file extractor --- src/job/file_extractor.rs | 85 ++++++++++++++++++++------------------- 1 file changed, 44 insertions(+), 41 deletions(-) diff --git a/src/job/file_extractor.rs b/src/job/file_extractor.rs index dbc29d3..fe22967 100644 --- a/src/job/file_extractor.rs +++ b/src/job/file_extractor.rs @@ -4,11 +4,13 @@ use std::fs::File; use std::io; use std::io::{BufRead, BufReader, Error, ErrorKind}; use std::path::Path; +use std::path::PathBuf; use sqlx::MySql; use sqlx::Pool; use crate::entity::article_summary::ArticleSummary; +use crate::entity::article::Article; pub struct Extractor<'a> { path: &'a Path, @@ -47,7 +49,7 @@ impl Extractor<'_> { println!("The file extension is: {:?}", &file_suffix); if file_suffix.to_lowercase() == "md" { println!("-----------md file----------"); - let article = Extractor::read_markdown(&path)?; + Extractor::read_markdown(&path, pool).await?; } } else { println!("Can not find markdown file."); @@ -55,47 +57,48 @@ impl Extractor<'_> { Ok(()) } - pub fn read_markdown(path :&PathBuf) -> Result { + pub async fn read_markdown(path :&PathBuf, pool: &Pool) -> Result{ let file = File::open(&path)?; - let buffer = BufReader::new(file); - let mut summary = String::new(); - for line in buffer.lines() { - let line = line?; - if line.trim().is_empty() { - println!("The summary has been read."); - break; - } - if !summary.is_empty() { - summary.push('\n'); - } - summary.push_str(&line); - } - let article_summary = ArticleSummary::new( - path.file_name() - .ok_or_else(|| Error::new(ErrorKind::InvalidInput, "Invalid file name"))? - .to_str() - .ok_or_else(|| { - Error::new(ErrorKind::InvalidData, "File name is not valid UTF-8") - })?, - summary.as_str(), - ); - println!("{:?}", article_summary); - let _ = sqlx::query( - r#"INSERT INTO article (title, summary, path, createBy, createOn, modifyBy, modifyOn) VALUES ('UT', '鸿蒙系统', 'E:\\test.md', 'Owwww', now(), 'YYYY',now() )"# - ).execute(pool).await.expect("insert article failed"); - //insert into database - /* - sqlx::query!( - r#"INSERT INTO articles (title, summary) VALUES (?, ?)"#, - article_summary.title, - article_summary.summary - ) - .execute(pool) - .await?; - */ - println!("insert a article summary!"); - //remove markdown file - let _ = fs::remove_file(path); + let buffer = BufReader::new(file); + let mut summary = String::new(); + for line in buffer.lines() { + let line = line?; + if line.trim().is_empty() { + println!("The summary has been read."); + break; + } + if !summary.is_empty() { + summary.push('\n'); + } + summary.push_str(&line); + } + let article_summary = ArticleSummary::new( + path.file_name() + .ok_or_else(|| Error::new(ErrorKind::InvalidInput, "Invalid file name"))? + .to_str() + .ok_or_else(|| { + Error::new(ErrorKind::InvalidData, "File name is not valid UTF-8") + })?, + summary.as_str(), + ); + println!("{:?}", &article_summary); + let _ = sqlx::query( + r#"INSERT INTO article (title, summary, path, createBy, createOn, modifyBy, modifyOn) VALUES ('UT', '鸿蒙系统', 'E:\\test.md', 'Owwww', now(), 'YYYY',now() )"# + ).execute(pool).await.expect("insert article failed"); + //insert into database + /* + sqlx::query!( + r#"INSERT INTO articles (title, summary) VALUES (?, ?)"#, + article_summary.title, + article_summary.summary + ) + .execute(pool) + .await?; + */ + println!("insert a article summary!"); + //remove markdown file + let _ = fs::remove_file(path); + Ok(article_summary) } } -- Gitee From ebf8fc617a37150bd9adbb2ef6f71edd5102b6a6 Mon Sep 17 00:00:00 2001 From: owen Date: Fri, 12 Jul 2024 23:23:09 +0800 Subject: [PATCH 085/115] some modify --- src/job/file_extractor.rs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/job/file_extractor.rs b/src/job/file_extractor.rs index fe22967..0dba248 100644 --- a/src/job/file_extractor.rs +++ b/src/job/file_extractor.rs @@ -9,8 +9,8 @@ use std::path::PathBuf; use sqlx::MySql; use sqlx::Pool; -use crate::entity::article_summary::ArticleSummary; use crate::entity::article::Article; +use crate::entity::article_summary::ArticleSummary; pub struct Extractor<'a> { path: &'a Path, @@ -57,7 +57,10 @@ impl Extractor<'_> { Ok(()) } - pub async fn read_markdown(path :&PathBuf, pool: &Pool) -> Result{ + pub async fn read_markdown( + path: &PathBuf, + pool: &Pool, + ) -> Result { let file = File::open(&path)?; let buffer = BufReader::new(file); let mut summary = String::new(); -- Gitee From 38432626bb3898c2f28d163dfbdbe8c320f313ef Mon Sep 17 00:00:00 2001 From: owen Date: Sat, 13 Jul 2024 08:28:15 +0800 Subject: [PATCH 086/115] read summary from md --- src/job/file_extractor.rs | 36 ++++++++++++++++++++++++------------ 1 file changed, 24 insertions(+), 12 deletions(-) diff --git a/src/job/file_extractor.rs b/src/job/file_extractor.rs index 0dba248..2c7b29c 100644 --- a/src/job/file_extractor.rs +++ b/src/job/file_extractor.rs @@ -1,7 +1,6 @@ use std::fs; use std::fs::DirEntry; use std::fs::File; -use std::io; use std::io::{BufRead, BufReader, Error, ErrorKind}; use std::path::Path; use std::path::PathBuf; @@ -9,7 +8,6 @@ use std::path::PathBuf; use sqlx::MySql; use sqlx::Pool; -use crate::entity::article::Article; use crate::entity::article_summary::ArticleSummary; pub struct Extractor<'a> { @@ -61,19 +59,31 @@ impl Extractor<'_> { path: &PathBuf, pool: &Pool, ) -> Result { - let file = File::open(&path)?; - let buffer = BufReader::new(file); + let file = File::open(&path).map_err(|error| { + if error.kind() == ErrorKind::NotFound { + Error::new( + ErrorKind::NotFound, + format!("The file path doesn't exist: {:?}", path), + ) + } else { + error + } + }); + let buffer = BufReader::new(file?); let mut summary = String::new(); + let mut is_summary = false; for line in buffer.lines() { let line = line?; - if line.trim().is_empty() { - println!("The summary has been read."); - break; - } - if !summary.is_empty() { - summary.push('\n'); + //读取Summary内容,Summary内容是以Summary为标题(一级,二级,三级标题都可以),直到遇到下一个标题结束。 + if !is_summary && line.trim().contains("=") && line.contains("Summary") { + is_summary = true; + continue; + } else if is_summary && line.trim().contains("=") { + break; //结束读取 + } else if is_summary { + //summary 内容 + summary.push_str(&line.as_str()); } - summary.push_str(&line); } let article_summary = ArticleSummary::new( path.file_name() @@ -86,7 +96,9 @@ impl Extractor<'_> { ); println!("{:?}", &article_summary); let _ = sqlx::query( - r#"INSERT INTO article (title, summary, path, createBy, createOn, modifyBy, modifyOn) VALUES ('UT', '鸿蒙系统', 'E:\\test.md', 'Owwww', now(), 'YYYY',now() )"# + r#"INSERT INTO article (title, summary, path, createBy, createOn, modifyBy, modifyOn) VALUES (?, ?, 'E:\\test.md', 'Admin', now(), 'YYYY',now() )"#, + article_summary.title, + article_summary.summary ).execute(pool).await.expect("insert article failed"); //insert into database /* -- Gitee From 774f7d92a48b76393454ef7b25aa8c207536d337 Mon Sep 17 00:00:00 2001 From: owen Date: Sat, 13 Jul 2024 08:28:39 +0800 Subject: [PATCH 087/115] read summary from md --- src/job/file_extractor.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/job/file_extractor.rs b/src/job/file_extractor.rs index 2c7b29c..3d321c1 100644 --- a/src/job/file_extractor.rs +++ b/src/job/file_extractor.rs @@ -95,7 +95,7 @@ impl Extractor<'_> { summary.as_str(), ); println!("{:?}", &article_summary); - let _ = sqlx::query( + let _ = sqlx::query_withgit( r#"INSERT INTO article (title, summary, path, createBy, createOn, modifyBy, modifyOn) VALUES (?, ?, 'E:\\test.md', 'Admin', now(), 'YYYY',now() )"#, article_summary.title, article_summary.summary -- Gitee From e3cd6a99b58dd5e6773a8760a82094c1697f3dbf Mon Sep 17 00:00:00 2001 From: owen Date: Sat, 13 Jul 2024 08:31:09 +0800 Subject: [PATCH 088/115] remove error string --- src/job/file_extractor.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/job/file_extractor.rs b/src/job/file_extractor.rs index 3d321c1..6dbfeb9 100644 --- a/src/job/file_extractor.rs +++ b/src/job/file_extractor.rs @@ -95,7 +95,7 @@ impl Extractor<'_> { summary.as_str(), ); println!("{:?}", &article_summary); - let _ = sqlx::query_withgit( + let _ = sqlx::query_with( r#"INSERT INTO article (title, summary, path, createBy, createOn, modifyBy, modifyOn) VALUES (?, ?, 'E:\\test.md', 'Admin', now(), 'YYYY',now() )"#, article_summary.title, article_summary.summary -- Gitee From e2116679a05e4b01cc9f58c2027aa71f43901db1 Mon Sep 17 00:00:00 2001 From: owen Date: Sat, 13 Jul 2024 09:00:34 +0800 Subject: [PATCH 089/115] insert article --- src/job/file_extractor.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/job/file_extractor.rs b/src/job/file_extractor.rs index 6dbfeb9..926dd6e 100644 --- a/src/job/file_extractor.rs +++ b/src/job/file_extractor.rs @@ -95,11 +95,11 @@ impl Extractor<'_> { summary.as_str(), ); println!("{:?}", &article_summary); - let _ = sqlx::query_with( + let _ = sqlx::query( r#"INSERT INTO article (title, summary, path, createBy, createOn, modifyBy, modifyOn) VALUES (?, ?, 'E:\\test.md', 'Admin', now(), 'YYYY',now() )"#, - article_summary.title, - article_summary.summary - ).execute(pool).await.expect("insert article failed"); + ) + .bind(&article_summary.title) + .bind(&article_summary.summary).execute(pool).await.expect("insert article failed"); //insert into database /* sqlx::query!( -- Gitee From cb9f7e5692d50802f246182f8f8f8e2c247c5108 Mon Sep 17 00:00:00 2001 From: "owen.chao" Date: Sat, 13 Jul 2024 09:17:31 +0800 Subject: [PATCH 090/115] replace = with # to get the summary --- src/job/file_extractor.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/job/file_extractor.rs b/src/job/file_extractor.rs index 926dd6e..23ab244 100644 --- a/src/job/file_extractor.rs +++ b/src/job/file_extractor.rs @@ -75,10 +75,10 @@ impl Extractor<'_> { for line in buffer.lines() { let line = line?; //读取Summary内容,Summary内容是以Summary为标题(一级,二级,三级标题都可以),直到遇到下一个标题结束。 - if !is_summary && line.trim().contains("=") && line.contains("Summary") { + if !is_summary && line.trim().contains("#") && line.contains("Summary") { is_summary = true; continue; - } else if is_summary && line.trim().contains("=") { + } else if is_summary && line.trim().contains("#") { break; //结束读取 } else if is_summary { //summary 内容 -- Gitee From 2fc9aef388493c22375956226ac28f2eede45002 Mon Sep 17 00:00:00 2001 From: "owen.chao" Date: Sat, 13 Jul 2024 20:04:05 +0800 Subject: [PATCH 091/115] basic path --- src/entity/article_summary.rs | 6 ++++-- src/job/file_extractor.rs | 23 ++++++++++++++--------- src/main.rs | 21 +++++++++++++++------ 3 files changed, 33 insertions(+), 17 deletions(-) diff --git a/src/entity/article_summary.rs b/src/entity/article_summary.rs index 29f3502..35c1d07 100644 --- a/src/entity/article_summary.rs +++ b/src/entity/article_summary.rs @@ -6,17 +6,19 @@ pub struct ArticleSummary { pub title: String, pub categoryId: Option, pub summary: String, + pub path: String, pub createOn: NaiveDateTime, pub createBy: String, } impl ArticleSummary { - pub fn new(title: &str, summary: &str) -> Self { + pub fn new(title: &str, summary: &str, path: &str) -> Self { ArticleSummary { id: 0, title: title.to_string(), categoryId: Some(0), summary: summary.to_string(), + path: path.to_string(), createOn: Utc::now().naive_utc(), createBy: "Admin".to_string(), } @@ -29,7 +31,7 @@ mod test { #[test] fn test_new() { - let article_sumary = ArticleSummary::new("test_title", "test_summary"); + let article_sumary = ArticleSummary::new("test_title", "test_summary" ,""); assert_eq!(article_sumary.title, "test_title"); } } diff --git a/src/job/file_extractor.rs b/src/job/file_extractor.rs index 23ab244..c3ce0cd 100644 --- a/src/job/file_extractor.rs +++ b/src/job/file_extractor.rs @@ -47,15 +47,20 @@ impl Extractor<'_> { println!("The file extension is: {:?}", &file_suffix); if file_suffix.to_lowercase() == "md" { println!("-----------md file----------"); - Extractor::read_markdown(&path, pool).await?; + let article_summary = Extractor::extract_aritcle_from_markdown(&path, pool).await?; + let _ = sqlx::query( + r#"INSERT INTO article (title, summary, path, createBy, createOn, modifyBy, modifyOn) VALUES (?, ?, 'E:\\test.md','Admin', now(), 'YYYY',now() )"#, + ) + .bind(&article_summary.title) + .bind(&article_summary.summary).execute(pool).await.expect("insert article failed"); } } else { - println!("Can not find markdown file."); + eprintln!("Can not find markdown file."); } Ok(()) } - pub async fn read_markdown( + pub async fn extract_aritcle_from_markdown( path: &PathBuf, pool: &Pool, ) -> Result { @@ -85,6 +90,7 @@ impl Extractor<'_> { summary.push_str(&line.as_str()); } } + let archives_path = path.display().to_string(); let article_summary = ArticleSummary::new( path.file_name() .ok_or_else(|| Error::new(ErrorKind::InvalidInput, "Invalid file name"))? @@ -93,13 +99,10 @@ impl Extractor<'_> { Error::new(ErrorKind::InvalidData, "File name is not valid UTF-8") })?, summary.as_str(), + &archives_path, ); println!("{:?}", &article_summary); - let _ = sqlx::query( - r#"INSERT INTO article (title, summary, path, createBy, createOn, modifyBy, modifyOn) VALUES (?, ?, 'E:\\test.md', 'Admin', now(), 'YYYY',now() )"#, - ) - .bind(&article_summary.title) - .bind(&article_summary.summary).execute(pool).await.expect("insert article failed"); + //insert into database /* sqlx::query!( @@ -111,7 +114,9 @@ impl Extractor<'_> { .await?; */ println!("insert a article summary!"); - //remove markdown file + //move these files to Archives directory + + fs::rename(path, &archives_path); let _ = fs::remove_file(path); Ok(article_summary) } diff --git a/src/main.rs b/src/main.rs index 82484be..f4105c6 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,10 +1,11 @@ +use std::env; +use std::io::Error; + use axum::extract; use axum::{extract::Path, routing::get, Router, extract::State}; use sqlx::mysql::MySqlPoolOptions; use sqlx::MySqlPool; -use std::io::Error; - pub mod entity; pub mod job; pub mod person; @@ -23,6 +24,13 @@ async fn main() { let workspace = std::env::current_dir().unwrap(); println!("{:?}", workspace); + let args = std::env::args().collect(); + if (args).capacity()<2 { + //第一个参数是程序名称,第二个参数才是我们输入的参数 + epritln!("You need to entry the basic_path"); + panic!("Lost the param basic_path"); + } + let basic_path = args[1]; let pool = MySqlPoolOptions::new() .connect("mysql://root:onny0620@localhost/blog") @@ -36,7 +44,8 @@ async fn main() { .route("/me", get(me)) .route("/article/new", get(extract_article)) .nest_service("/assets", tower_http::services::ServeDir::new("assets")) - .with_state(pool); + .with_state(pool) + .with_state(basic_path); // run our app with hyper, listening globally on port 3000 let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap(); @@ -114,11 +123,11 @@ async fn article_detail(State(pool): State, Path(id): Path) -> A article_detail.setContent(content) } -pub async fn extract_article(State(pool): State) { +pub async fn extract_article(State(pool): State, State(basic_path): State<&str>) { let _ = Extractor::visit_dirs( - std::path::Path::new("E:\\rust\\markdown"), - &pool, + std::path::Path::new(&basic_path), + &pool ) .await.expect_err("failed insert article......"); -- Gitee From 47bed63c0e59df597b90b25f8711e97b66489db3 Mon Sep 17 00:00:00 2001 From: owen Date: Sun, 14 Jul 2024 18:24:19 +0800 Subject: [PATCH 092/115] modify the file location --- src/configuration/configuration.rs | 28 ++++++++++++++++ src/configuration/mod.rs | 1 + src/entity/mod.rs | 4 +-- src/job/file_extractor.rs | 23 ++++++-------- src/main.rs | 51 ++++++++++++++---------------- 5 files changed, 64 insertions(+), 43 deletions(-) create mode 100644 src/configuration/configuration.rs create mode 100644 src/configuration/mod.rs diff --git a/src/configuration/configuration.rs b/src/configuration/configuration.rs new file mode 100644 index 0000000..f145d47 --- /dev/null +++ b/src/configuration/configuration.rs @@ -0,0 +1,28 @@ +use sqlx::MySqlPool; + +use std::fs::File; +use std::io::{BufRead, BufReader, Error}; + +#[derive(Clone, Debug)] +struct Configuration { + basic_path: String, + pool: MySqlPool, +} + +impl Configuration { + pub fn new() {} + + //从当前目录读取配置文件 + pub fn read_from_configuration_file(&self) -> Self { + let configuration_path = std::env::current_dir()?.join("configuration"); + println!("configuration path: {}", &configuration_path); + let file = File::open(&configuration_path).map_err(|error| { + println!("Read configuration file failed {:?}", error); + panic!("Error occored when read configuration: {:?}", error); + }); + let buffer = BufReader::new(file?); + for line in buffer.lines() { + let line = line?; + } + } +} diff --git a/src/configuration/mod.rs b/src/configuration/mod.rs new file mode 100644 index 0000000..2d148af --- /dev/null +++ b/src/configuration/mod.rs @@ -0,0 +1 @@ +pub mod configuration; diff --git a/src/entity/mod.rs b/src/entity/mod.rs index 67aa4b0..7c0bf7d 100644 --- a/src/entity/mod.rs +++ b/src/entity/mod.rs @@ -1,4 +1,4 @@ -pub mod article; +pub mod article; +pub mod article_detail; pub mod article_summary; pub mod article_summary_vec; -pub mod article_detail; diff --git a/src/job/file_extractor.rs b/src/job/file_extractor.rs index c3ce0cd..15bc1b9 100644 --- a/src/job/file_extractor.rs +++ b/src/job/file_extractor.rs @@ -11,7 +11,7 @@ use sqlx::Pool; use crate::entity::article_summary::ArticleSummary; pub struct Extractor<'a> { - path: &'a Path, + _path: &'a Path, } impl Extractor<'_> { @@ -47,7 +47,7 @@ impl Extractor<'_> { println!("The file extension is: {:?}", &file_suffix); if file_suffix.to_lowercase() == "md" { println!("-----------md file----------"); - let article_summary = Extractor::extract_aritcle_from_markdown(&path, pool).await?; + let article_summary = Extractor::extract_aritcle_from_markdown(&path).await?; let _ = sqlx::query( r#"INSERT INTO article (title, summary, path, createBy, createOn, modifyBy, modifyOn) VALUES (?, ?, 'E:\\test.md','Admin', now(), 'YYYY',now() )"#, ) @@ -55,15 +55,12 @@ impl Extractor<'_> { .bind(&article_summary.summary).execute(pool).await.expect("insert article failed"); } } else { - eprintln!("Can not find markdown file."); + println!("Can not find markdown file."); } Ok(()) } - pub async fn extract_aritcle_from_markdown( - path: &PathBuf, - pool: &Pool, - ) -> Result { + pub async fn extract_aritcle_from_markdown(path: &PathBuf) -> Result { let file = File::open(&path).map_err(|error| { if error.kind() == ErrorKind::NotFound { Error::new( @@ -90,7 +87,7 @@ impl Extractor<'_> { summary.push_str(&line.as_str()); } } - let archives_path = path.display().to_string(); + let archives_path = std::env::current_dir().unwrap().join("archives"); let article_summary = ArticleSummary::new( path.file_name() .ok_or_else(|| Error::new(ErrorKind::InvalidInput, "Invalid file name"))? @@ -99,10 +96,10 @@ impl Extractor<'_> { Error::new(ErrorKind::InvalidData, "File name is not valid UTF-8") })?, summary.as_str(), - &archives_path, + &archives_path.to_str().unwrap(), ); println!("{:?}", &article_summary); - + //insert into database /* sqlx::query!( @@ -114,9 +111,9 @@ impl Extractor<'_> { .await?; */ println!("insert a article summary!"); - //move these files to Archives directory - - fs::rename(path, &archives_path); + //move these files to Archives directory + + let _ = fs::rename(path, &archives_path); let _ = fs::remove_file(path); Ok(article_summary) } diff --git a/src/main.rs b/src/main.rs index f4105c6..8de0f33 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,11 +1,9 @@ -use std::env; -use std::io::Error; - -use axum::extract; -use axum::{extract::Path, routing::get, Router, extract::State}; +use axum::{extract::Path, extract::State, routing::get, Router}; use sqlx::mysql::MySqlPoolOptions; use sqlx::MySqlPool; +use std::sync::Arc; + pub mod entity; pub mod job; pub mod person; @@ -20,17 +18,15 @@ use crate::job::file_extractor::Extractor; #[tokio::main] async fn main() { - // build our application with a single route - let workspace = std::env::current_dir().unwrap(); println!("{:?}", workspace); - let args = std::env::args().collect(); - if (args).capacity()<2 { - //第一个参数是程序名称,第二个参数才是我们输入的参数 - epritln!("You need to entry the basic_path"); - panic!("Lost the param basic_path"); - } - let basic_path = args[1]; + let args: Vec = std::env::args().collect(); + if (args).capacity() < 2 { + //第一个参数是程序名称,第二个参数才是我们输入的参数 + eprintln!("You need to entry the basic_path"); + panic!("Lost the param basic_path"); + } + let basic_path = Arc::new(args[1].clone()); let pool = MySqlPoolOptions::new() .connect("mysql://root:onny0620@localhost/blog") @@ -43,9 +39,9 @@ async fn main() { .route("/article/:id", get(article_detail)) .route("/me", get(me)) .route("/article/new", get(extract_article)) - .nest_service("/assets", tower_http::services::ServeDir::new("assets")) - .with_state(pool) - .with_state(basic_path); + .with_state(pool) + .with_state(basic_path) + .nest_service("/assets", tower_http::services::ServeDir::new("assets")); // run our app with hyper, listening globally on port 3000 let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap(); @@ -54,7 +50,6 @@ async fn main() { #[warn(dead_code)] async fn say_hello(State(pool): State) -> String { - let row: (String,) = sqlx::query_as("SELECT 'hello world, Rust!'") .fetch_one(&pool) .await @@ -63,12 +58,15 @@ async fn say_hello(State(pool): State) -> String { row.0 } -async fn article_list(State(pool): State, Path(page_num): Path) -> ArticleSummaryVec { +async fn article_list( + State(pool): State, + Path(page_num): Path, +) -> ArticleSummaryVec { println!("page_num: {}", page_num); let page_size: i32 = 9; let offset = (page_num - 1) * page_size; println!("the offset is {}", &offset); - + let summary_vec: Vec= sqlx::query_as("SELECT id, title, categoryId, summary, createOn, createBy FROM article WHERE deleted=0 order by id desc limit ?, ? ") .bind(offset) .bind(page_size) @@ -123,14 +121,11 @@ async fn article_detail(State(pool): State, Path(id): Path) -> A article_detail.setContent(content) } -pub async fn extract_article(State(pool): State, State(basic_path): State<&str>) { - - let _ = Extractor::visit_dirs( - std::path::Path::new(&basic_path), - &pool - ) - .await.expect_err("failed insert article......"); - +pub async fn extract_article(State(pool): State) { + let current_workspace = std::env::current_dir().unwrap().join("markdown"); + let _ = Extractor::visit_dirs(std::path::Path::new(current_workspace.as_os_str()), &pool) + .await + .expect_err("failed insert article......"); } async fn me() -> Person<'static> { -- Gitee From 3c411c9042a95696bbde143c3c3967b092d9086f Mon Sep 17 00:00:00 2001 From: owen Date: Sun, 14 Jul 2024 21:24:54 +0800 Subject: [PATCH 093/115] remove input arguments --- src/main.rs | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/src/main.rs b/src/main.rs index 8de0f33..d016905 100644 --- a/src/main.rs +++ b/src/main.rs @@ -20,14 +20,15 @@ use crate::job::file_extractor::Extractor; async fn main() { let workspace = std::env::current_dir().unwrap(); println!("{:?}", workspace); - let args: Vec = std::env::args().collect(); - if (args).capacity() < 2 { - //第一个参数是程序名称,第二个参数才是我们输入的参数 - eprintln!("You need to entry the basic_path"); - panic!("Lost the param basic_path"); - } - let basic_path = Arc::new(args[1].clone()); - + /* + let args: Vec = std::env::args().collect(); + if (args).capacity() < 2 { + //第一个参数是程序名称,第二个参数才是我们输入的参数 + eprintln!("You need to entry the basic_path"); + panic!("Lost the param basic_path"); + } + let basic_path = Arc::new(args[1].clone()); + */ let pool = MySqlPoolOptions::new() .connect("mysql://root:onny0620@localhost/blog") .await @@ -40,7 +41,7 @@ async fn main() { .route("/me", get(me)) .route("/article/new", get(extract_article)) .with_state(pool) - .with_state(basic_path) + //.with_state(basic_path) .nest_service("/assets", tower_http::services::ServeDir::new("assets")); // run our app with hyper, listening globally on port 3000 -- Gitee From dca965e18a3dfa5b6e4232eb9cf52a3341ff7a71 Mon Sep 17 00:00:00 2001 From: owen Date: Sun, 14 Jul 2024 21:33:08 +0800 Subject: [PATCH 094/115] article_summary add path field --- src/main.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main.rs b/src/main.rs index d016905..fae7f99 100644 --- a/src/main.rs +++ b/src/main.rs @@ -68,7 +68,7 @@ async fn article_list( let offset = (page_num - 1) * page_size; println!("the offset is {}", &offset); - let summary_vec: Vec= sqlx::query_as("SELECT id, title, categoryId, summary, createOn, createBy FROM article WHERE deleted=0 order by id desc limit ?, ? ") + let summary_vec: Vec= sqlx::query_as("SELECT id, title, categoryId, summary,path, createOn, createBy FROM article WHERE deleted=0 order by id desc limit ?, ? ") .bind(offset) .bind(page_size) .fetch_all(&pool).await.expect("failed!"); -- Gitee From 2e6ae8304db9ca07ad080424a701dced23418d8b Mon Sep 17 00:00:00 2001 From: owen Date: Sun, 14 Jul 2024 21:49:13 +0800 Subject: [PATCH 095/115] add path to article summary --- src/job/file_extractor.rs | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/src/job/file_extractor.rs b/src/job/file_extractor.rs index 15bc1b9..d7106cf 100644 --- a/src/job/file_extractor.rs +++ b/src/job/file_extractor.rs @@ -49,9 +49,10 @@ impl Extractor<'_> { println!("-----------md file----------"); let article_summary = Extractor::extract_aritcle_from_markdown(&path).await?; let _ = sqlx::query( - r#"INSERT INTO article (title, summary, path, createBy, createOn, modifyBy, modifyOn) VALUES (?, ?, 'E:\\test.md','Admin', now(), 'YYYY',now() )"#, + r#"INSERT INTO article (title, summary, path, createBy, createOn, modifyBy, modifyOn) VALUES (?, ?, ?,'Admin', now(), 'Admin',now() )"#, ) .bind(&article_summary.title) + .bind() .bind(&article_summary.summary).execute(pool).await.expect("insert article failed"); } } else { @@ -88,15 +89,15 @@ impl Extractor<'_> { } } let archives_path = std::env::current_dir().unwrap().join("archives"); + let file_name = path + .file_name() + .ok_or_else(|| Error::new(ErrorKind::InvalidInput, "Invalid file name"))? + .to_str() + .ok_or_else(|| Error::new(ErrorKind::InvalidData, "File name is not valid UTF-8"))?; let article_summary = ArticleSummary::new( - path.file_name() - .ok_or_else(|| Error::new(ErrorKind::InvalidInput, "Invalid file name"))? - .to_str() - .ok_or_else(|| { - Error::new(ErrorKind::InvalidData, "File name is not valid UTF-8") - })?, + file_name, summary.as_str(), - &archives_path.to_str().unwrap(), + format!("{}{}", &archives_path.to_str().unwrap(), file_name).as_str(), ); println!("{:?}", &article_summary); -- Gitee From 14464a6018b44fedee8c347dd5dd5dc99ea35006 Mon Sep 17 00:00:00 2001 From: owen Date: Sun, 14 Jul 2024 21:51:14 +0800 Subject: [PATCH 096/115] bind path to article summary --- src/job/file_extractor.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/job/file_extractor.rs b/src/job/file_extractor.rs index d7106cf..22f8fa2 100644 --- a/src/job/file_extractor.rs +++ b/src/job/file_extractor.rs @@ -52,7 +52,7 @@ impl Extractor<'_> { r#"INSERT INTO article (title, summary, path, createBy, createOn, modifyBy, modifyOn) VALUES (?, ?, ?,'Admin', now(), 'Admin',now() )"#, ) .bind(&article_summary.title) - .bind() + .bind(&article_summary.path) .bind(&article_summary.summary).execute(pool).await.expect("insert article failed"); } } else { -- Gitee From d461d8005e04894614050c51dcca150e5b7cdfe8 Mon Sep 17 00:00:00 2001 From: owen Date: Sun, 14 Jul 2024 22:19:58 +0800 Subject: [PATCH 097/115] file name modify --- src/job/file_extractor.rs | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/src/job/file_extractor.rs b/src/job/file_extractor.rs index 22f8fa2..32e9eff 100644 --- a/src/job/file_extractor.rs +++ b/src/job/file_extractor.rs @@ -89,15 +89,23 @@ impl Extractor<'_> { } } let archives_path = std::env::current_dir().unwrap().join("archives"); - let file_name = path + let file_name_with_suffix = path .file_name() .ok_or_else(|| Error::new(ErrorKind::InvalidInput, "Invalid file name"))? .to_str() .ok_or_else(|| Error::new(ErrorKind::InvalidData, "File name is not valid UTF-8"))?; + let file_name_vec: Vec<&str> = file_name_with_suffix.split(".").collect(); + let file_name = file_name_vec[0]; let article_summary = ArticleSummary::new( file_name, summary.as_str(), - format!("{}{}", &archives_path.to_str().unwrap(), file_name).as_str(), + format!( + "{}{}{}", + &archives_path.to_str().unwrap(), + "/", + file_name_with_suffix + ) + .as_str(), ); println!("{:?}", &article_summary); -- Gitee From 83e19d1f78c274f367f722d3e3f1c17b01410c4f Mon Sep 17 00:00:00 2001 From: "owen.chao" Date: Sun, 14 Jul 2024 22:35:45 +0800 Subject: [PATCH 098/115] bf --- src/job/file_extractor.rs | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/job/file_extractor.rs b/src/job/file_extractor.rs index 32e9eff..0144a7a 100644 --- a/src/job/file_extractor.rs +++ b/src/job/file_extractor.rs @@ -52,8 +52,10 @@ impl Extractor<'_> { r#"INSERT INTO article (title, summary, path, createBy, createOn, modifyBy, modifyOn) VALUES (?, ?, ?,'Admin', now(), 'Admin',now() )"#, ) .bind(&article_summary.title) - .bind(&article_summary.path) - .bind(&article_summary.summary).execute(pool).await.expect("insert article failed"); + .bind(&article_summary.summary) + .bind(&article_summary.path) + .execute(pool).await + .expect("insert article failed"); } } else { println!("Can not find markdown file."); @@ -102,7 +104,7 @@ impl Extractor<'_> { format!( "{}{}{}", &archives_path.to_str().unwrap(), - "/", + "\\", file_name_with_suffix ) .as_str(), -- Gitee From 0af644d1851bab6a05dda14a436102ddff5e158c Mon Sep 17 00:00:00 2001 From: owen Date: Sun, 14 Jul 2024 22:42:42 +0800 Subject: [PATCH 099/115] rename file --- src/job/file_extractor.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/job/file_extractor.rs b/src/job/file_extractor.rs index 0144a7a..b7b2130 100644 --- a/src/job/file_extractor.rs +++ b/src/job/file_extractor.rs @@ -124,7 +124,7 @@ impl Extractor<'_> { println!("insert a article summary!"); //move these files to Archives directory - let _ = fs::rename(path, &archives_path); + let _ = fs::rename(path, &article_summary.path); let _ = fs::remove_file(path); Ok(article_summary) } -- Gitee From 7de46e925f44bce89549a779496d906d3b63a559 Mon Sep 17 00:00:00 2001 From: owen Date: Sun, 14 Jul 2024 22:56:44 +0800 Subject: [PATCH 100/115] remove some unuseful code --- src/main.rs | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/main.rs b/src/main.rs index fae7f99..8a4ab70 100644 --- a/src/main.rs +++ b/src/main.rs @@ -2,8 +2,6 @@ use axum::{extract::Path, extract::State, routing::get, Router}; use sqlx::mysql::MySqlPoolOptions; use sqlx::MySqlPool; -use std::sync::Arc; - pub mod entity; pub mod job; pub mod person; @@ -41,7 +39,6 @@ async fn main() { .route("/me", get(me)) .route("/article/new", get(extract_article)) .with_state(pool) - //.with_state(basic_path) .nest_service("/assets", tower_http::services::ServeDir::new("assets")); // run our app with hyper, listening globally on port 3000 -- Gitee From c8c6d54e76865c2586c2b4cf5dac2907823ff89a Mon Sep 17 00:00:00 2001 From: "owen.chao" Date: Tue, 16 Jul 2024 12:52:31 +0800 Subject: [PATCH 101/115] add insert article alert message --- src/main.rs | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/src/main.rs b/src/main.rs index 8a4ab70..c69e34f 100644 --- a/src/main.rs +++ b/src/main.rs @@ -119,11 +119,15 @@ async fn article_detail(State(pool): State, Path(id): Path) -> A article_detail.setContent(content) } -pub async fn extract_article(State(pool): State) { +pub async fn extract_article(State(pool): State) ->String { let current_workspace = std::env::current_dir().unwrap().join("markdown"); - let _ = Extractor::visit_dirs(std::path::Path::new(current_workspace.as_os_str()), &pool) - .await - .expect_err("failed insert article......"); + let insert_article_result = Extractor::visit_dirs(std::path::Path::new(current_workspace.as_os_str()), &pool) + .await; + match insert_article_result { + Ok(r) => "Insert Article successfully.".to_string(), + Err(err) => "Insert Article failed!".to_string() + } + } async fn me() -> Person<'static> { -- Gitee From 86511a022130062da199d8168edccc0272780230 Mon Sep 17 00:00:00 2001 From: "owen.chao" Date: Fri, 19 Jul 2024 19:08:35 +0800 Subject: [PATCH 102/115] change web background color --- resource/{step. md => step.md} | 28 ++++++++++++++-------------- templates/html/blog.html | 2 ++ templates/html/blog_list.html | 31 +++++++++++++++++-------------- 3 files changed, 33 insertions(+), 28 deletions(-) rename resource/{step. md => step.md} (97%) diff --git a/resource/step. md b/resource/step.md similarity index 97% rename from resource/step. md rename to resource/step.md index 06fae4e..bc48664 100644 --- a/resource/step. md +++ b/resource/step.md @@ -1,15 +1,15 @@ -### MySql server 设置 -阿里云服务器安装mysql服务后,防火墙开启端口 -阿里云网络安全组设置端口进出规则 -不要用root用户直接登录,新建用户,并赋予权限。 - -``` --- 创建用户并设置密码 -CREATE USER 'newuser'@'%' IDENTIFIED BY 'securepassword'; - --- 授予新用户对特定数据库的所有权限 -GRANT ALL PRIVILEGES ON mydb.* TO 'newuser'@'%'; - --- 如果需要允许用户从任何地方连接,并执行FLUSH PRIVILEGES来立即生效 -FLUSH PRIVILEGES; +### MySql server 设置 +阿里云服务器安装mysql服务后,防火墙开启端口 +阿里云网络安全组设置端口进出规则 +不要用root用户直接登录,新建用户,并赋予权限。 + +``` +-- 创建用户并设置密码 +CREATE USER 'newuser'@'%' IDENTIFIED BY 'securepassword'; + +-- 授予新用户对特定数据库的所有权限 +GRANT ALL PRIVILEGES ON mydb.* TO 'newuser'@'%'; + +-- 如果需要允许用户从任何地方连接,并执行FLUSH PRIVILEGES来立即生效 +FLUSH PRIVILEGES; ``` \ No newline at end of file diff --git a/templates/html/blog.html b/templates/html/blog.html index 7ee94b2..6222bd6 100644 --- a/templates/html/blog.html +++ b/templates/html/blog.html @@ -15,6 +15,8 @@ html, body { height: 100%; margin: 0; + background-image: linear-gradient(-225deg, #231557 0%, #44107A 29%, #FF1361 67%, #FFF800 100%); + color: white; } footer { diff --git a/templates/html/blog_list.html b/templates/html/blog_list.html index 961716e..7af6275 100644 --- a/templates/html/blog_list.html +++ b/templates/html/blog_list.html @@ -19,8 +19,12 @@ body { height: 100%; margin: 0; - + background-image: linear-gradient(-225deg, #231557 0%, #44107A 29%, #FF1361 67%, #FFF800 100%); } + + a { + text-decoration: none; + } footer { height: 60px; @@ -34,42 +38,41 @@ - +
    {% for article in vec1 %} -
    {% for article in vec2 %} -
    {% for article in vec3 %} - -- Gitee From 97d858b002438464e5ebb4f6c5faa36c57b427dd Mon Sep 17 00:00:00 2001 From: owen Date: Sat, 20 Jul 2024 08:56:10 +0800 Subject: [PATCH 103/115] new line --- src/job/file_extractor.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/job/file_extractor.rs b/src/job/file_extractor.rs index b7b2130..2a2a6c9 100644 --- a/src/job/file_extractor.rs +++ b/src/job/file_extractor.rs @@ -87,6 +87,7 @@ impl Extractor<'_> { break; //结束读取 } else if is_summary { //summary 内容 + summary.push_str("\n\t"); summary.push_str(&line.as_str()); } } -- Gitee From 5cc69035241219215792a69be028910c4349f9fa Mon Sep 17 00:00:00 2001 From: owen Date: Sat, 20 Jul 2024 09:13:28 +0800 Subject: [PATCH 104/115] summary breaklien --- templates/html/blog.html | 138 ++++++++++++++++++++++----------------- 1 file changed, 78 insertions(+), 60 deletions(-) diff --git a/templates/html/blog.html b/templates/html/blog.html index 6222bd6..ee2679c 100644 --- a/templates/html/blog.html +++ b/templates/html/blog.html @@ -1,64 +1,82 @@ - + - - - - RustAll - - - - - - -
    -
    -
    -

    {{title}}

    -
    -
    -
    -
    -
    -
    -
    - -
    -

    © 2023 你的公司名或个人名. All rights reserved.

    -
    + + + + RustAll + + + + + +
    +
    +
    +

    {{title}}

    +
    +
    +
    +
    +
    +
    +
    + +
    +

    © 2023 你的公司名或个人名. All rights reserved.

    +
    + + + + + -- Gitee From fb0117fb4b767bce18ed418751eb0e0a2bab7ea4 Mon Sep 17 00:00:00 2001 From: owen Date: Sat, 20 Jul 2024 09:16:13 +0800 Subject: [PATCH 105/115] footer location --- templates/html/blog_list.html | 357 +++++++++++++++++++--------------- 1 file changed, 205 insertions(+), 152 deletions(-) diff --git a/templates/html/blog_list.html b/templates/html/blog_list.html index 7af6275..f577c90 100644 --- a/templates/html/blog_list.html +++ b/templates/html/blog_list.html @@ -1,169 +1,222 @@ - + + + + + RustAll + + + - - - -
    -
    -
    -
    - {% for article in vec1 %} -
    - -
    {{article.title|e}}
    -

    {{article.summary|e}}

    - -
    + footer { + height: 60px; + /* 设置footer的高度 */ + text-align: center; + padding: 20px 0; + position: relative; + //margin-top: 40px; + /* 与min-height一起确保footer在内容不足时也能置底 */ + } + + + + +
    +
    +
    +
    + {% for article in vec1 %} + + {% endfor %}
    - {% endfor %} -
    -
    - {% for article in vec2 %} -
    - -
    {{article.title|e}}
    -

    {{article.summary|e}}

    -
    +
    + {% for article in vec2 %} + + {% endfor %}
    - {% endfor %} -
    -
    - {% for article in vec3 %} -
    - -
    {{article.title|e}}
    -

    {{article.summary|e}}

    - -
    +
    + {% for article in vec3 %} + + {% endfor %}
    - {% endfor %}
    -
    -
    - -
    -
    -
    -
    - +
    + +
    +
    +
    +
    + +
    +
    -
    -
    -
    - - - -
    -

    © 2023 你的公司名或个人名. All rights reserved.

    -
    +
    + +
    +

    © 2023 你的公司名或个人名. All rights reserved.

    +
    + + + + + - - - - + window.addEventListener('load', + reloadPages() + ); + + -- Gitee From 38502e7e3a8b88aef97e9204359d402eda2422b2 Mon Sep 17 00:00:00 2001 From: owen Date: Sat, 20 Jul 2024 09:18:26 +0800 Subject: [PATCH 106/115] footer location --- templates/html/blog_list.html | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/templates/html/blog_list.html b/templates/html/blog_list.html index f577c90..8947be4 100644 --- a/templates/html/blog_list.html +++ b/templates/html/blog_list.html @@ -15,7 +15,7 @@ .content-wrap { min-height: calc(100% - 60px); /* 60px是footer的高度,可根据实际情况调整 */ - margin-bottom: 60px; + margin-bottom: -60px; /* 负margin等于footer的高度,避免内容被footer遮挡 */ } @@ -46,7 +46,7 @@ text-align: center; padding: 20px 0; position: relative; - //margin-top: 40px; + margin-top: 60px; /* 与min-height一起确保footer在内容不足时也能置底 */ } -- Gitee From 278f3c777bc23513ee6495432383b10a1705e88e Mon Sep 17 00:00:00 2001 From: owen Date: Thu, 15 Aug 2024 23:25:49 +0800 Subject: [PATCH 107/115] add tklog --- Cargo.toml | 2 +- templates/html/blog_list.html | 4 ---- 2 files changed, 1 insertion(+), 5 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 8b7cf0d..dd0116c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -17,4 +17,4 @@ tower-http = { version = "0.5.2", features = ["fs", "trace"] } sqlx = { version = "0.7.4", features = ["mysql", "runtime-tokio", "macros", "chrono"] } chrono = "0.4.38" cron = "0.12.1" - +tklog = "0.0.10" diff --git a/templates/html/blog_list.html b/templates/html/blog_list.html index 8947be4..fcbb97e 100644 --- a/templates/html/blog_list.html +++ b/templates/html/blog_list.html @@ -32,10 +32,6 @@ ); } - p { - overflow-wrap: break-word; /* 允许长单词换行到下一行 */ - } - a { text-decoration: none; } -- Gitee From 3f4a940a7ab732db2f3f2578802d73dab60f23be Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=A8=8B=E5=BA=8F=E8=99=AB?= Date: Thu, 22 Aug 2024 10:15:48 +0000 Subject: [PATCH 108/115] update README.md. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 程序虫 --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index ca388d2..cb62767 100644 --- a/README.md +++ b/README.md @@ -22,5 +22,5 @@ ### 注意 -- 文件名建议中文,如果是英文的话,如果路径中使用反斜杠那么名字可能被转移,例如\test.md, \t 就被当作换行符。 +- 文件名建议中文,假如是英文的话,如果路径中使用反斜杠那么名字可能被转移,例如\test.md, \t 就被当作换行符。 - 路径名为全路径名称, 要改 -- Gitee From 044bba238402fa92a4e5635d78278e3525e31dea Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=A8=8B=E5=BA=8F=E8=99=AB?= Date: Thu, 22 Aug 2024 11:07:14 +0000 Subject: [PATCH 109/115] update README.md. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 程序虫 --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index cb62767..a917490 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,7 @@ #### 介绍 -使用axum 试着创建一个web app, 通过项目学习Rust, tokio登 +使用axum 试着创建一个web app, 通过项目学习Rust, tokio等 ####使用的crate 后端框架:Axum -- Gitee From 2b3dcdc4661f4f9fb310bb0f05f904c4ce5ba2db Mon Sep 17 00:00:00 2001 From: owen Date: Sat, 31 Aug 2024 10:22:01 +0800 Subject: [PATCH 110/115] html --- templates/html/blog.html | 8 ++--- templates/html/blog_list.html | 55 +++++++++++++++-------------------- 2 files changed, 27 insertions(+), 36 deletions(-) diff --git a/templates/html/blog.html b/templates/html/blog.html index ee2679c..1961d79 100644 --- a/templates/html/blog.html +++ b/templates/html/blog.html @@ -14,23 +14,23 @@ @@ -50,23 +56,18 @@
    -
    +
    {% for article in vec1 %} @@ -76,18 +77,13 @@
    {% for article in vec2 %} @@ -97,18 +93,13 @@
    {% for article in vec3 %} @@ -152,8 +143,8 @@
    -
    +

    © 2023 你的公司名或个人名. All rights reserved.

    -- Gitee From ae3d7c463f2cc04a7e539ab95d066595cf0b2f69 Mon Sep 17 00:00:00 2001 From: owen Date: Tue, 3 Sep 2024 08:06:48 +0800 Subject: [PATCH 111/115] add tklog --- src/entity/article.rs | 2 +- src/job/file_extractor.rs | 10 +++++++++- src/main.rs | 32 +++++++++++++++++++++----------- 3 files changed, 31 insertions(+), 13 deletions(-) diff --git a/src/entity/article.rs b/src/entity/article.rs index 3207a59..537f97c 100644 --- a/src/entity/article.rs +++ b/src/entity/article.rs @@ -39,7 +39,7 @@ impl Article { contents } - pub fn getInfo(self) -> (i32, String, NaiveDateTime) { + pub fn get_info(self) -> (i32, String, NaiveDateTime) { (self.id, self.title, self.createOn) } } diff --git a/src/job/file_extractor.rs b/src/job/file_extractor.rs index 2a2a6c9..8a6c8dd 100644 --- a/src/job/file_extractor.rs +++ b/src/job/file_extractor.rs @@ -8,6 +8,8 @@ use std::path::PathBuf; use sqlx::MySql; use sqlx::Pool; +use tklog::{error, info}; + use crate::entity::article_summary::ArticleSummary; pub struct Extractor<'a> { @@ -18,6 +20,7 @@ impl Extractor<'_> { // one possible implementation of walking a directory only visiting files pub async fn visit_dirs(path: &Path, pool: &Pool) -> Result<(), Error> { println!("-------------visit_dirs start--------------"); + info!("-------------visit_dirs start--------------"); let dir = Path::new(path); if dir.is_dir() { for entry in fs::read_dir(dir)? { @@ -28,8 +31,10 @@ impl Extractor<'_> { let _ = Self::visit_dirs(&path, pool); } else if path.is_file() { println!("-------------extract start--------------"); + info!("-------------extract start--------------"); let _ = Extractor::extract(&entry, pool).await?; } else { + error!("it is not dir or file."); panic!("it is not dir or file."); } } @@ -45,8 +50,9 @@ impl Extractor<'_> { .to_str() .ok_or_else(|| Error::new(ErrorKind::InvalidData, "Invalid file suffix"))?; println!("The file extension is: {:?}", &file_suffix); + info!("The file extension is: ", &file_suffix); if file_suffix.to_lowercase() == "md" { - println!("-----------md file----------"); + info!("-----------md file----------"); let article_summary = Extractor::extract_aritcle_from_markdown(&path).await?; let _ = sqlx::query( r#"INSERT INTO article (title, summary, path, createBy, createOn, modifyBy, modifyOn) VALUES (?, ?, ?,'Admin', now(), 'Admin',now() )"#, @@ -59,6 +65,7 @@ impl Extractor<'_> { } } else { println!("Can not find markdown file."); + error!("Can not find markdown file."); } Ok(()) } @@ -123,6 +130,7 @@ impl Extractor<'_> { .await?; */ println!("insert a article summary!"); + info!("insert a article summary!"); //move these files to Archives directory let _ = fs::rename(path, &article_summary.path); diff --git a/src/main.rs b/src/main.rs index c69e34f..d22155f 100644 --- a/src/main.rs +++ b/src/main.rs @@ -2,6 +2,8 @@ use axum::{extract::Path, extract::State, routing::get, Router}; use sqlx::mysql::MySqlPoolOptions; use sqlx::MySqlPool; +use tklog::info; + pub mod entity; pub mod job; pub mod person; @@ -17,7 +19,8 @@ use crate::job::file_extractor::Extractor; #[tokio::main] async fn main() { let workspace = std::env::current_dir().unwrap(); - println!("{:?}", workspace); + println!("{:?}", &workspace); + info!("Current workspace:: {:?}", &workspace.to_string_lossy()); /* let args: Vec = std::env::args().collect(); if (args).capacity() < 2 { @@ -28,7 +31,7 @@ async fn main() { let basic_path = Arc::new(args[1].clone()); */ let pool = MySqlPoolOptions::new() - .connect("mysql://root:onny0620@localhost/blog") + .connect("mysql://root:xxxxxxxx/Blog") .await .expect("failed to connect database."); @@ -61,9 +64,11 @@ async fn article_list( Path(page_num): Path, ) -> ArticleSummaryVec { println!("page_num: {}", page_num); + info!("page_num: ", page_num); let page_size: i32 = 9; let offset = (page_num - 1) * page_size; println!("the offset is {}", &offset); + info!("the offset is {}", &offset); let summary_vec: Vec= sqlx::query_as("SELECT id, title, categoryId, summary,path, createOn, createBy FROM article WHERE deleted=0 order by id desc limit ?, ? ") .bind(offset) @@ -75,14 +80,18 @@ async fn article_list( .await .expect("Query page total failed!"); println!("total: {}", &total); + info!("total: ", &total); let page_total = ((total as f64 / page_size as f64).ceil()) as i32; println!("total pages: {}", &page_total); + info!("total pages: ", &page_total); println!("{:?}", &summary_vec); + //info!("{:#?}", &summary_vec); let mut vec1: Vec = vec![]; let mut vec2: Vec = vec![]; let mut vec3: Vec = vec![]; for (position, article) in summary_vec.iter().enumerate() { println!("position: {}", position); + info!("position: ", position); match position % 3 { 0 => vec1.push(article.clone()), @@ -107,27 +116,27 @@ async fn article_list( async fn article_detail(State(pool): State, Path(id): Path) -> ArticleDetail { println!("the article id is {}", &id); + info!("the article id is ", &id); let article: Article = sqlx::query_as("SELECT id, title, categoryId, summary, path, deleted, createOn, createBy, modifyOn, modifyBy FROM article WHERE ID=?") .bind(id) .fetch_one(&pool).await.expect("Can not find the article detail"); println!("the article detail {:?}", &article); - let (article_id, article_title, article_create_on) = article.clone().getInfo(); + let (article_id, article_title, article_create_on) = article.clone().get_info(); let article_detail = ArticleDetail::new(article_id, article_title, vec![], article_create_on); let content = article.read_file().await; article_detail.setContent(content) } -pub async fn extract_article(State(pool): State) ->String { +pub async fn extract_article(State(pool): State) -> String { let current_workspace = std::env::current_dir().unwrap().join("markdown"); - let insert_article_result = Extractor::visit_dirs(std::path::Path::new(current_workspace.as_os_str()), &pool) - .await; - match insert_article_result { - Ok(r) => "Insert Article successfully.".to_string(), - Err(err) => "Insert Article failed!".to_string() - } - + let insert_article_result = + Extractor::visit_dirs(std::path::Path::new(current_workspace.as_os_str()), &pool).await; + match insert_article_result { + Ok(_) => "Insert Article successfully.".to_string(), + Err(_) => "Insert Article failed!".to_string(), + } } async fn me() -> Person<'static> { @@ -159,6 +168,7 @@ mod test { #[tokio::test] async fn insert_db() { println!("insert article into db"); + info!(">>>>>>>>>>>>>>>>>insert article into db"); //let mysql_conn = MySqlPool::connect("mysql://root:onny0620@localhost/blog").await.expect("Failed to connect to database"); let mysql_conn = MySqlPoolOptions::new() -- Gitee From cd892a25b32fc5c2e7ace2e7ee4a564fd9f4ea35 Mon Sep 17 00:00:00 2001 From: "owen.chao" Date: Fri, 6 Sep 2024 19:15:54 +0800 Subject: [PATCH 112/115] add log config code --- .../{configuration.rs => db_config.rs} | 1 + src/configuration/log_config | 13 +++++++++++++ src/configuration/mod.rs | 3 ++- src/lib.rs | 1 + src/main.rs | 6 ++++-- 5 files changed, 21 insertions(+), 3 deletions(-) rename src/configuration/{configuration.rs => db_config.rs} (99%) create mode 100644 src/configuration/log_config diff --git a/src/configuration/configuration.rs b/src/configuration/db_config.rs similarity index 99% rename from src/configuration/configuration.rs rename to src/configuration/db_config.rs index f145d47..c753409 100644 --- a/src/configuration/configuration.rs +++ b/src/configuration/db_config.rs @@ -13,6 +13,7 @@ impl Configuration { pub fn new() {} //从当前目录读取配置文件 + pub fn read_from_configuration_file(&self) -> Self { let configuration_path = std::env::current_dir()?.join("configuration"); println!("configuration path: {}", &configuration_path); diff --git a/src/configuration/log_config b/src/configuration/log_config new file mode 100644 index 0000000..9018d58 --- /dev/null +++ b/src/configuration/log_config @@ -0,0 +1,13 @@ +use tklog::{ + sync::Logger, + LEVEL, LOG, + Format,MODE, + }; + + fn log_init() { + LOG.set_console(true) //设置控制台日志 + .set_level(LEVEL::Info) //日志级别,默认Info + .set_format(Format::LevelFlag | Format::Time | Format::ShortFileName) //结构化日志,定义输出的日志信息 + .set_cutmode_by_size("axum-hello.log", 10<<20, 10, true) //日志文件切割模式为文件大小,每1M文件切分一次,保留10个备份日志文件,并压缩备份日 + .set_formatter("{level}{time} {file}:{message}\n") //自定义日志输出格式。默认:{level}{time} {file}:{message}\n + } \ No newline at end of file diff --git a/src/configuration/mod.rs b/src/configuration/mod.rs index 2d148af..7e18065 100644 --- a/src/configuration/mod.rs +++ b/src/configuration/mod.rs @@ -1 +1,2 @@ -pub mod configuration; + +pub mod log_config; diff --git a/src/lib.rs b/src/lib.rs index 24660cc..0612770 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -5,4 +5,5 @@ //pub mod common; pub mod entity; pub mod job; +pub mod configuration; diff --git a/src/main.rs b/src/main.rs index d22155f..8ebabe7 100644 --- a/src/main.rs +++ b/src/main.rs @@ -7,6 +7,7 @@ use tklog::info; pub mod entity; pub mod job; pub mod person; +pub mod configuration; use crate::entity::article::Article; use crate::entity::article_detail::ArticleDetail; @@ -18,6 +19,9 @@ use crate::job::file_extractor::Extractor; #[tokio::main] async fn main() { + //初始化日志配置 + log_config::log_init(); + let workspace = std::env::current_dir().unwrap(); println!("{:?}", &workspace); info!("Current workspace:: {:?}", &workspace.to_string_lossy()); @@ -115,7 +119,6 @@ async fn article_list( } async fn article_detail(State(pool): State, Path(id): Path) -> ArticleDetail { - println!("the article id is {}", &id); info!("the article id is ", &id); let article: Article = sqlx::query_as("SELECT id, title, categoryId, summary, path, deleted, createOn, createBy, modifyOn, modifyBy FROM article WHERE ID=?") @@ -167,7 +170,6 @@ mod test { #[tokio::test] async fn insert_db() { - println!("insert article into db"); info!(">>>>>>>>>>>>>>>>>insert article into db"); //let mysql_conn = MySqlPool::connect("mysql://root:onny0620@localhost/blog").await.expect("Failed to connect to database"); -- Gitee From 39ae5476e2273ab422f2ed7367bd423d563a60ab Mon Sep 17 00:00:00 2001 From: "owen.chao" Date: Fri, 6 Sep 2024 19:17:39 +0800 Subject: [PATCH 113/115] add log config code --- src/configuration/{log_config => log_config.rs} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename src/configuration/{log_config => log_config.rs} (100%) diff --git a/src/configuration/log_config b/src/configuration/log_config.rs similarity index 100% rename from src/configuration/log_config rename to src/configuration/log_config.rs -- Gitee From 07dd1ca99844ffe71be286acaa25e521a67bdd4b Mon Sep 17 00:00:00 2001 From: owen Date: Fri, 6 Sep 2024 22:25:00 +0800 Subject: [PATCH 114/115] add log config --- src/configuration/log_config.rs | 20 ++++++++------------ src/main.rs | 8 ++++---- 2 files changed, 12 insertions(+), 16 deletions(-) diff --git a/src/configuration/log_config.rs b/src/configuration/log_config.rs index 9018d58..03b20a1 100644 --- a/src/configuration/log_config.rs +++ b/src/configuration/log_config.rs @@ -1,13 +1,9 @@ -use tklog::{ - sync::Logger, - LEVEL, LOG, - Format,MODE, - }; +use tklog::{Format, LEVEL, LOG}; - fn log_init() { - LOG.set_console(true) //设置控制台日志 - .set_level(LEVEL::Info) //日志级别,默认Info - .set_format(Format::LevelFlag | Format::Time | Format::ShortFileName) //结构化日志,定义输出的日志信息 - .set_cutmode_by_size("axum-hello.log", 10<<20, 10, true) //日志文件切割模式为文件大小,每1M文件切分一次,保留10个备份日志文件,并压缩备份日 - .set_formatter("{level}{time} {file}:{message}\n") //自定义日志输出格式。默认:{level}{time} {file}:{message}\n - } \ No newline at end of file +pub fn log_init() { + LOG.set_console(true) + .set_level(LEVEL::Info) + .set_format(Format::LevelFlag | Format::Time | Format::ShortFileName) + .set_cutmode_by_size("tklogsize.txt", 1 << 20, 10, true) + .set_formatter("{level}{time} {file}:{message}\n"); +} diff --git a/src/main.rs b/src/main.rs index 8ebabe7..2e6223f 100644 --- a/src/main.rs +++ b/src/main.rs @@ -4,10 +4,10 @@ use sqlx::MySqlPool; use tklog::info; +pub mod configuration; pub mod entity; pub mod job; pub mod person; -pub mod configuration; use crate::entity::article::Article; use crate::entity::article_detail::ArticleDetail; @@ -20,8 +20,8 @@ use crate::job::file_extractor::Extractor; #[tokio::main] async fn main() { //初始化日志配置 - log_config::log_init(); - + configuration::log_config::log_init(); + let workspace = std::env::current_dir().unwrap(); println!("{:?}", &workspace); info!("Current workspace:: {:?}", &workspace.to_string_lossy()); @@ -35,7 +35,7 @@ async fn main() { let basic_path = Arc::new(args[1].clone()); */ let pool = MySqlPoolOptions::new() - .connect("mysql://root:xxxxxxxx/Blog") + .connect("mysql://root:rust(202408)@47.92.236.188/Blog") .await .expect("failed to connect database."); -- Gitee From f8102bc711397882dc4bfc0adcef357ae8e0e97a Mon Sep 17 00:00:00 2001 From: owen Date: Fri, 6 Sep 2024 22:29:57 +0800 Subject: [PATCH 115/115] add log config --- src/main.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main.rs b/src/main.rs index 2e6223f..35044b2 100644 --- a/src/main.rs +++ b/src/main.rs @@ -35,7 +35,7 @@ async fn main() { let basic_path = Arc::new(args[1].clone()); */ let pool = MySqlPoolOptions::new() - .connect("mysql://root:rust(202408)@47.92.236.188/Blog") + .connect("mysql://xxx/Blog") .await .expect("failed to connect database."); -- Gitee