11use regex:: Regex ;
22use std:: fs;
33use std:: path:: Path ;
4+ use tokio:: time;
45
56fn extract_links_from_file < P : AsRef < Path > > ( path : P ) -> Vec < String > {
67 let content = fs:: read_to_string ( & path) . unwrap ( ) ;
@@ -22,16 +23,15 @@ enum LinkCheckResult {
2223 Invalid ( String ) ,
2324}
2425
25- fn check_link ( url : & str ) -> LinkCheckResult {
26- let client = reqwest:: blocking :: Client :: builder ( )
26+ async fn check_link ( url : & str ) -> LinkCheckResult {
27+ let client = reqwest:: Client :: builder ( )
2728 . timeout ( std:: time:: Duration :: from_secs ( 10 ) )
2829 . build ( )
2930 . unwrap ( ) ;
3031
3132 let mut attempts = 3 ;
3233 while attempts > 0 {
33- let res = client. get ( url) . send ( ) ;
34- match res {
34+ match client. get ( url) . send ( ) . await {
3535 Ok ( res) => {
3636 let status = res. status ( ) ;
3737 return if status. is_success ( ) || status. is_redirection ( ) {
@@ -47,16 +47,27 @@ fn check_link(url: &str) -> LinkCheckResult {
4747 }
4848 }
4949 attempts -= 1 ;
50+ time:: sleep ( time:: Duration :: from_secs ( 1 ) ) . await ;
5051 }
5152 LinkCheckResult :: Invalid ( "Max retries exceeded" . to_string ( ) )
5253}
5354
54- fn main ( ) {
55+ #[ tokio:: main]
56+ async fn main ( ) {
5557 let file_path = "example.md" ;
5658 let links = extract_links_from_file ( file_path) ;
5759
60+ let mut handles = Vec :: new ( ) ;
5861 for link in links {
59- if let LinkCheckResult :: Invalid ( message) = check_link ( & link) {
62+ let handle = tokio:: spawn ( async move {
63+ let result = check_link ( & link) . await ;
64+ ( link, result)
65+ } ) ;
66+ handles. push ( handle) ;
67+ }
68+
69+ for handle in handles {
70+ if let Ok ( ( link, LinkCheckResult :: Invalid ( message) ) ) = handle. await {
6071 println ! ( "유효하지 않은 링크: '{}', 실패 원인: {}" , link, message) ;
6172 }
6273 }
@@ -96,11 +107,14 @@ mod tests {
96107 Ok ( ( ) )
97108 }
98109
99- #[ test]
100- fn validate_link ( ) {
110+ #[ tokio :: test]
111+ async fn validate_link ( ) {
101112 let link = "https://redddy.com" ;
102- assert ! ( matches!( check_link( link) , LinkCheckResult :: Invalid ( _) ) ) ;
113+ assert ! ( matches!(
114+ check_link( link) . await ,
115+ LinkCheckResult :: Invalid ( _)
116+ ) ) ;
103117 let link = "https://lazypazy.tistory.com" ;
104- assert_eq ! ( check_link( link) , LinkCheckResult :: Valid ) ;
118+ assert_eq ! ( check_link( link) . await , LinkCheckResult :: Valid ) ;
105119 }
106120}
0 commit comments