`````rust use athene::handler::Handler; use athene::prelude::*; use std::future::Future; use serde::{Deserialize, Serialize};
pub struct User { pub name: String, pub age: i32, }
impl Handler for User {
type Responder = Builder;
type Future = Box
fn handle(&self, req: Request) -> Self::Future {
Box::new(Box::pin(async move {
let uri = req.uri().path();
let method = req.method();
let peer_addr = req.peer_addr();
let builder = Builder::new();
builder.text(format!("uri : {}, method: {}, peer_addr: {}",uri,method,peer_addr))
}))
}
}
impl User { pub fn hello(_: Request) -> impl Future
pub fn get_user(mut req: Request) -> impl Future<Output = impl Responder> {
async move {
let user = req.parse::<User>().await?;
Ok::<_, Error>(json!(user))
}
}
pub fn basic_router(r: Router) -> Router {
r.get("/hello", Self::hello)
.post("/user", Self::default())
.post("/get_user", Self::get_user)
}
}
pub async fn main() -> Result<()> {
let app = athene::new()
.router(|r| {
r.get("/",|: Request| async {
"Hello World"
})
})
.router(User::basicrouter)
.build();
app.listen("127.0.0.1:7878").await
} `````
````rust use athene::prelude::*; use serde::{Deserialize,Serialize};
use validator::Validate;
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
impl UserController {
#[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();
(200, format!("uri : {}, method: {}", uri_path, method))
}
#[delete("/{username}/{age}")]
pub async fn delete_by_param(&self, username: String, age: Option<u16>) -> impl Responder {
(200, format!("username is : {}, and age is : {:?}", username, age))
}
#[get("/get_query_1")]
pub async fn get_query_1(&self, username: String, age: u16) -> impl Responder {
(200,json!(&Self {
username,
age,
}))
}
#[get("/get_query_2")]
//#[validator(exclude("user"))] // The user parameter will not be validated
pub async fn get_query_2(&self, request: Request) -> impl Responder {
let user = request.query::<Self>()?;
Ok::<_, Error>((200, json!(&user)))
}
// Context-Type : application/json Or application/x-www-form-urlencoded
// Context-Type : application/msgpack Or application/cbor
#[post("/parse_body")]
#[get("/parse_body")]
//#[validator] // User will be validated
async fn parse_body(&self, mut req: Request) -> impl Responder {
let user = req.parse::<Self>().await?;
Ok::<_, Error>((
200,
format!("username = {} and age = {}", user.username, user.age),
))
}
// Context-Type : application/multipart-formdata
#[post("/files")]
async fn files(&self, mut req: Request) -> impl Responder {
let files = req.files("files").await?;
let fist_file_name = files[0].name().unwrap();
let second_file_name = files[1].name().unwrap();
Ok::<_, Error>((
200,
format!(
"fist {}, second {}",
fist_file_name, second_file_name
),
))
}
// Content-Disposition: application/octet-stream
#[get("/download")]
pub async fn download(&self,_req: Request) -> impl Responder {
let mut res = status!(hyper::StatusCode::OK);
res.write_file("templates/author.txt", DispositionType::Attachment)?;
Ok::<_, Error>(res)
}
}
pub async fn main() -> Result<()> {
let app = athene::new()
.router(|r|r.controller(UserController::default()));
let app = app.build();
app.listen("127.0.0.1:7878").await
} ````
````rust use athene::prelude::*; use serde::{Deserialize, Serialize};
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("label");
let keyword = req.param("keyword");
(200,format!("lable = {},keyword = {}",lable,keyword))
}
// http://127.0.0.1:7878/api/v1/athene/update
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 = json!(&arg);
Ok::<_, Error>(res)
}
}
async fn main() -> Result<(), Error> { let app = athene::new() .router(|r|r.controller(AtheneController::default())) .build();
app.listen("127.0.0.1:7878").await
} ````
````rust use athene::prelude::*; use headers::{authorization::Bearer, Authorization}; use serde::{Deserialize, Serialize}; use tracing::info;
pub struct User { pub username: String, pub age: u16, }
pub async fn user_params(mut req: Request) -> impl Responder {
let username = req.param("username");
let age = req.param("age");
let age = age.parse::
pub async fn login(mut req: Request) -> impl Responder {
if let Ok(user) = req.parse::
pub async fn sign_up(mut req: Request) -> impl Responder {
let user = req.parse::
pub async fn readbody(mut req: Request) -> impl Responder { let body = req.bodybytes().await?; Ok::<_, Error>((200, body)) }
pub fn userrouter(r: Router) -> Router { r.get("/{username}/{age}", userparams) .post("/login", login) .post("/signup", signup) .put("/readbody", readbody) }
// ============================ Middleware Fuction ============================
pub async fn logmiddleware(ctx: Context, next: &'static dyn Next) -> Result
let ctx = next.next(ctx).await?;
info!(
"new response with status: {}",
ctx.state.response_unchecked().status()
);
Ok(ctx)
}
// ================================ Middleware ====================== struct ApiKeyMiddleware { api_key: String, }
impl ApiKeyMiddleware {
async fn next(&self, ctx: Context, next: &dyn Next) -> Result
pub async fn main() -> Result<()> { let app = athene::new() .router(userrouter) .middleware(|m| { m.apply(logmiddleware, vec!["/"], None).apply( ApiKeyMiddleware { apikey: "athene".tostring(), }, vec!["/login", "/signup"], vec!["/readbody"], ) }) .build(); app.listen("127.0.0.1:7878").await } ````