| Pattern | Kind | Description |
| ------------------------------- | ------------------- | ------------------------------------------------------------------------------ |
| :name
| Normal
| Matches a path piece, excludes /
|
| :name?
| Optional
| Matches an optional path piece, excludes /
|
| /:name?/
/:name?
| OptionalSegment
| Matches an optional path segment, excludes /
, prefix or suffix should be /
|
| +
:name+
| OneOrMore
| Matches a path piece, includes /
|
| *
:name*
| ZeroOrMore
| Matches an optional path piece, includes /
|
| /*/
/*
/:name*/
/:name*
| ZeroOrMoreSegment
| Matches zero or more path segments, prefix or suffix should be /
````rust use hypers::prelude::*; use std::time::Instant;
pub struct CookieJarParams { pub hypers: String, pub rust: String, }
pub struct HeaderParams {
pub host: Option
pub struct PathParams {
pub id: Option
pub struct QueryParams {
pub id: Option
pub struct FormParams { pub id: u32, pub name: String, pub age: u16, }
pub struct JsonParams {
pub id: Option
// Request Cookies
pub async fn parsecookies(req: Request) -> impl Responder {
let cookiejar = req.parsecookies::
// Request Headers
pub async fn parseheader(req: Request) -> impl Responder {
let headerparams = req.parseheader::
// Url Path Params
pub async fn parseparam(req: Request) -> impl Responder {
let params = req.parseparam::
// Url Query Params
pub async fn parsequery(req: Request) -> impl Responder {
let queryparams = req.parsequery::
// Context-Type : application/x-www-form-urlencoded
pub async fn parseformpatch(mut req: Request) -> impl Responder {
let user = req.parse::
// Context-Type : application/x-www-form-urlencoded
pub async fn parseformget(mut req: Request) -> impl Responder {
let user = req.parse::
// Context-Type : application/json
pub async fn parse_json(mut req: Request) -> impl Responder {
let user = req.parse::
// Context-Type : multipart/form-data Form Fields
pub async fn multipartform(mut req: Request) -> impl Responder {
let formdata = req.parse::
// Context-Type : multipart/form-data Files pub async fn multipartfile(mut req: Request) -> impl Responder { let file = req.file("file").await?; let filename = file.name()?; let filename = filename.to_string();
let img = req.files("imgs").await?;
let imgs_name = img
.iter()
.map(|m| m.name().unwrap().to_string())
.collect::<Vec<String>>()
.join(",");
Some((
200,
format!("file_name = {}, imgs_name = {}", file_name, imgs_name),
))
}
// Request Headers
pub async fn header(req: Request) -> impl Responder {
let host = req.header::
// Url Path Params
pub async fn param(req: Request) -> impl Responder {
let name = req.param::
// Url Query Params
pub async fn query(req: Request) -> impl Responder {
let name = req.query::
// Websocket ws://127.0.0.1:7878/hello/ws http://www.jsons.cn/websocket/
pub async fn websocket(req: Request, mut ws: WebSocket) -> Result<()> {
let name = req.param::
// Middleware Function pub async fn stattime(req: Request, netx: Next) -> Result { // Before executing the request processing function let starttime = Instant::now();
// Calling subsequent request processing functions
let res = netx.next(req).await?;
// After the execution of the request processing function
let elapsed_time = start_time.elapsed();
println!(
"The current request processing function takes time :{:?}",
elapsed_time
);
println!(
"The response after the execution of the current request processing function : {:?}",
res.body()
);
Ok(res)
}
pub async fn logger(req: Request, next: Next) -> Result { // Before executing the request processing function let uri = req.uri().path(); println!("uri = {:?}", uri);
// Calling subsequent request processing functions
let res = next.next(req).await;
// After the execution of the request processing function
res
}
// Write router like a tree fn main() -> Result<()> {
// The Root Router
let mut root = Router::new("/");
// Add Middleware ( Middleware can be added to any routing node )
root.hook(logger, vec!["/param/:name/:age"], None);
root.get("/*", StaticDir::new("src").listing(true));
root.ws(":name/ws", websocket);
root.get("/header", header);
root.delete("param/:name/:age", param);
root.get("query", query);
root.get("set_cookies", |_| async {
let mut cookie1 = Cookie::new("hypers", "hypers2023");
cookie1.set_path("/user");
let mut cookie2 = Cookie::new("rust", "athene2023");
cookie2.set_path("/user");
let mut cookie_jar = CookieJar::new();
cookie_jar.add(cookie1);
cookie_jar.add(cookie2);
(200, cookie_jar)
});
// The Sub Router
let mut user = Router::new("user");
user.hook(stat_time, vec!["/user"], None);
user.get("parse_cookies", parse_cookies)
.get("/parse_header", parse_header)
.delete("parse_param/:id/:name", parse_param)
.get("parse_query", parse_query)
.patch("parse_form_patch", parse_form_patch)
.get("parse_form_get", parse_form_get)
.post("parse_json", parse_json)
.post("/multipart_form", multipart_form)
.post("multipart_file", multipart_file);
// Add sub router to the root router
root.push(user);
// Registering the root router into the server
let app = hypers::new(root);
// Start Server
// Not Use SSL/TLS
#[cfg(not(any(feature = "rustls", feature = "native_tls")))]
{
app.run("127.0.0.1:7878")
}
// Use SSL/TLS
#[cfg(feature = "rustls")]
{
let tls = RustlsConfig::new()
.cert(include_bytes!("./certs/cert.pem").to_vec())
.key(include_bytes!("./certs/key.pem").to_vec());
app.run("127.0.0.1:7878", tls)
}
// Use SSL/TLS
#[cfg(feature = "native_tls")]
{
let tls = NativeTls::from_pkcs12(include_bytes!("./certs/identity.p12"), "mypass")?;
app.run("127.0.0.1:7878", tls)
}
} `````