Skip to content

Commit 3e73d92

Browse files
committed
Applied sample codes
1 parent bc7e366 commit 3e73d92

File tree

1 file changed

+91
-7
lines changed

1 file changed

+91
-7
lines changed

router/src/main.rs

Lines changed: 91 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,96 @@
1-
fn main() {
2-
1+
use std::{fs::OpenOptions, io::Write};
2+
3+
fn main() -> anyhow::Result<()> {
4+
// File Storage kullanımı
5+
6+
let fs_handler = Box::new(FileStorageHandler {
7+
base_path: ".".into(),
8+
});
9+
10+
let mut router = Router::new(fs_handler);
11+
12+
router.add(Request {
13+
path: "api/users/title".into(),
14+
data: b"{\"name\": \"john@doe\"}".to_vec(),
15+
});
16+
router.apply()?;
17+
18+
router.add(Request {
19+
path: "api/products".into(),
20+
data: b"{\"category\": \"Books\"}".to_vec(),
21+
});
22+
router.apply()?;
23+
24+
// Api Yönlendirme Kullanımı
25+
router.handler = Box::new(PassToRemoteHandler {
26+
target_uri: "https://backend-services/api/route/one".into(),
27+
});
28+
router.apply()?;
29+
30+
Ok(())
31+
}
32+
33+
pub struct Request {
34+
pub path: String,
35+
pub data: Vec<u8>,
36+
}
37+
38+
pub trait RouteHandler {
39+
fn handle(&self, request: &Request) -> anyhow::Result<()>;
340
}
441

5-
pub struct Request<'a> {
6-
pub path:&'a str,
7-
pub data:Vec<u8>
42+
pub struct FileStorageHandler {
43+
pub base_path: String,
844
}
945

10-
pub trait RouteHandler{
11-
fn handle(&self,request:&Request) -> anyhow::Result<()>;
46+
impl RouteHandler for FileStorageHandler {
47+
fn handle(&self, request: &Request) -> anyhow::Result<()> {
48+
let mut file = OpenOptions::new()
49+
.append(true)
50+
.create(true)
51+
.open("request_logs.dat")?;
52+
file.write_all(&request.data)?;
53+
Ok(())
54+
}
55+
}
56+
57+
pub struct PassToRemoteHandler {
58+
pub target_uri: String,
59+
}
60+
61+
impl RouteHandler for PassToRemoteHandler {
62+
fn handle(&self, request: &Request) -> anyhow::Result<()> {
63+
println!(
64+
"Pretending to POST to {}{} with {} bytes",
65+
self.target_uri,
66+
request.path,
67+
request.data.len()
68+
);
69+
70+
Ok(())
71+
}
72+
}
73+
74+
pub struct Router {
75+
requests: Vec<Request>,
76+
handler: Box<dyn RouteHandler>,
77+
}
78+
79+
impl Router {
80+
pub fn new(handler: Box<dyn RouteHandler>) -> Self {
81+
Router {
82+
requests: Vec::new(),
83+
handler,
84+
}
85+
}
86+
pub fn add(&mut self, request: Request) {
87+
self.requests.push(request);
88+
}
89+
90+
pub fn apply(&self) -> anyhow::Result<()> {
91+
for r in self.requests.iter() {
92+
self.handler.handle(&r)?;
93+
}
94+
Ok(())
95+
}
1296
}

0 commit comments

Comments
 (0)