1个不稳定版本

0.1.2 2023年5月20日

#735HTTP服务器

MIT 许可证

13KB
246

Jast

Jast是一个开源的极简Rust库,用于构建高性能Web服务器。Jast旨在易于使用且性能出色,它利用了Rust在安全性和内存使用等领域的优势。

Jast (版本:0.1.2)

安装

Cargo.toml
[dependencies]
jast = "0.1.2"

设置

基本服务器

fn controller() -> RouteResponse<'static> {
        let response = RouteResponse {
            method: "GET",
            res: Res::json(vec![
                ("name", DataTypes::Str(String::from("Hello"))), 
                ("lastname", DataTypes::Str(String::from("World"))), 
                ("id", DataTypes::Int(i32::from(1)))
            ])
        };

        response
}

let routes = vec![
        Http::route("/", controller())
];

let settings = Builder::new("localhost:8080", routes);

Http::create_server(
   settings
)

服务器设置

默认情况下,它使用CPU核心数来确定工作线程数。这可以按照以下方式更改

let settings = Builder::new("localhost:8080", routes).worker_threads(4);

用法

新建路由

用于创建新路由的路由结构体

pub struct Routes<'a> {
    pub method: &'a str, 
    pub route: &'a str,
    pub response: &'a str,
}
Http::route(method, route, response)

响应

Json

Res::json(vec![((name, value)))])

数据类型结构体到值的结构体

Res::json(vec![("name", DataTypes::Str(String::from("Hello")))])

文件:从项目根目录

Http::route("/html", (|| RouteResponse { method: "GET", res: "src/index.html"})()) 

示例

use jast::{Http, Res, DataTypes, RouteResponse, Builder};

fn main() {
    fn controller() -> RouteResponse<'static> {
        let response = RouteResponse {
            method: "GET",
            res: Res::json(vec![
                ("name", DataTypes::Str(String::from("Juan"))), 
                ("lastname", DataTypes::Str(String::from("Alberto"))), 
                ("id", DataTypes::Int(i32::from(1)))
            ])
        };

        response
    }

    let routes = vec![
        Http::route("/", controller()),
        Http::route("/hola", 
            (|| RouteResponse { method: "GET", res: Res::json(vec![("name", DataTypes::Str("Juan".to_string()))]) })()),
        Http::route("/html", 
            (|| RouteResponse { method: "GET", res: "src/index.html"})())
    ];


    let settings = Builder::new("localhost:8080", routes).worker_threads(4);

    Http::create_server(
       settings
    )
}

贡献

依赖项

~1.4–2.3MB
~40K SLoC