athene 1.4.7

A simple and lightweight rust web framework based on Hyper, with routing similar to Java SpringBoot and Go gin
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
# [example]https://gitea.com/rustacean/athene-example.git

# `This version is built on hyper v0.14 and crate async_trait is used `

# 1、 Usage MacroController     
## use athene's validate and multipart feature

````rust
use athene::prelude::*;
use serde::{Deserialize, Serialize};
use validator::Validate;

static INDEX_HTML: &str = r#"<!DOCTYPE html>
<html>
    <head>
        <title>Upload Test</title>
    </head>
    <body>
        <h1>Upload Test</h1>
        <form action="/api/v1/user/upload" method="post" enctype="multipart/form-data">
            <input type="file" name="file" />
            <input type="submit" value="upload" />
        </form>
    </body>
</html>
"#;

#[derive(Serialize, Deserialize, Validate, Default, Debug)]
pub struct UserController {
    #[validate(email)]
    pub username: String,
    #[validate(range(min = 18, max = 20))]
    pub age: u16,
}

// http://127.0.0.1:7878/api/v1/user
#[controller(prefix = "api", version = 1, name = "user")]
impl UserController {

    // http://127.0.0.1:7878/api/v1/user/xxx
    #[get("/*/**")]
    pub async fn match_any_route(&self, req: Request) -> impl Responder {
        let uri_path = req.uri().path().to_string();
        let method = req.method().to_string();
        (201, format!("uri : {}, method: {}", uri_path, method))
    }

    // http://127.0.0.1:7878/api/v1/user/web/18
    #[delete("/{username}/{age}")] // username and age will not be validated
    pub async fn delete_by_param(&self, username: String, age: Option<u16>) -> impl Responder {
        (
            202,
            format!("username is : {}, and age is : {:?}", username, age),
        )
    }

    // http://127.0.0.1:7878/api/v1/user/get_query_1/?username=admin&age=29
    #[get("/get_query_1")] // username and age will not be validated
    pub async fn get_query_1(&self, username: String, age: u16) -> impl Responder {
        (203, Json(Self { username, age }))
    }

    // http://127.0.0.1:7878/api/v1/user/get_query_2/?username=admin@qq&age=19
    #[get("/get_query_2")] // user will be validated
    pub async fn get_query_2(&self, user: Query<Self>) -> impl Responder {
        (203, Json(user.0))
    }

    // http://127.0.0.1:7878/api/v1/user/parse_json_body
    // Context-Type : application/json
    #[post("/parse_json_body")]
    #[get("/parse_json_body")] // user will be validated
    async fn parse_json_body(&self, user: Json<Self>) -> impl Responder {
        Ok::<_, Error>((206, user))
    }

    // http://127.0.0.1:7878/api/v1/user/parse_form_body
    // Context-Type : application/x-www-form-urlencoded
    #[post("/parse_form_body")]
    #[get("/parse_form_body")] // user will be validated
    async fn parse_form_body(&self, user: Form<Self>) -> impl Responder {
        Ok::<_, Error>((206, user))
    }

    // http://127.0.0.1:7878/api/v1/user/parse_body_vec
    #[post("/parse_body_vec")]
    #[get("/parse_body_vec")]
    async fn parse_body_vec(&self,mut req: Request) -> impl Responder {
        let vector = req.parse_body::<Vec<u8>>().await?;
        Ok::<_, Error>((StatusCode::OK, vector))
    }
    
    // http://127.0.0.1:7878/api/v1/user/parse_body_string
    #[post("/parse_body_string")]
    #[get("/parse_body_string")]
    async fn parse_body_string(&self,mut req: Request) -> impl Responder {
        let vector = req.parse_body::<String>().await?;
        Ok::<_, Error>((StatusCode::OK, vector))
    }

    // http://127.0.0.1:7878/api/v1/user/file
    #[post("/file")]
    pub async fn file(&self, mut req: Request) -> impl Responder {
        let file = req.file("file").await?;
        let file_name = file
            .name()
            .ok_or_else(|| Error::Other("file not found".to_string()))?;
        Ok::<_, Error>((200, file_name.to_string()))
    }

    // http://127.0.0.1:7878/api/v1/user/files
    #[post("/files")]
    pub async fn files(&self, mut req: Request) -> impl Responder {
        let files = req.files("files").await?;
        let fist_file_name = files[0]
            .name()
            .ok_or_else(|| Error::Other("file not found".to_string()))?;
        let second_file_name = files[1]
            .name()
            .ok_or_else(|| Error::Other("file not found".to_string()))?;
        Ok::<_, Error>((
            200,
            format!(
                "fist_file_name: {}, second_file_name: {}",
                fist_file_name, second_file_name
            ),
        ))
    }

    // http://127.0.0.1:7878/api/v1/user/upload
    #[post("/upload")]
    pub async fn upload(&self, mut req: Request) -> impl Responder {
        let res = req.upload("file", "temp").await?;
        if res > 0 {
            Ok::<_, Error>((200, "File uploaded successfully"))
        } else {
            Ok::<_, Error>((400, "File upload failed"))
        }
    }

    // http://127.0.0.1:7878/api/v1/user/uploads
    #[post("/uploads")]
    pub async fn uploads(&self, mut req: Request) -> impl Responder {
        let msg = req.uploads("files", "temp").await?;
        Ok::<_, Error>((200, msg))
    }

    // http://127.0.0.1:7878/api/v1/user/download
    // Content-Disposition: application/octet-stream
    #[get("/download")]
    pub async fn download(&self, _req: Request) -> impl Responder {
        let mut res = Response::new();
        res.write_file("temp/ws.rs", DispositionType::Attachment)?;
        Ok::<_, Error>((200, "Download successful"))
    }
}

#[tokio::main]
pub async fn main() -> Result<()> {

    let app = athene::new().router(|r| {
        r.get("/api/v1/user/upload", |_: Request| async {
            Html(INDEX_HTML)
        })
        .controller(UserController::default())
    });

    app.listen("127.0.0.1:7878").await
}
````

# 2、Usage BasicController
````rust
use athene::prelude::*;
use serde::{Deserialize, Serialize};

#[derive(Default, Serialize, Deserialize)]
pub struct AtheneController {
    pub label: String,
    pub keyword: String,
}

impl Controller for AtheneController {
    const BASE_PATH: &'static str = "/api/v1/athene";

    fn method(&self) -> Vec<ControllerMethod<Self>>
    where
        Self: Sized,
    {
        ControllerBuilder::new()
            .post("/add", Self::add)
            .delete("/{label}/{keyword}", Self::delete)
            .put("/update", Self::update)
            .get("/get", Self::get)
            .build()
    }
}

impl AtheneController {

    // http://127.0.0.1:7878/api/v1/athene/add
    pub async fn add(&self, mut req: Request) -> impl Responder {
        let obj = req.parse::<Self>().await?;
        Ok::<_, Error>((200, Json(obj)))
    }

    // http://127.0.0.1:7878/api/v1/athene/
    pub async fn delete(&self, mut req: Request) -> impl Responder {
        let lable = req.param::<String>("label")?;
        let keyword = req.param::<String>("keyword")?;

        Ok::<_, Error>((300, format!("lable = {},keyword = {}", lable, keyword)))
    }

    // http://127.0.0.1:7878/api/v1/athene/update
    // Context-Type : application/json  Or application/x-www-form-urlencoded
    async fn update(&self, mut req: Request) -> impl Responder {
        let obj = req.parse::<Self>().await?;
        Ok::<_, Error>((200, Json(obj)))
    }

    // http://127.0.0.1:7878/api/v1/athene/get
    async fn get(&self, req: Request) -> impl Responder {
        #[derive(Deserialize, Serialize)]
        struct QueryParam<'a> {
            label: &'a str,
            keyword: &'a str,
        }

        let arg = req.query::<QueryParam>()?;
        let res = Response::new();
        Ok::<_, Error>(res.json(&arg))
    }
}

#[tokio::main]
async fn main() -> Result<(), Error> {

    let app = athene::new()
        .router(|r| r.controller(AtheneController::default()));

    app.listen("127.0.0.1:7878").await
}
````

# 3、Usage Middleware and RouterGroup
````rust
use athene::prelude::*;
use headers::{authorization::Bearer, Authorization};
use serde::{Deserialize, Serialize};
use tracing::info;

#[derive(Serialize, Deserialize)]
pub struct User {
    pub username: String,
    pub age: u16,
}

// 127.0.0.1:7878/user/admin/18
pub async fn user_params(mut req: Request) -> impl Responder {
    let username = req.param("username")?;
    let age = req.param::<u16>("age")?;
    Ok::<_, Error>((200, Json(User { username, age })))
}

// 127.0.0.1:7878/user/sign_up
pub async fn sign_up(mut req: Request) -> impl Responder {
    let user = req.parse::<User>().await?;
    Ok::<_, Error>((200, Json(user)))
}

// 127.0.0.1:7878/user/body_to_vec_u8
pub async fn body_to_vec_u8(mut req: Request) -> impl Responder {
    let body = req.parse_body::<Vec<u8>>().await?;
    Ok::<_, Error>((200, body))
}

// 127.0.0.1:7878/user/body_to_string
pub async fn body_to_string(mut req: Request) -> impl Responder {
    let body = req.parse_body::<String>().await?;
    Ok::<_, Error>((200, body))
}

pub fn user_router(r: Router) -> Router {
    r.group("/user")
        .get("/{username}/{age}", user_params)
        .post("/login", login)
        .post("/sign_up", sign_up)
        .put("/body_to_vec_u8", body_to_vec_u8)
        .post("/body_to_string", body_to_string)
}

// 127.0.0.1:7878/user/login
pub async fn login(mut req: Request) -> impl Responder {
    if let Ok(user) = req.parse::<User>().await {
        (
            201,
            format!("username: {} , age: {} ", user.username, user.age),
        )
    } else {
        (400, String::from("Bad user format"))
    }
}

pub async fn log_middleware(ctx: Context, next: &dyn Next) -> Result {
    let uri_path = ctx.state.request().map(|req| req.uri().path());
    info!("new request on path: {:?}", uri_path);
    let ctx = next.next(ctx).await?;
    let status = ctx.state.response().map(|res| res.status());
    info!("new response with status: {:?}", status);
    Ok(ctx)
}

struct ApiKeyMiddleware {
    api_key: String,
}

#[derive(Debug, Deserialize, Serialize)]
pub struct MiddlewareError<T> {
    pub code: u32,
    pub msg: String,
    pub data: T
}

#[middleware]
impl ApiKeyMiddleware {
    async fn next(&self, ctx: Context, chain: &dyn Next) -> Result {
        if let Some(req) = ctx.state.request() {
            if let Some(bearer) = req.header::<Authorization<Bearer>>() {
                let token = bearer.0.token();
                if token == self.api_key {
                    info!(
                        "Handler {} will be used",
                        ctx.metadata.name.unwrap_or("unknown")
                    );
                    chain.next(ctx).await
                } else {
                    info!("Invalid token");
                    let res = MiddlewareError {
                        code: 400,
                        msg: String::from("Invalid token"),
                        data: "Invalid token"
                    };
                    Err(Error::Json(json!(res)))
                }
            } else {
                info!("Not Authenticated");
                Err(Error::Response(404,json!("Not Authenticated")))
            }
        } else {
            Ok(ctx)
        }
    }
}

#[tokio::main]
pub async fn main() -> Result<()> {

    tracing_subscriber::fmt().compact().init();

    let app = athene::new().router(user_router).middleware(|m| {
        m.apply(log_middleware, vec!["/"], None).apply(
            ApiKeyMiddleware {
                api_key: "athene".to_string(),
            },
            vec!["/user/login", "/user/sign_up"],
            vec!["/user/body_to_vec_u8", "/user/body_to_string"],
        )
    });

    app.listen("127.0.0.1:7878").await
}
````

# 4、Load static files and directories
## use athene's static_file feature

````rust
use athene::prelude::*;

#[tokio::main]
pub async fn main() -> Result<()> {
    let app = athene::new().router(|r| {
        
        // Using this in a production environment
        // let r = r.static_dir("/**", "athene");

        // If you want to test the functionality, use this
        let r = r.get("/**", StaticDir::new("athene").with_listing(true));
        r
    });
    app.listen("127.0.0.1:7879").await
}
````

# 5、Support  Websocket 
## use athene's websocket feature

````rust
use athene::prelude::*;

// ws://127.0.0.1:7878/ws  
// http://www.jsons.cn/websocket/
#[tokio::main]
async fn main() -> Result<()> {
    let app = athene::new().router(|r| {
        r.ws("/ws", |_req, mut tx, mut rx| async move {
            while let Some(msg) = rx.receive().await? {
                tx.send(msg).await?;
            }
            Ok(())
        })
    });
    app.listen("127.0.0.1:7878").await
}
`````