hypers 0.1.13

A simple rust web framework based on hyper 1.0.0-rc.4
Documentation

HTTP Request URL Parameters Syntax

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 /

⚡️ Quick Start

use hypers's full feature

use hypers::prelude::*;
use std::time::Instant;
use utoipa::{IntoParams, OpenApi, ToSchema};

#[derive(Serialize, Deserialize)]
pub struct CookieJarParams {
    pub hypers: String,
    pub rust: String,
}

#[derive(Serialize, Deserialize, ToSchema)]
pub struct HeaderParams {
    pub host: Option<String>,
    #[serde(rename(deserialize = "user-agent"))]
    pub user_agent: Option<String>,
    pub accept: Option<String>,
}

#[derive(Serialize, Deserialize, IntoParams, ToSchema)]
pub struct PathParams {
    pub id: Option<u32>,
    pub name: Option<String>,
    pub age: Option<u16>,
}

#[derive(Serialize, Deserialize, IntoParams, ToSchema)]
#[into_params(parameter_in = Query)]
pub struct QueryParams {
    pub id: Option<u32>,
    pub name: Option<String>,
    pub age: Option<u16>,
}

#[derive(Serialize, Deserialize, ToSchema)]
pub struct FormParams {
    pub id: u32,
    pub name: String,
    pub age: u16,
}

#[derive(Debug, Serialize, Deserialize, ToSchema)]
pub struct JsonParams {
    pub id: Option<u32>,
    pub name: Option<String>,
    pub age: Option<u16>,
}

// Request Cookies
#[get("/parse_cookies")]
pub async fn parse_cookies(req: Request) -> impl Responder {
    let cookie_jar = req.parse_cookies::<CookieJarParams>()?;
    Ok::<_, Error>((200, Json(cookie_jar)))
}

// Request Headers
#[utoipa::path(
    get,
    path = "/user/parse_header",
    tag = "parse request headers",
    responses(
        (status = 200, description = "Parse header from request successfully", body = HeaderParams),
        (status = 404, description = "Parse header from request failed")
    )
)]
#[get("/parse_header")]
pub async fn parse_header(req: Request) -> impl Responder {
    let header_params = req.parse_header::<HeaderParams>()?;
    /*
       ....
    */
    Ok::<_, Error>((200, Json(header_params)))
}

// Url Path Params
#[utoipa::path(
    delete,
    path = "/user/parse_param/{id}/{name}/{age}",
    tag = "parse request url path params",
    params(PathParams) ,
    responses(
        (status = 200, description = "Parse Url Path Params successfully",body = PathParams),
        (status = 404, description = "Parse Url Path Params failed")
    ),
    security(
        ("api_key" = [])
    )
)]
#[delete("parse_param/:id/:name/:age")]
pub async fn parse_param(req: Request) -> impl Responder {
    let params = req.parse_param::<PathParams>()?;
    let app_state = req.get::<JsonParams>("user");
    println!("app_state = {:?}", app_state);
    /*
       .....
    */
    Ok::<_, Error>((200, Json(params)))
}

// Url Query Params
#[utoipa::path(
    get,
    path = "/user/parse_query",
    tag = "parse request url query params",
    params(QueryParams),
    responses(
        (status = 200, description = "Parse query successfully", body = QueryParams)
    )
)]
#[get("parse_query")]
pub async fn parse_query(req: Request) -> impl Responder {
    let query_params = req.parse_query::<QueryParams>()?;
    /*
       .....
    */
    Ok::<_, Error>((200, Json(query_params)))
}

// Context-Type : application/x-www-form-urlencoded
#[utoipa::path(
    patch,
    path = "/user/parse_form_patch",
    tag = "parse request body",
    request_body(
        content = FormParams,
        content_type = "application/x-www-form-urlencoded",
    ),
    responses(
        (status = 200, description = "FormParams created successfully", body = FormParams),
        (status = 409, description = "FormParams already exists")
    )
)]
#[patch("parse_form_patch")]
pub async fn parse_form_patch(mut req: Request) -> impl Responder {
    let user = req.parse::<FormParams>().await?;
    /*
       .....
    */
    Ok::<_, Error>((200, Json(user)))
}

// Context-Type : application/x-www-form-urlencoded
#[get("parse_form_get")]
pub async fn parse_form_get(mut req: Request) -> impl Responder {
    let user = req.parse::<FormParams>().await?;
    /*
       .....
    */
    Ok::<_, Error>((200, Json(user)))
}

// Context-Type : application/json
#[utoipa::path(
    post,
    path = "/user/parse_json",
    tag = "parse request body",
    request_body(
        content = JsonParams,
        content_type = "application/json",
    ),
    responses(
        (status = 201, description = "JsonParams item created successfully", body = JsonParams),
        (status = 409, description = "JsonParams already exists")
    )
)]
#[post("parse_json")]
pub async fn parse_json(mut req: Request) -> impl Responder {
    let user = req.parse::<JsonParams>().await?;
    /*
        ......
    */
    Ok::<_, Error>((200, Json(user)))
}

// Context-Type : multipart/form-data Form Fields
#[post("multipart_form")]
pub async fn multipart_form(mut req: Request) -> impl Responder {
    let form_data = req.parse::<FormParams>().await?;
    /*
       ....
    */
    Ok::<_, Error>((200, Json(form_data)))
}

// Context-Type : multipart/form-data Files
#[post("multipart_file")]
pub async fn multipart_file(mut req: Request) -> impl Responder {
    let file = req.file("file").await?;
    let file_name = file.name()?;
    let file_name = file_name.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
#[utoipa::path(
    get,
    path = "/base/header",
    tag = "request headers",
    responses(
        (status = 200, description = "header successfully", body = String),
        (status = 404, description = "header failed")
    ),
)]
#[get("/header")]
pub async fn header(req: Request) -> impl Responder {
    let host = req.header::<String>("host")?;
    let user_agent = req.header::<String>("user-agent")?;
    /*
       .....
    */
    Some((
        200,
        format!("host = {} , user_agent = {}", host, user_agent),
    ))
}

// Url Path Params
#[utoipa::path(
    delete,
    path = "/base/param/{name}/{age}",
    tag = "url path params",
    params(
        ("name" = String, Path, description = "Url Path Params name"),
        ("age" = u16, Path, description = "Url Path Params age"),
    ),
    responses(
        (status = 200, description = "successfully, response = String"),
        (status = 404, description = "failed")
    )
)]
#[delete("param/:name/:age")]
pub async fn param(req: Request) -> impl Responder {
    let name = req.param::<String>("name")?;
    let age = req.param::<u16>("age")?;
    /*
       .....
    */
    Some((200, format!("name = {} , age = {}", name, age)))
}

// Url Query Params
#[utoipa::path(
    get,
    path = "/base/query",
    tag = "url query params",
    params(
        ("name" = Vec<String>, Query, description = "Url Query Params name"),
        ("age" = u16, Query, description = "Url Query Params age"),
    ),
    responses(
        (status = 200, description = "successfully, response = String"),
        (status = 404, description = "failed")
    )
)]
#[get("/query")]
pub async fn query(req: Request) -> impl Responder {
    let name = req.query::<Vec<String>>("name")?;
    let age = req.query::<u16>("age")?;
    let key = req.get::<&str>("key")?;
    println!("app_state = {}", key);
    /*
       .....
    */
    Some((200, format!("name = {:?} , age = {}", name, age)))
}

#[get("/set_cookies")]
pub async fn set_cookies(_req: Request) -> impl Responder {
    let mut cookie1 = Cookie::new("hypers", "hypers2023");
    cookie1.set_path("/user");

    let mut cookie2 = Cookie::new("rust", "rust2023");
    cookie2.set_path("/user");

    let mut cookie_jar = CookieJar::new();
    cookie_jar.add(cookie1);
    cookie_jar.add(cookie2);
    (200, cookie_jar)
}

#[get("/html")]
pub async fn html(_req: Request) -> impl Responder {
    Text::Html("<html><body>hello</body></html>")
}

// 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::<String>("name").unwrap_or_default();
    while let Ok(msg) = ws.receive().await {
        if let Some(msg) = msg {
            match msg {
                Message::Text(text) => {
                    let text = format!("{},{}", name, text);
                    ws.send(Message::Text(text)).await?;
                }
                Message::Close(_) => break,
                _ => {}
            }
        }
    }
    Ok(())
}

// Middleware Function
pub async fn stat_time(req: Request, netx: Next) -> Result {
    // Before executing the request processing function
    let start_time = 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
    );
    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
}

pub async fn app_state(mut req: Request, next: Next) -> Result {
    let user = JsonParams {
        id: Some(1),
        name: Some("admin".to_owned()),
        age: Some(21),
    };
    req.set("user", user);
    req.set("key", "Hello World");
    next.next(req).await
}

#[derive(OpenApi)]
#[openapi(
    info(title = "Base Api", description = "Base Api description"),
    paths(header, param, query),
    tags(
        (name = "base", description = " base router")
    )
)]
struct ApiDoc1;

#[derive(OpenApi)]
#[openapi(
    info(title = "User Api", description = "User Api description"),
    paths(parse_header, parse_param, parse_query, parse_form_patch, parse_json),
    components(schemas(HeaderParams, PathParams, QueryParams, FormParams, JsonParams)),
    tags(
        (name = "user", description = " user router ")
    )
)]
struct ApiDoc2;

// Write router like a tree
fn main() -> Result<()> {

    // The Root Router
    let mut root = Router::new("");
    root.get("/*", StaticDir::new("src").listing(true));
    root.ws(":name/ws", websocket);

    // Add Middleware  ( Middleware can be added to any routing node )
    root.hook(logger, vec!["/param/:name/:age"], None);

    // The Sub Router
    let mut base = Router::new("base");
    // Add Middleware  ( Middleware can be added to any routing node )
    base.hook(app_state, vec!["/"], None);
    base.services(routes!(header, param, query, set_cookies, html))
        .openapi(ApiDoc1::openapi());

    // The Sub Router
    let mut user = Router::new("user");
    // Add Middleware  ( Middleware can be added to any routing node )
    user.hook(stat_time, vec!["/user"], None);
    user.services(routes!(
        parse_cookies,
        parse_header,
        parse_param,
        parse_query,
        parse_form_patch,
        parse_form_get,
        parse_json,
        multipart_form,
        multipart_file
    ))
    .openapi(ApiDoc2::openapi());

    // Add sub router to the root router
    root.push(base);
    root.push(user);

    // Accessing in a browser  http://127.0.0.1:7878/swagger-ui/
    root.swagger("swagger-ui");

    println!("root router = {:#?}", root);

    // Start Server
    // Not Use SSL/TLS
    #[cfg(not(any(feature = "rustls", feature = "native_tls")))]
    {
        hypers::run(root, "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());
        hypers::run(root, "127.0.0.1:7878", tls)
    }

    // Use SSL/TLS
    #[cfg(feature = "native_tls")]
    {
        let tls = NativeTls::from_pkcs12(include_bytes!("./certs/identity.p12"), "mypass")?;
        hypers::run(root, "127.0.0.1:7878", tls)
    }
}